Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.

Solution 2:

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

Solution 3:

.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);

Post a Comment for "Jquery: How To Do A Callback After Attr?"