Solved

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

Posted on 2014-07-25
2
438 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

MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

Question has a verified solution.

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

Suggested Solutions

Is your Office 365 signature not working the way you want it to? Are signature updates taking up too much of your time? Let's run through the most common problems that an IT administrator can encounter when dealing with Office 365 email signatures.
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 the benefit of using external CSS files and the relationship between class and ID selectors. Create your external css file by saving it as style.css then set up your style tags: (CODE) Reference the nav tag and set your prop…

820 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