April 18, 2011

Why does this attribute not change?

Question by daniel.tosaba

In the code below the last line is not setting the src attribute. Why?

$("div.galerina").each(function(){
    var gal=$(this);
    var bullet=gal.children("img.galerina1");
    var width=12*(gal.children("img").size())+'px';
    gal.children("p").css({width:width})

    gal.children("img").each(function(){
    var img=$(this);
    gal.children("p").append("<img class='bullet' src='images/bullet1.png'></img>");
    $("img.bullet").last().click(function(){
        bullet.animate({opacity:0},300,function(){
            bullet.css({display:'none'});
            bullet=img;
            img.css({display:'block'});
            img.animate({opacity:1},300);
        });

    })
})
gal.children("img.bullet").first().attr("src","images/bullet2.png")
})

LIVE VERSION HERE!!!

Answer by Frédéric Hamidi

gal in not in scope anymore when you try to use it to change the bullet image.

You’ll need to either move your last line inside the function passed to $("div.galerina").each(), or reinitialize gal before you use it:

$("div.galerina").each(function() {
    var gal = $(this);
    gal.children("img.bullet").first().attr("src", "images/bullet2.png");
});

Answer by Starx

Just try it using gal.children because gal is already initiated at $(this). No need to do $(gal)

Same goes with $(img)

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!