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")
})
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)