JQuery: how to make a callback after attr?

I want to change img src first and then execute the others. Something like that -

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

how will i do this

+5
source share
3 answers

Perhaps another line of code?

$('#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 are probably looking for an event load:

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

Note that an event handler load(...)was created before the attribute was changed srcusing attr- in case of image caching.

If you do this several times, you might want to look into unbind.

+23
source

onload, . :

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

.attrperformed immediately. Most likely, you really need to wait until the image is loaded, and then do something.

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

All Articles