0

I have a set of images with various widths. I want them 100% width for responsiveness, but no larger that their actual size.

I tried:

$("#mainImg").on('load', function() {
var natWidth = $(this).get(0).naturalWidth;
alert(natWidth);
});

But nothing alerts.

I also tried this, again with no alert:

var myImage = document.getElementById("mainImg");
myImage.addEventListener('load', function() {
    alert('My width is: ', this.naturalWidth);
});

Obviously, I'm missing something!

Once I can grab the width, I assume I can easily use it to set the max-width for the image.

webguy
  • 664
  • 10
  • 27
  • Where are HTML and CSS of your set? Please add a [mcve]. – Kosh Aug 11 '18 at 01:57
  • You may get some insight here at: https://stackoverflow.com/questions/318630/get-the-real-width-and-height-of-an-image-with-javascript-in-safari-chrome – Tanvir Ahmed Aug 11 '18 at 01:59

1 Answers1

2

I put this snippet together using your code and it works fine for me. I suspect that your mainImg ID doesn't actually refer to an img tag, but perhaps an enclosing div or some such. Is that possible?

Also, yes, it's easy to set the max width to the naturalWidth value. Just use attr. I've put an example in the code as well.

$(document).ready(function($) {
    $('#myImg').on('load', function(e) {
        var natWidth = $(this).get(0).naturalWidth;
        alert(natWidth);
        $(this).attr('maxwidth', natWidth);
        alert($(this).attr('maxwidth'));
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="myImg" src="http://ppls.robertrodes.com/includes/images/Dashboard%20Mockup2.png" />
BobRodes
  • 5,990
  • 2
  • 24
  • 26
  • @webguy I'm curious. Did you find that you weren't referring to an `img` tag, or was something else the problem? – BobRodes Aug 14 '18 at 01:15
  • Stupid mistake I assume. I must have hit the "prevent this page from throwing alerts" so with no alerts, it looked like the code wasn't working. – webguy Aug 14 '18 at 15:10
  • @webguy Sounds like something I might do. A prosaic cause if ever there were one. :) Glad you got it sorted out. – BobRodes Aug 14 '18 at 17:26