Solved

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

Posted on 2014-07-25
2
429 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:garysamuels
2 Comments
 
LVL 21

Assisted Solution

by:Randy Poole
Randy Poole earned 250 total points
Comment Utility
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
Comment Utility
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

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
In this tutorial viewers will learn how to style elements, such a divs, with a "drop shadow" effect using the CSS box-shadow property Start with a normal styled element, such as a div.: In the element's style, type the box shadow property: "box-shad…
The viewer will learn how to dynamically set the form action using jQuery.

728 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now