How To Get Visible Width And Height Of Image Using JavaScript

By bhagwatchouhan
How To Get Visible Width And Height Of Image Using JavaScript

This tutorial provides the steps required to get the visible width and height of an Image using JavaScript. The actual or real width and height may be different as compared to the visible width and height.

 

Image Width and Height

In several cases, we might be required to find out the visible width and height of the image to set the parent width and height. We can get the width and height of the given image using the clientWidth and clientHeight properties as shown below.

// Get the Image
var image = document.querySelector( "#banner" );
// Visible Width var imgWidth = image.clientWidth;
// Visible Height var imgHeight = image.clientHeight;

This is the easiest way to get the visible width and height of the given image.

 

Complete Example

This section shows a complete example to show the image width and height using an alert box.

<!DOCTYPE html>
<html lang="en-US">
	<head>
		<meta charset="utf-8">
		<title>Visible Width and Height of Image - JavaScript</title>
		<script>
			window.onload = function() {
initPage(); };
function initPage() {
var button = document.querySelector( "#btn-show" );
button.addEventListener( 'click', function( event ) {
showImageDimensions(); }); }
function showImageDimensions() {
// Get the Image
var image = document.querySelector( "#banner" );
// Visible Width
var imgWidth = image.clientWidth;
// Visible Height
var imgHeight = image.clientHeight;
alert( "Visible Width=" + imgWidth + ", " + "Visible Height=" + imgHeight ); } </script> </head> <body> <h1>Image Width & Height Demo</h1> <div> <img id="banner" src="banner.jpg" width="350px" alt="Banner" /> </div> <div> <button id="btn-show" type="button">Show</button> </div> </body> </html>

 

Summary

This tutorial provided the steps required to obtain the visible width and height of an Image using JavaScript.

Share this blog:

Profile picture for user bhagwatchouhan
bhagwatchouhan