Randomize background image using button onClick event - html

I want to randomize the background image when the user clicks a button.
Here's what I have.
Every time the button at the bottom right is cliked, I want to randomize the background image from a set array of externally hosted images.
How can I achieve that? (Without PHP, if possible.)

Try this method:
<script type="text/javascript">
function randomImg1() {
var myImages1 = new Array ();
myImages1[1] = "img/who/1.jpg";
myImages1[2] = "img/who/2.jpg";
myImages1[3] = "img/who/3.jpg";
var rnd = Math.floor( Math.random() * myImages1.length );
if( rnd == 0 ) {
rnd =1;
}
html_code = '<img class="who" src="' + myImages1[rnd] + '" />";
document.write(html_code);
}
</script>
You can also check out this
// EDIT -- By Pipskweak
instead of
html_code = '<img class="who" src="' + myImages1[rnd] + '" />";
document.write(html_code);
we could do this;
document.getElementsByTagName("body")[0].setAttribute('style','background-image: url(' + myImages1[rnd] + ')');
after all, background image was mentioned.

Related

Javascript ReGEX for JSON

This is all so confusing, I've seen so many examples of how to do different things and cannot seem to find a valid example for what I am trying to do.
I'm using the YQL for the stock quotes only to get just the major indexes, DOW S&P 500 and NASDAQ.
The project is getting the data and working, but I need to determine if the stock value is returning + or - (up or down).
if the market is up or flat, I want to add a CSS class to set it to green, if it is down, I want to set a CSS to red.
One other issue, this only seems to work when I place the function between the head and body, not in the head, not in the body.
<script type="text/javascript">
function stock_quotes(obj)
{
var items = obj.query.results.quote;
var output = '';
var num_quotes = items.length;
items[0].symbol = "DOW ";
items[1].symbol = "NASDAQ ";
items[2].symbol = "S&P 500 ";
//var posquote = {"\d\.?\d{0,9}\.\d{0,9}\s\+"};
//var negquote = {"\d\.?\d{0,9}\.\d{0,9}\s\-"};
for (var i = 0; i < num_quotes; i++) {
var link = items[i].url;
var symbl = items[i].symbol;
var Change_PercentChange = items[i].Change_PercentChange;
var LastTradePriceOnly = items[i].LastTradePriceOnly;
output += "<table><tr><td>" + "<a href='" + link + "'>" + symbl + "</a>" + LastTradePriceOnly + " " + Change_PercentChange + "</td></tr></table>";
}
// Place news stories in div tag
document.getElementById('results').innerHTML = output;
}
This is the HTML with the query
<div id='results'></div>
<script type="text/javascript" src='http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22DOW%22%2C%22%5EIXIC%22%2C%22%5EGSPC%22)%0A%09%09&format=json&diagnostics=true&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback=stock_quotes'></script>
Ideally I'd like to predefine the html elements which would make it easier to set the css class but one headache at a time.
In the end, this seemed to work just fine
var match_nas_neg = nas_result.match(/\-/);

How to scale inline SVG

I want to scale inline SVG document in html. I have code like this:
var svg_width = svg.attr('width');
var svg_height = svg.attr('height');
function resize(width, height) {
svg.attr('width', width).attr('height', height);
var group = svg.find('#resize_group');
if (!group.length) {
group = svg.children().not('metadata, defs').wrapAll('<g/>').
parent().attr('id', 'resize_group');
}
var matrix = svg[0].createSVGMatrix();
//var matrix = group[0].getCTM();
matrix.a = width/svg_width;
matrix.d = width/svg_height;
group.attr('transform', matrix.asString());
}
SVGMatrix.prototype.asString = function() {
return 'matrix(' + this.a + ' ' + this.b + ' ' + this.c + ' ' + this.d +
' ' + this.e + ' ' + this.f + ')';
};
NOTE: I need to transform the elements inside svg because otherwise the image is trimmed.
but when I call resize function whole svg disappear. I've save svg to file and open it in Inkscape and it look normal (it's scaled). Why the svg disappear? (I tested on Firefox, Chrome and Opera)
I found quick hack, to replace svg with text of the svg to force redraw.
$.fn.xml = function() {
return (new XMLSerializer()).serializeToString(this[0]);
};
$.fn.SVGRedraw = function() {
return $(this.xml()).replaceAll(this);
};

remove span by class from $(this).html()

