Get Image Width Height With JQuery And JavaScript
Posted by in Javascript July 12, 2011 2 Comments

In some case, you may need to read the Width and Height property of a particular image dynamically. These scenario could be just detect an image dimensions, adjust image to fit the design or view an image in a same size popup.

In order to do that, you have to know its ID attribute then you either of following methods: using JQuery or JavaScript.

1. Using JQuery to get image Width and Height

<script type="text/javascript">
function jquery_get_width_height()
{
	var imgWidth = $("#img").width();
	var imgHeight = $("#img").height();
	alert("JQuery -- " + "imgWidth: " + imgWidth + " - imgHeight: " + imgHeight);
}
</script>

2. Using JavaScript to get image Width and Height

<script type="text/javascript">
function javascript_get_width_height()
{
	var img = document.getElementById('img');
	alert("JavaSript -- " + "imgWidth: " + img.width + " - imgHeight: " + img.height);
}
</script>

Example and demo source code

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
function javascript_get_width_height()
{
	var img = document.getElementById('img');
	alert("JavaSript -- " + "imgWidth: " + img.width + " - imgHeight: " + img.height);
}
function jquery_get_width_height()
{
	var imgWidth = $("#img").width();
	var imgHeight = $("#img").height();
	alert("JQuery -- " + "imgWidth: " + imgWidth + " - imgHeight: " + imgHeight);
}
</script>
</head>
<body>
 
 
<img id="img" src="http://www.google.com/intl/en_ALL/images/logo.gif" /><br>
<input type="button" value="Get Width Height With JavaScript" onClick="javascript_get_width_height()" ><br>
<input type="button" value="Get Width Height With JQuery" onClick="jquery_get_width_height()" ><br>
</body>
</html>
Download Get Image Width Height With JQuery And JavaScript Source Code

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at hoan@4rapiddev.com
  • pritesh

    is there a way to get the actual width and height of the image via jquery?
    ex. there is an image 500px x 500px and I use it
    is there a function to get me the real height/width  = 500?

    • http://4rapiddev.com/ Hoan Huynh

      Hi there, 

      I think we also can set width & height of the image via JQuery. For example:

      $(“#img”).width(500);
      $(“#img”).height(500);

      H2.