Solved

How to find the width of an image before it loads.

Posted on 2014-07-25
2
437 Views
Last Modified: 2014-07-25
I need to know the width of an image before it is called in the html source. I know the name of the image and I'm trying to use javascript to discover the width. This returns a vale of 0 for the width.


var img = new Image();
img.src = "http://mysite.com/graphics/myimage.png"
window.confirm(img.width);
0
Comment
Question by:Gary Samuels
2 Comments
 
LVL 21

Assisted Solution

by:Randy Poole
Randy Poole earned 250 total points
ID: 40219655
There is no way to know before it is loaded.  You can however catch this info before you add it to your page and do what needs to be done:
img = new Image();
img.onload = function() {
  alert("(" + this.width + "x" + this.height+")");
};
img.src = "http://mysite.com/graphics/myimage.png";

Open in new window

0
 
LVL 13

Accepted Solution

by:
duncanb7 earned 250 total points
ID: 40219721
You can do get the image width before adding it into DOM

Duncan    
<script type="text/javascript">
var getImageSize = function(src) {
    var img = new Image();
    $(img).bind('load', function(e) {
        var height = img.height;
        var width = img.width;
      //  document.write('width:' + width + ', height: ' + height);
	  alert("width="+width);
    });
    img.src = src;
};	
getImageSize('http://localhost/data/php/water.jpg');
</script>

Open in new window

0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
Find out what you should include to make the best professional email signature for your organization.
In this tutorial viewers will learn how to embed an audio file in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: : The declaration should display (CODE) HTML5 is supported by the most recent versions of all major browsers…
The viewer will learn how to dynamically set the form action using jQuery.

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question