Home >Web Front-end >JS Tutorial >How Can I Get an Image's Width and Height Using JavaScript or jQuery?

How Can I Get an Image's Width and Height Using JavaScript or jQuery?

DDD
DDDOriginal
2024-12-27 00:03:14817browse

How Can I Get an Image's Width and Height Using JavaScript or jQuery?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn