Reputation: 1266
I came upon a script for resizing images dynamically for fitting a specific width here. I modified it for my own web app and it works great part of the time, but for some reason the function will sometimes randomly not trigger the if statement when the image does indeed have a larger width then I’m desiring so the image never resizes. I put in a set timeout hoping that the timeout would give the browser time to read the image. But no luck any ideas as to why it would not trigger?
Side note: this is for a mobile web app, is there something with HTML5 that I could use?
var maxWidth = 200;
var imgWidth = $('#locImg').width();
console.log(imgWidth);
setTimeout(function () {
if( imgWidth > maxWidth) {
newWidth = maxWidth;
var newHeight = $('#locImg').height() / ( $('#locImg').width() / maxWidth);
$('#locImg').height(newHeight).width(newWidth);
console.log($('#locImg').width());
$('#loc').css('visibility','visible');
}
else {
$('#loc').css('visibility','visible');
}
},750);
Upvotes: 0
Views: 331
Reputation: 78570
You could use something like this to ensure the image is fully loaded:
var maxWidth = 200;
var imgWidth = $('#locImg').width();
var image = new Image();
image.src = $('#locImg').attr("src");
image.onload = (function () {
if( imgWidth > maxWidth) {
newWidth = maxWidth;
var newHeight = $('#locImg').height() / ( $('#locImg').width() / maxWidth);
$('#locImg').height(newHeight).width(newWidth);
console.log($('#locImg').width());
$('#loc').css('visibility','visible');
}
else {
$('#loc').css('visibility','visible');
}
});
this way it only starts the resize after the image has fully loaded.
Upvotes: 1