Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/jQuery: How to detect img is fully downloaded or not?

All I need to do is locate image at the center of its parent div.
First, I tried this.

$(document).ready(function() { 
    $('#image1').css({
    'top': 50%, 'left': 50%,
    'margin-top': (-$('#image1').height()/2) + 'px',
    'margin-left': (-$('#image1').width()/2) + 'px'
    }); 
});

It failed cause $('#image1').height() and width() gives 0 before it is fully downloaded.
So I tried to keep inspecting size of the image until it has specific width and height.
like,

function inspectSize() { return ($('#image1').width() != 0); }
function setPosition() {
    if(!inspectSize()) {
        setTimeout(setPosition, 1000);
        return;
    }
    $('#image1').css({
        'top': 50%, 'left': 50%,
        'margin-top': (-$('#image1').height()/2) + 'px',
        'margin-left': (-$('#image1').width()/2) + 'px'
    }); 
}
$(document).ready(setPosition);

Still it doesn't work.
because $('#image').width() returns 28px before it is downloaded in IE8 (by the way, IE7 was fine)

So I finally tried waitForImages jQuery plugin like this,

$(document).ready(function() {
    $('#image1').waitForImages(function() {
         setPosition(); // without inspectSize() 
    });
});

It works fine with cached images, but doesn't work with non-cached images.
The function is called before Image1 has width and height.

What should I do?

like image 721
Sang Avatar asked Feb 22 '23 01:02

Sang


2 Answers

You should be able to just bind your repositioning callback to the load event handler.

So in your last example:

$('#image1').load(function() {
     setPosition(); // without inspectSize() 
});

Where #image1 points to your image tag. Alternatively, as you mention the #image1 might just be a container then:-

$('#image1 img').load(function() {
     setPosition();
});

Update jfriend00 makes a good point below, in that 'load' will only fire when an image is added to the DOM, not if it already exists on the page at the time your JavaScript is run.

To cover both scenarios, you can do this:

var img = $('#image1');

if (img.prop('complete')) {
     setPosition();
} else {
     img.load(function() { setPosition(); });
}

The prop('complete') check will return true if the image already exists, and if it doesn't we bind the 'load' event handler.

like image 175
isNaN1247 Avatar answered Feb 24 '23 17:02

isNaN1247


a simple example is to bind the load event to the image. I always do the following

<img data-src="image.jpg" />

note that i don't set the src attribute yet

$(function() {
    $("img").each(function() {
        $(this).load(function() {
            alert('ready to call $(this).width()');
        }).prop("src", $(this).prop("data-src"));
    });
});

the .prop("src", $(this).prop("data-src")); set's the new src after the load event is binded

like image 21
Manuel van Rijn Avatar answered Feb 24 '23 17:02

Manuel van Rijn