How to get height of a 100% width image with auto height? - javascript

In this case, I set an image with width: 100% and height: auto (actual image size is 362x614). I need to get height of image for another step.
Here is my code:
<img class="phone" src="img/phone2.png">
and js:
$(document).ready(function() {
phoneSlider();
});
$(window).resize(function(){
phoneSlider()
});
function phoneSlider(){
var phoneMaskWidth = $(".phone").width();
var phoneMaskHeight = $(".phone").height();
console.log(phoneMaskWidth + "|" + phoneMaskHeight);
.......
}
Then, I check in the console, and the result: 362|0. Why is phoneMaskHeight showing 0 and how can I get the real height?

Move your code from $(document).ready() to $(window).load(). The browser needs to load the image (or at least the image header) before it can calculate its width and height. Document ready event can fire before the browser has chance to have a look at the image.
Demo here; change the image source (or empty browser cache), run and look at the console

use:
var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.height);
}
img.src = $(".phone").attr('src');
Working Fiddle

$("img.phone").on('load', function() { alert( this.height ); });
This worked for me.

Browsers load images asynchronously and until the image is fully loaded its height will be unknown.
As others have suggested you will need to attach your code to the "onload" event that is fired when the image is loaded, but that will force you to change your whole phoneSlider method. You will need to put everything that depends on the height of the image in the corresponding onload callback.
If you don't need to do your calculation as soon as the image is loaded, the Salman A's answer is the better approach - put your logic when the window#onload event is fired, this ensures all external resources (including images) are loaded.

