Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: how to do a callback after attr?

Tags:

html

jquery

css

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?

like image 488
Avisek Chakraborty Avatar asked Oct 21 '11 14:10

Avisek Chakraborty


3 Answers

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.

like image 82
Richard JP Le Guen Avatar answered Nov 07 '22 04:11

Richard JP Le Guen


.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);
like image 44
Kevin B Avatar answered Nov 07 '22 04:11

Kevin B


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");
});
like image 44
Jacob Mattison Avatar answered Nov 07 '22 03:11

Jacob Mattison