Reputation: 272264
I want to load html , and then get the true image height.
$("#cover").html(stuff); //this has the image inside it
$(function(){
console.log($("#cover img").height()); //sometimes it's 0
});
For some reason, height is sometimes 0. Could it be because the image hasn't been fully loaded yet, and JQuery sees it as 0? If so, how do I overcome this? Is there a callback or something when the image is loaded?
Upvotes: 1
Views: 1799
Reputation: 884
Don't you mean to do something like this?
jQuery("#myImg")[0].naturalHeight
better still don't use overhead of jQuery when possible.
document.getElementById('myImg').naturalHeight
Upvotes: 0
Reputation: 639
Here is a piece of small code i used before hope this will help you
On my displayed image when mouse is in call this function
function MouseIn()
{
var src;
//to get original image size
var img =$(this);// displayed image
var theImage = new Image();// create a cache image
var imgsource =img.attr("src");// take the src of displayed image
theImage.src = imgsource;// give cached image the source of displayed image
var original_height = theImage.height// take height of image from the source
var original_width = theImage.width;//take width of image from the source
// to get the displayed image size
var Image_displaysize_width= img.width();
var Image_displaysize_height= img.height();
}
Upvotes: 0
Reputation: 6166
try using attr() to get the height:-
$("#yourElemengtID").attr('height')
Upvotes: 0
Reputation: 3558
try to using load method
method that we can take advantage of to make this work the way we want it too.
The problem we have right now is that, in the Webkit browsers, the jQuery code runs when the DOM is ready and the DOM is ready before the image has been loaded. So the code runs but since there’s no image to get a width of, we get 0 for the image’s width. We can use the load method to make the code wait until the window has loaded entirely before it runs.
$(window).load(function() {
console.log($("#cover img").height());
});
Upvotes: 0
Reputation: 191
Why do the console.log inside an anonymous function? Have you tried this?
$("#cover").html(stuff); //this has the image inside it
console.log($("#cover img").height());
Upvotes: 1
Reputation: 1168
You can use the .load() method of jQuery
$('#cover').html(stuff);
$('#cover img').load(function () {
console.log($(this).height());
};
Upvotes: 3
Reputation: 119877
//locate the image(s)
$("#cover img").each(function(){
//Build a new Image Object outside the DOM
//that way, CSS won't affect it
var img = new Image();
//add a callback when loaded
img.onload = function(){
//your width and height
//img.width
//img.height
}
//use the image src to load
//use attr() to resolve path issues across browsers
img.src = $(this).attr('src');
});
Upvotes: 0