Javascript DOM HTML Image naturalWidth Property get

Introduction

Return the original width of an image:

var x = document.getElementById("myImg").naturalWidth;

In this example, the image's width is originally 98 pixels.

We have used CSS to style the image to 120 pixels wide.

Click the button to display the original width of the image.

View in separate window

<!DOCTYPE html>
<html>
<body>

<img id="myImg" src="image1.png" style="width:120px;height:98px;">


<button onclick="myFunction()">Test</button>

<p id="demo"></p>

<script>
function myFunction() {/*  ww w .  java 2  s  . c  om*/
  var x = document.getElementById("myImg").naturalWidth;
  document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The naturalWidth property returns the original width of an image.

The naturalWidth property stores the actual width while the width property returns the styled width.

This property is read-only.

The naturalWidth property returns a Number representing the original width of an image in pixels.




PreviousNext

Related