How to get current image size (width and height) using JavaScript
📅January 6, 2022
Today we will show you how to get current image size (width and height) using JavaScript.
Checkout more articles on JavaScript
- scroll-to-a-specific-element-using-javascript" title="Scroll to a specific element using JavaScript">Scroll to a specific element using JavaScript
- Detect a mobile device using JavaScript
- file-using-javascript" title="Download a file using JavaScript">Download a file using JavaScript
- array-into-chunks-in-javascript" title="Split an array into chunks in JavaScript">Split an array into chunks in JavaScript
You can simply use the `API/Element/clientWidth" title="clientWidth">clientWidth` and `clientHeight` to get the current width and height of the image in pixel.
Refer to the sample HTML code below to get the image size.
<meta charset="utf-8">
<title>How to get current image size (width and height) using JavaScript - Clue Mediator</title>
<script>
function getImgSize(){
var myImg = document.querySelector("#myImage");
var currWidth = myImg.clientWidth;
var currHeight = myImg.clientHeight;
console.log("Image width: ", currWidth);
console.log("Image height: ", currHeight);
}
</script>
<img src="/my-img.jpg" id="myImage" width="250" alt="My Image">
<button type="button" onclick="getImgSize();">Click to get Image Size</button>
Using the code above you will find the width and height of the current image in the console.
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