Avisek Chakraborty
Avisek Chakraborty

Reputation: 8309

Jquery: how to do a callback after attr?

I want to change the img src at first then accomplish others. Something like this-

$('#bgImage').attr('src','images/'+bgImage, function() {
    alert('inside');
});

how will i do that?

Upvotes: 9

Views: 18068

Answers (3)

Kevin B
Kevin B

Reputation: 95023

.attr is executed immediately. More than likely what you actually need is to wait until the image is done loading, then do something.

var $img = $("#bgImage");    
$img.load(function(){
    // image is done loading, do something
    alert("worky (not cached)")
});
$img.attr('src','images/' + bgImage);

Upvotes: 6

Richard JP Le Guen
Richard JP Le Guen

Reputation: 28753

Another line of code perhaps?

$('#bgImage').attr('src','images/'+bgImage),
$('#searchPin').css("top",y+"px");
$('#searchPin').css("left",x+"px");

If you want to wait for the image to load, you're probably looking for the event load:

$('#bgImage').load(function() {
    $('#searchPin').css("top",y+"px");
    $('#searchPin').css("left",x+"px");
}).attr('src','images/'+bgImage);

Note that the load(...) event handler was created before changing the src attribute using attr - in case the image has been cached.

If you're doing this more than once you might want to look into unbind too.

Upvotes: 27

Jacob Mattison
Jacob Mattison

Reputation: 51052

When you change the image's source, it will be loaded, and will fire an onload event when it is done. So:

$('#bgImage').attr('src','images/'+bgImage).load(function() {
    $('#searchPin').css("top",y+"px");
    $('#searchPin').css("left",x+"px");
});

Upvotes: 9

Related Questions