tags:

views:

111

answers:

3

a) I have 100 body-background images

b) and a single link

The background image should change to the next one in the lot every time the link is clicked, going thru the lot one by one (would be nice if the name/number of current image also is displayed).

The images are all in a dedicated directory. jQuery is already loaded.

Anyone know where I can find the code to do this simply?

All the best...

+1  A: 
var allImages = ["path/to/image2", "path/to/image1"];


$(document).ready(function() {
    $("#theLink").click(function() {
        var newImageLink = allImages.pop();
        $("body").css("background-image", "url(" + newImageLink + ")");
    });
});
Georg
A: 

(added counter to gs' answer)

var allImages = ["path/to/image2", "path/to/image1"];
var counter = 0;


$(document).ready(function() {
    $("#theLink").click(function() {
        var newImageLink = allImages.pop();
        $("body").css("background-image", "url(" + newImageLink + ")");
        $("#displayhere").html("<b>"+ counter +"</b>");
        counter = counter + 1;
    });
});
Shadi Almosri
A: 

You don't necessarily need to hard code the path to your images that way. You can name your images something like image_xxx.png, 1 - 100 and refer to that name in one place. That way if you ever need to change the name, you can easily do it in one place. Furthermore, make sure that the href attribute of the anchor tag is set to # to prevent page reloads on each click.

Here's a more complete solution that also does range checking and it wraps around when we reach our limit:

<script language="javascript" type="text/javascript">
<!--    
    var ctr = 0;

    $(document).ready( function () {
     nextBg();
    });

    function nextBg()
    {
     ++ctr;

     if( ctr <= 100 )
     {
      $("body").css( "background-image", "url(images/image_" + ctr + ".png)" );
      $("#message").text("Current image: " + "image_" + ctr + ".png");
      if( ctr == 100 )
       ctr = 0;
     }
    }
//-->
</script>
</head>

<body>
    <div>
       <span id="message"></span><br />
       <a href="#" onclick="nextBg();" />Next</a>
    </div>
</body>
zdawg
Thank you all for your kind responses.I owe 'zdawg' an extra strong 'thank you' for his thoughtful and informative reply and his code which does everything I asked for and works like a charm.Issue resolved. The 'stackoverflow' community rocks.All the best...
terrestrial