The reason your code doesn't work is that you have a single "numBackgrounds"
variable shared throughout all the code. You may increment this in a loop,
but then later on when the .click() callback is called, numBackgrounds has
already been incremented all the way to 6.

Also your loop should probably start at 1 instead of 5.

One way to code it is like this:

    $(document).ready(function(){
    
        for( var n = 1;  n < 6;  ++n )
            setupChanger( n );
    
        function setupChanger( n ) {
            $( '#bgChangerAnchor' + n ).click( function () {
                $('#mainContainer').css(
                    'background','url(backgrounds/bg_' + n + '.jpg)'
                );
            });
        }
    
    });

By calling the setupChanger() function each time through the loop, the loop
variable is captured in each function call, so when n (I changed the name
for brevity) is later used in the click event handler, it uses *that* value
of n.

This is called a "closure" - it's one of the best features of JavaScript:

http://www.google.com/search?q=javascript+closure

-Mike

> From: eludlow
> 
> This might not be possible at all - I've tried the code and 
> it's not working so I'm guessing it probably isn't possible, 
> but it could also be I've done something wrong!
> 
> This is the code i have that works:
> 
> [code]
> $(document).ready(function(){
> 
> $("#bgChangerAnchor1").click(function () {
>       
> $("#mainContainer").css("background","url(backgrounds/bg_1.jpg)");
> });
> 
> 
> $("#bgChangerAnchor2").click(function () {
>       
> $("#mainContainer").css("background","url(backgrounds/bg_2.jpg)");
> });
> 
> 
> $("#bgChangerAnchor3").click(function () {
>       
> $("#mainContainer").css("background","url(backgrounds/bg_3.jpg)");
> });
> 
> 
> $("#bgChangerAnchor4").click(function () {
>       
> $("#mainContainer").css("background","url(backgrounds/bg_4.jpg)");
> });
> 
> 
> $("#bgChangerAnchor5").click(function () {
>       
> $("#mainContainer").css("background","url(backgrounds/bg_5.jpg)");
> });
> 
> });[/code]
> 
> But I was hoping to condense it down into this:
> 
> [code]
> $(document).ready(function(){
> 
> for (numBackgrounds=5;numBackgrounds<6;numBackgrounds++) {
> 
>       $("#bgChangerAnchor"+numBackgrounds).click(function () {
>               $("#mainContainer").css("background","url(backgrounds/
> bg_"+numBackgrounds+".jpg)");
>       });
> 
> }
> 
> 
> });
> [/code]
> 
> Any pointers / tips about this would be brilliant, thanks.
> 
> All the best,
> Ed Ludlow
> 

Reply via email to