Reputation: 127
I have this javascript that's supposed to get the image's actual width and height. It works when I test locally on 127.0.0.1:8000 console logs on the snapshot but on the server it fails
returns 0 as the image width and height.
Tried nesting the code in jquery ready but it does trigger before the image fully loads so I believe this is the issue.
here's the javascript
$(function() {
$(document).ready(function() {
$('.lynk-section img').each(function() {
var width = $(this)[0].naturalWidth;
console.log(width);
//$(this).css('max-width', width+'px');
var height = $(this)[0].naturalHeight;
console.log(height);
//$(this).css('max-height', height+'px');
});
});
});
Upvotes: 0
Views: 64
Reputation: 6565
Put your code under window load event.
$(function() {
$(document).on('load',function() {
// Your code to measure image dimensions should go here.
});
});
Upvotes: 0
Reputation: 4370
you have to use the onload event of the image, or maybe you just have to use window.onload event
//....
$('img').each(function() {
$(this).on("load", function(){
console.log("width: ", this.naturalWidth);
console.log("height: ", this.naturalHeight);
});
});
//....
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://via.placeholder.com/50x150">
<img src="http://via.placeholder.com/100x150">
<img src="http://via.placeholder.com/200x150">
Upvotes: 0
Reputation: 26360
$(function() {
and $(document).ready(function() {
are the same thing (the first one is a shorthand), you only need one. But anyway, this will just wait for all the HTML code to be present in the page, not for the assets to be loaded. As @Rory said, window.load
will wait for the images to be loaded, so you can then grab their dimensions.
Upvotes: 1