Change img src and width

I am changing scr for img tag using jQuery like

$("#img1").attr("src", "pic1.png"); 

after that, I try to get the img width (it is not set in html)

 $("#img1").width(); 

It seems that the width does not change with src, am I missing something? thanks.

+4
source share
1 answer

If you try to do this immediately, it may be because the image is not yet fully loaded.

Add one load handler to the image using .one() .

 $("#img1").attr("src", "pic1.png").one('load',function() { alert($(this).width()); }); 

or in case of image caching, you can try the following:

 $("#img1").attr("src", "pic1.png").each(function() { if( this.complete ) { alert($(this).width()); } else { $(this).one('load',function() { alert($(this).width()); }); } }); 

As @Humberto noted, you used scr instead of the correct src .

+4
source

Source: https://habr.com/ru/post/1340829/


All Articles