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