I'm trying to read the size of an image and regulate its margin if its larger than 150 in height. But I'm always getting a '0' in the console when running this code:
var coverImg;
coverImg = document.getElementById('userCover');
$.ajax({
type: "POST",
url: 'code/submit/submitGetUserData.php',
data: {id: userID, what: 'all'},
async: false,
success:function(data,status){
var dataArray = data.split(',');
document.getElementById('userAvatar').src = dataArray[0];
coverImg.src = dataArray[1];
$('#userName').text(dataArray[2]);
},
error: function(){
alert("error occured");
},
complete: function(){
console.log(coverImg.height);
if(document.getElementById('userCover').height > 150)
{
var regulate = 0;
regulate = (coverImg.height - 150) / 2;
regulate = regulate * (-1);
coverImg.style.marginTop = regulate;
}
}
});
Is JS too slow to read the height property?!
I hope someone can help me!
Move the code currently placed in complete
into coverImg.onload
handler. For example:
coverImg.onload = function() {
if(document.getElementById('userCover').height > 150) {
var regulate = (150 - this.height) / 2;
// ...
}
}
coverImg.src = dataArray[1];
... as browser can determine the height of <img>
element only after it's fully loaded - and complete
callback is fired before that.