Fred
Fred

Reputation: 1234

change img src and width

I change the scr of an img tag using jQuery, such as,

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

after this, I try to get the width of img (it's not set in html),

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

it seems the width is not changed with the src, did I miss something? thanks.

Upvotes: 4

Views: 865

Answers (1)

user113716
user113716

Reputation: 322502

If you're trying to do it immediately, it may be because the image isn't fully loaded yet.

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

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

or in case the image was cached, you can try this:

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

As noted by @Humberto, you were using scr instead of the proper src.

Upvotes: 4

Related Questions