Reputation: 1628
I am attempting to get the dimensions of an image to use later in my script. Selecting the img element directly with jQuery works fine and is easier, however it does not function in webkit browsers (the image is not loaded at the time of the function call). I'm trying to implement this solution where the variables are set after the image loads by using the jquery load() function.
Why are my variables not being set as desired?
function startSlider() {
if (1 == 1) {
var bImg = $('#banner img');
var bWidth = 111, bHeight = 222;
$("<img/>")
.attr("src", $(bImg).attr("src"))
.load(function() {
bWidth = this.width;
bHeight = this.height;
console.log('inner: ' + this.height);
});
console.log('outer: ' + bHeight);
}
}
$(window).load(startSlider(skin));
Output
outer: 222
inner: 333
Example Source
<div id="banner">
<img src="/path/to/image.jpg" />
</div>
Upvotes: 3
Views: 479
Reputation: 2339
startSlider()
called and $("<img/>")
is not ready or is not completed loaded,that's why you can't change your variable.make sure you are using DOMContentLoaded on your code, DOMContentLoaded is event will be fire when parsing of element is finished, in jquery you can use this function
$(document).ready(function(){
console.log('DOM Loaded (DOMContentLoaded)');
//place your function in here
});
Upvotes: 1
Reputation: 3900
.load()
is an asynchronous callback, meaning it will occur at the time the browser has finished downloading the image file.
You are binding .load()
to your image, then immediately logging the height. Because the .load()
callback hasn't yet run, it will output the default height.
You need to wait until .load()
has finished executing before continuing with any further logic that relies on the image height.
Upvotes: 5