0

bar1

I want to find out dimension of this image in px.

In jQuery

var h = $("img").height();
var w = $("img").width();
alert(h +"px", w +"px");

In PrototypeJS

var h = $('img').getHeight();
var w = $('img').getWidth();
alert(h);
alert(w);

using this two I get dimensions as 20px and 1350px for every image with their original different dimensions.

akietta
  • 261
  • 1
  • 3
  • 11

2 Answers2

0

So you want to get actual size of the image, not the size that it was rendered to web browser? If that's the case, these code might help you:

var img = new Image();
img.onload = function() {
  alert(this.width + 'x' + this.height);
}
img.src = $("#myimg").attr('src');

Reference here: How do I get actual image width and height using jQuery?

Community
  • 1
  • 1
Doan Cuong
  • 2,486
  • 4
  • 20
  • 37
0

It's because $('img') will target every image in your DOM, the 20px and 1350px is the dimension of your first image. You need to use each() in this case:

$("img").each(function() {
    $(this).click(function() {
        var w = $(this).width(),
            h = $(this).height();
        alert(h +"px " + w +"px");
    });
});

Fiddle

But I'd suggest you giving a class to your images instead of just selecting pure <img> tag:

<img class="image" />

Then you can do:

$(".image").click(function() {
    var w = $(this).width(),
        h = $(this).height();
    alert(h +"px " + w +"px");
});

Fiddle

Eli
  • 14,537
  • 5
  • 56
  • 77