Getting Image Dimensions with JavaScript
Question:
Is it possible to programmatically retrieve the dimensions (width and height) of an image on a webpage using JavaScript or jQuery?
Answer:
Yes, you can obtain the dimensions of an image on a webpage using JavaScript or jQuery. Here's how:
JavaScript:
const img = new Image(); img.onload = function() { alert(this.width + 'x' + this.height); } img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
This code creates a new image object and assigns a load event listener to it. When the image finishes loading, the event listener is triggered and it calculates and alerts the image's width and height. Replace the provided image URL with the actual image you want to check.
jQuery:
jQuery offers a built-in function for retrieving image dimensions:
const imgHeight = $('img').height(); const imgWidth = $('img').width();
Simply replace the '$('img')' selector with the appropriate selector for your image element.
The above is the detailed content of How Can I Get an Image's Width and Height Using JavaScript or jQuery?. For more information, please follow other related articles on the PHP Chinese website!