Question

So I am very much a beginner at JS and I wrote a really simple script for randomly selecting a background image for pages on my site. The problem is sometimes when navigating to a new page or reloading the same page the same image will be randomly selected. I need some way of storing which image has just been used as the background in the browser.

Here is my script:

    var rand_image_bg = function(){
        $('<div id="background_container"><img class="background_image"/></div>').insertAfter("#menu");
        var image_src = ["Images/spaceship.jpg", "Images/hallway.jpg", "Images/steampunk.jpg", "Images/mine.jpg"];
        var selected_bg_image = Math.floor((Math.random()*image_src.length)+1)-1;
        console.log($("body").data("bg_image"));
        if (selected_bg_image == /*Number of the previous background image*/) {
            selected_bg_image = image_src.length-1-selected_bg_image;
        }
        $(".background_image").attr("src",""+image_src[selected_bg_image]+"");
        /*Record number of the new background image for later*/
    }

Any advice anyone can give me would be great. Please keep in mind that I am a beginner so keep it simple. THANKS!

Was it helpful?

Solution

Following adeno's advice I wrote this and it seems to work:

    var rand_image_bg = function(){
        $('<div id="background_container"><img class="background_image"/></div>').insertAfter("#menu");
        var image_src = ["Images/spaceship.jpg", "Images/hallway.jpg", "Images/steampunk.jpg", "Images/mine.jpg"];
        var selected_bg_image = Math.floor((Math.random()*image_src.length)+1)-1;
        if (selected_bg_image == localStorage.bg_image) {
            selected_bg_image = image_src.length-1-selected_bg_image;
        }
        $(".background_image").attr("src",""+image_src[selected_bg_image]+"");
        localStorage.bg_image = selected_bg_image;
    }
    rand_image_bg();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top