user3188159
user3188159

Reputation:

Randoming image with javascript and apply a background color to the page according the randomed image

Title says all. I have the following JS code:

function randomImg(){
var myImages = new Array();
myImages[1] = "images/image1.gif";
myImages[2] = "images/image2.gif";
var rnd = Math.floor(Math.random() * myImages.length);
if(rnd == 0){
rnd = 1;
}
document.write('<img src="'+myImages[rnd]+'" alt="image" style="border: 0;" />');
}

Both images have different content, so the page background image should be different also. Here's the CSS for the page background:

/* image1.gif */
body {
background-color: #FBFBFB;
}

/* image2.gif */
body {
background-color: #FFFFFF;
}

Also I'd like not to use jQuery because I've already added a library. So the only acceptable jQuery code should be the one compatible with: jquery-1.4.3.min.js

Upvotes: 0

Views: 126

Answers (1)

antyrat
antyrat

Reputation: 27765

Don't use document.write as this will clear your document content. To make different background based on random number you can do for example:

if(rnd == 0){
    rnd = 1;
    document.body.style.background = '#FBFBFB';
} else {
    document.body.style.background = '#FFFFFF';
}

Or using jQuery:

if(rnd == 0){
    rnd = 1;
    $( 'body' ).css( 'background', '#FBFBFB' );
} else {
    $( 'body' ).css( 'background', '#FFFFFF' );
}

Compatible with jQuery 1.4.3 too.

As you are using jQuery, you can avoid using document.write by

$( 'body' ).append( '<img src="'+myImages[rnd]+'" alt="image" style="border: 0;" />' ); 

Full edited code should be:

function randomImg() {
    var myImages = [];
    myImages[0] = "images/image1.gif";
    myImages[1] = "images/image2.gif";
    var rnd = Math.floor(Math.random() * myImages.length);
    if (rnd == 0) {
        rnd = 1;
        $('body').css('background', '#FBFBFB');
    } else {
        $('body').css('background', '#FFFFFF');
    }
    $('body').append('<img src="' + myImages[rnd] + '" alt="image" style="border: 0;" />');
}

Upvotes: 2

Related Questions