1

I am currently experiencing a 'strange problem'... I am a beginner in JavaScript and I want to get the height of an image in order to set the size of a .

  1. I get the width of the screen
  2. I set the width of an image which depend on the screen size => I guess the computer set also the height of the image.
  3. I ask for the height of the image
  4. I print it

This is the code:

var screenWidth = (window.innerWidth);  
myImg.width = Math.floor(screenWidth/3); // That works, my image is sized well.  
var imgLarg = getComputedStyle(myImg,null).height.toLowerCase()  
console.log(imgLarg); 

The problem is at follow: When I refresh the page by reloading the page via the web address, it works. But, when I press the refresh button, the code return '0px'.

2
  • Please provide some more context, this can't be solved with the information in the post. An important part here is when and where this code is executed. Commented Dec 5, 2013 at 22:54
  • At this step, the code is very simple, i have simplified it to have a better understanding and the problem still remain. A simple html code with <img src="waves.jpg" alt="photo" id="imag" />. Juste before </html>, there is the js script as before, with this line var myImg = document.querySelector('#imag') at the beginning. In a real situation, i want the get the height of the image to set the size a <div>. I have tried with myImg.onload = function(){} but i experience difficulties... Commented Dec 7, 2013 at 10:48

1 Answer 1

0

wrap your code in document.ready (if you use jquery) or listen for DOMContentLoaded. Wait for the image to load completely before getting its dimensions. Use .load if you use jquery or Image.onload().

http://api.jquery.com/ready/
http://api.jquery.com/load/
http://developer.mozilla.org/En/XUL/Attribute/Onload

Sign up to request clarification or add additional context in comments.

5 Comments

The timing really can be an issue here, but can't you just give the answer without obtruding jQuery, which is not even tagged in the post.
@Teemu i just updated my answer to include information for vanilla javascript. I have tried my best to shed some light in the right direction.
Unfortenately DOMContentLoaded or jQuery's $(document).ready() don't wait images to load...
@Teemu that is why i have mentioned Image.onload() or .load() :)
FWIW to future readers, I am using the jQuery .load() approach, but often can still find a not-yet-computed size (0px). I'm still looking for a "style computed" event.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.