Reputation:
When I set the source of the image beforehand in the html, I am able to get the original width and height. If I set the source of the image using javascript/jquery, I am unable to get the original width and height. Why is that and how can I fix it?
jQuery(document).ready(function() {
var originalWidth = $('#test').prop('naturalWidth');
var originalHeight = $('#test').prop('naturalHeight');
console.log(originalWidth + " x " + originalHeight);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<img id="test" src="https://www.gstatic.com/webp/gallery3/2.png">
</div>
The above way works, but I want to add the source image using javascript. But when I try that, it doesn't work.
jQuery(document).ready(function() {
$('#test').attr('src', 'https://www.gstatic.com/webp/gallery3/2.png');
var originalWidth = $('#test').prop('naturalWidth');
var originalHeight = $('#test').prop('naturalHeight');
console.log(originalWidth + " x " + originalHeight);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<img id="test">
</div>
As you can see, it returns the values 0 and 0, unlike the previous snippet. Why? and how can I fix that?
Upvotes: 1
Views: 22
Reputation: 177950
Because the code is too fast and the image has not loaded yet when you try to access the properties
Add a load handler before the change of the src
$(function() {
$('#test').on("load", function() {
var originalWidth = $('#test').prop('naturalWidth');
var originalHeight = $('#test').prop('naturalHeight');
console.log(originalWidth + " x " + originalHeight);
})
$('#test').attr('src', 'https://www.gstatic.com/webp/gallery3/2.png');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<img id="test">
</div>
Upvotes: 2