$(document).ready(function(){
console.log($('#myimg').width() + 'x' + $('#myimg').height());
console.log($("#myimg").attr('src'));
})
working demo [http://jsfiddle.net/A5QJM/238/]

Related

document ready gives wrong selector height

I want to get proper height of my div element, so in code i Use:
$(document).ready(function() {
var h = $('.myElement.active').outerHeight(true);
alert('height:'+h);
... // further more code to work with height
}
But this element contains lots of images and seems like I got my alert with height lower than it should be because images can't stretch size of that element so fast. If I request height after couple seconds it will fire alert with correct height.
Question: How to get height and run my code with checking is all images been loaded and transitions if there some is done?
Sincerely,
Vitaly.
$(document).ready gets triggered by the time the DOM tree was successfully built, similar to calling a script at the very end of the <body>. At that time, images might still be loading, which means the height cannot be calculated yet.
Once the whole document, including images, is loaded, window.onload will be triggered.
window.onload = function() {
var h = $('.myElement.active').outerHeight(true);
alert('height:'+h);
... // further more code to work with height
}
use window.onload this fires after images have been loaded
window.onload = function() {
var h = $('.myElement.active').outerHeight(true);
alert('height:'+h);
}

Image Width and Height is 0 after setting div unvisible before load has finished

I load a lot of images to my site and it works fine if I'm patient. But sometimes I fire an action with myDiv.style.display = 'none'; in it during image load and then the image gets width=height=0, for all the images haven't been completed. When I make my div visible again I can't see them but identify by searching for width=height=0.
If I set the width and height to something bigger than 0, I see the images but in this way I lose the real size. I also tried to change image.src by adding something like myImage.src += "?t=random";. Doing this, myImage.onload function gets fired again but width and height are still 0.
How can I get the real size of the images or how can I force a reload?
You can attach an event to your image elements:
image.onload = function () { /* Your code here */ };
This will fire when the image is actually loaded.
Make sure this event is attached before you set the src element and make sure that your src is actually valid. You can check this in the Network panel in Google Chrome (F12 on Windows).
Taking a deeper look i found following Workaround.
When the image is loaded the first time, it has a valid width and height but doesn't get painted because of the div is not visible. When I make the div visible again and initiate the reload by changing the image URL like myImage.src+="?t=random" the image.onload gets fired with the image width and height of 0. So what I can do is just to save the original values and use them if needed.
// save or reload image size in case of load interruption
if (typeof this.orgWidth == 'undefined' && this.width>0) this.orgWidth = this.width;
if (typeof this.orgHeight == 'undefined' && this.height>0) this.orgHeight = this.height;
if (this.width==0) this.width=this.orgWidth;
if (this.height==0) this.height=this.orgHeight;

jQuery width() is incorrect on load

When I load my page and use $('div.logo').width() it returns a massive value of 6500, which is incorrect. The image is only 130 px wide.
But, if I use a setTimeout and check the $('div.logo').width() after a few seconds it returns the correct width.
Why would this be? All of my CSS should be already loaded so why would the few second pause make a difference?
You have to check the image width after the image has been loaded.
So either:
// NOTE: not $(document).ready
$(window).load(function() {
var width = $('.logo img').width();
});
Or
$('.logo img').load(function() {
var width = $(this).width();
});
should give the right width.
Set the width and height attributes to the image. You can specify the size in CSS too. Then the browser will know what size the image will be before it loads.
That's because an image is not loaded yet, so initial size is based on CSS or guessed. You can use:
$('.logo img').load(function() {
var width = $(this).width();
});
Image is getting loaded with GET method,
so you need to check it after,
$('.logo img').load(function(){
//your code
});
If you want your image gets loaded instantly you may go with BASE64 image.
For more detail Plase see here
it can be javascript modifying the layout of page, for example it can be script tags included on the bottom of the page, or any other javascript code executed on JQuery ready or load events. For example if this code appending html code it can affect width of you .logo div.
Another possibility is that your html is incorrect, to check this simply run any HTML validator like this http://www.freeformatter.com/html-validator.html. When taking HTML from your page for validation, be aware that some browsers fix the incorrect HTML, so better get it from your source code.

jQuery is only loading on resize and I want it to load on both resize and page load

I have two sections next to each other, the first with a flexible width image and the second with a series of elements. I want the second to adjust it's height to match the height of the image in the first. I managed to get some javascript working that looks at the height of the image and adjusts the height of second section. However, it only works on resize and I'm unable to get it to work on load as well. For an example, see my fiddle. You'll notice the height matching doesn't kick in until resize.
$(document).ready(function(){
function matchHeight() {
var newHeight = $("#slider").height();
$("#ctas").height(newHeight);
}
jQuery.event.add(window,"resize",matchHeight);
});
http://jsfiddle.net/sGNcc/2/
Just call "matchHeight" in your "ready" handler:
jQuery.event.add(window,"resize",matchHeight);
matchHeight();
Also that's kind-of a weird way to establish an event handler:
$(window).resize(matchHeight);
Call the matchHeight function onload:
$(document).ready(function(){
matchHeight();
});
function matchHeight() {
var newHeight = $("#slider").height();
$("#ctas").height(newHeight);
}

The image's dimension is different from when it's loading and after it loads

I have a page that loads a lot of fairly large images (about 200 of 100Kb images [about 600 x 400 px]).
What I'm trying to do is manipulate the photo if it's in portrait, as opposed to landscape.
The problem I'm experiencing is that when i use javascript to grab a portrait photo's properties when it's loading, the height is significantly lower than what it should be, and the width is bigger than it should be. Specifically, a 75 x 100 image was considered as a 100 x 16. So when the function runs through this image, the image is considered landscape, not portrait, and skips over.
I had hard time identifying the problem, because the property shows it as a 75 x 100px image after it's done loading.
Is there a way to get around this problem? or run the function after all the images have loaded?
Run the function after it has loaded, You'd do it like this:
Using the DOM exclusively
var newImg = document.createElement('img');
newImg.src = "theImage.png";
newImg.alt = "Always specify an alternate text for accessibility, even if left blank";
newImg.onload = function () {
//Image manipulation
};
galleryNode.appendChild(newImg); //Replace galleryNode with the parent element of your image.
Using innerHTML
galleryNode.innerHTML += "<img src='theImage.png' alt='' id='newImage1'/>";
var newImg = document.getElementById('newImage1');
newImg.onload = function () {
//Image manipulation
};
Using jQuery
$('.gallery img').live('load',function () {
//Image manipulation
});
Its always a good idea to run javascript after the page elements have finished loading. I usually do this in jQuery, like this:
$(function(){
//code to run after load goes here
});
Otherwise, you can try modifying the body tag and giving it an onload attribute, like:
<body onload="myFunction();" >

Categories