Search code examples
javascriptjqueryimagedimensions

jQuery: how to get the dimensions of a external image?


Looking for a way to get the dimensions (width and height) of an external image.
I have used prop() and attr(), but they don't return any values. Just an error.

Example:

<a href="pathtotheimage">some link</a>

Solution

  • jQuery

    var path = 'https://source.unsplash.com/random/600x300/?montreal';
    $("<img/>").attr('src', path).load(function() {
        console.log(this.width, this.height);
     });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

    Vanilla Javascript

    var path = 'https://source.unsplash.com/random/600x300/?montreal';
    var img = new Image();
    img.src = path;
    img.addEventListener('load', function() {
      console.log(this.width, this.height);
    });