3

I want to get a image's width when a page loaded. Because the image's width is used to judge some conditions, the logic like this:

var width = $('img').width();
var height = $('img').height();
if(width > height){
  //do fn1
}else{
  //do fn2
}

Here is a link to simulate my problem. I knew if use function setTimeout delay to get image width is available but it's not precise.

Todd Mark
  • 1,847
  • 13
  • 25

4 Answers4

3

This is the example given in the jQuery documentation:

... a page with a simple image:

<img src="book.png" alt="Book" id="book">

The event handler can be bound to the image:

$( "#book" ).load(function() {
  // Handler for .load() called.
});

As soon as the image has been loaded, the handler is called.

http://api.jquery.com/load-event/

Here's more on the topic that will help you out:

How to get image size (height & width) using JavaScript?

Community
  • 1
  • 1
shmuli
  • 5,086
  • 4
  • 32
  • 64
2

Or if you are awesome, you could create the image element, add a source, and do something when it's loaded. No jQuery needed.

var image = new Image();
image.onload = function() {
    alert('image loaded');
};
image.src = 'image/image.jpg';
Tony Gustafsson
  • 828
  • 1
  • 7
  • 18
0
object.onload=function(){
var width = $('img').width();
height = $('img').height();
};

You can try this onload function.

0

You should check image width and height after image is loaded. With JQuery you can check page load like this:

    $('img').load(function() {
          var width =  $('img').width();
          var height = $('img').height();

          if(width > height){
            console.log(1);
          }else{
            console.log(2);
          }
    });

JS BinExample Here

Shalva Kakauridze
  • 1,225
  • 4
  • 12
  • 23