Basically my search returns search results in spans, then when one is clicked, a new span is added to another div with a select input and hidden input so all the selected features can be posted as an array.
My question is, $(this).html() now includes a span of class alias_span. Which I don't want to appear in the new span. How do I remove it before inserting the contents of the clicked span into the new span
$(".minisearch_res").live('click', function() {
// when a search result is clicked we disable the submit button,
// append a span to the left column with an id,
// a select input to select standard/optional and
// a hidden field with the required information to save and something to
// show the user
var id = $(this).attr('id');
var html = "<span class= \"added_result_cont\" id=\"" + id + "_cont\">";
html += "<select name='" + id + "_sel'>";
html += "<option value=\"none\" selected=\"selected\"></option>";
html += "<option value=\"std\">Standard</option>";
html += "<option value=\"opt\" >Optional</option>";
html += "</select>";
html += "<span id= \"" + id + "\" class=\"added_result\">";
html += "<input type=\"hidden\" name=\"selectedfeat[]\" value=\"" + id + "\">";
html += $(this).html() + "</span></span>";
$('#div_apply_to').append(html);
$(this).remove();
$('#search_input').trigger('keyup');
$("input[type=submit]").attr("disabled", "disabled");
});
Update: here's the html of the span
<span class="minisearch_res" id="opt_1">Anti-Lock Brakes<br><span style="padding-left:20px" class="alias_span"><i>abs</i></span><br></span>
<div></div>
Add it to the dom, then remove it.
var htm = (
'<span class="foo">foo</span>' +
'<span>bar</span>' +
'<span>bar</span>' +
'<span>bar</span>' +
'<span>bar</span>'
);
var $el = $("div").append(htm);
console.log($el.html());
$el.find('.foo').remove();
console.log($el.html());
http://jsfiddle.net/chovy/w2HdE/
Got a tidy cross browser solution, which I'm very proud of :)
var temp = $(this);
temp.children('.alias_span').remove();
$('#div_apply_to').append("...html..." + temp.html() + "...html...");
inspiration came from here:
Remove element from Ajax Response

Issue with adding a image at the end of tabs

I am trying to add add a button called shopping cart to my Tabs script. The new button is controlled if a checkbox is clicked. (Show). Im confused why the image is not showing. Any answers would be helpful.
Thank you.
Copy code
$(function() {
var $tabs = $('#tabs').tabs({cookie:{expires:1}});
$(".ui-tabs-panel").each(function(i){
var totalSize = $(".ui-tabs-panel").size() - 1;
var prevImage = "custom/images/prev.png";
var nextImage = "custom/images/next.png";
var atcImage = "custom/images/cart.jpg";
if (i != 0) {
prev = i;
$(this).append("<img href='#' class='prev-tab mover' rel='" + prev + "' src='" + prevImage + "'></img>");
}
if (i != totalSize) {
next = i + 2;
$(this).append("<img href='#' class='next-tab mover' rel='" + next + "' src='" + nextImage + "'></img>");
}
if (i > 1) {
atc = i + 2;
$(this).append("<img href='#' class='atc-tab mover' rel='" + next + "' src='" + atcImage + "'></img>");
}
$('input[name=FIELD_469]').click(function() {
if (this.checked) {
$("img[src*=cart]").show();
}
else {
$("img[src*=cart]").hide();
}
});
$('.next-tab, .prev-tab, .atc-tab').click(function() {
$tabs.tabs('select', $(this).attr("rel"));
return false;
});
});
Sorry, I can not ask for clarification because of low level of my rating, but there are several things that I have noticed and some recomendations.
1) Your selector should look like 'img[src~="cart"]'
http://api.jquery.com/attribute-contains-word-selector/
2) If you use class 'mover' only for that images, you can use '.mover' selector, otherwise just add new class name.
3) Test your JQuery objects with Google Chrome using console.log($("selector")) (Tools->Developer Tools->Console)
4) I think it should be not 'this' but $(this)
$('input[name=FIELD_469]').click(function() {
if (this.checked) {
$("img[src*=cart]").show();
}
If recommendations don't help, please provide more info about your form preferrably with example to see. Thanks

DataTables Combo box width

I'm applying DataTables
to utilize filtering, sorting and pagination on my HTML table. I'm using the following code to apply these attributes to the table:
$(document).ready(function() {
<!-- Sorting and pagination -->
var oTable = $('#mainTable').dataTable( {
"sPaginationType": "full_numbers",
"bJQueryUI": true
});
<!-- Filtering -->
$("thead td").each( function ( i ) {
<!-- Create and populate combo boxes -->
this.innerHTML = fnCreateSelect( oTable.fnGetColumnData(i) );
<!-- Filter data when selection changes -->
$('select', this).change( function () {
oTable.fnFilter( $(this).val(), i );
});
});
});
On the function call:
fnCreateSelect( oTable.fnGetColumnData(i));
..the combo boxes are filled with the data from the table. However, the boxes are automatically sized to contain the full length of the values (some of which span many lines) and so the columns are sized too big and run way off the page. I've determined it's not a CSS issue, so what I need is a way to make the combo boxes use multiple lines per entry, or only show a portion of the value so that I can fit all these columns on one page.
Thanks in advance!
Answer for anyone following this:
I changed the code in fnCreateSelect (where the combo boxes are built) to limit how much text is stored per value in the combo boxes as such:
function fnCreateSelect(aData) {
var r = '<select><option value=""></option>', i, iLen = aData.length;
for (i = 0; i < iLen; i++) {
// If string is a URL, handle it accordingly
if (aData[i].indexOf("href") != -1) {
var url = aData[i].substring(aData[i].indexOf('http'), aData[i].indexOf('">'));
r += '<option title="' + url + '" value="' + url + '">' + url.substring(0, 25);
if (url.length > 25)
r += '...';
}
else {
r += '<option title="' + aData[i] + '" value="' + aData[i] + '">' + aData[i].substring(0, 40)
if (aData[i].length > 40)
r += '...';
}
r += '</option>';
}
return r + '</select>';
}