Reputation: 33
I try to get height/width from some background images, but how to get these values into some variables?
var bgobj = jQuery(this); // assigning the object
var url = bgobj.css('background-image').replace(/url\(|\)$|"/ig, '');
var img = new Image();
img.src = url;
Option 1:
alert('img.width: ' + img.width); // alert: " img.width: 0 "
Probably, the image hasn't loaded. So I try onload: Option 2:
jQuery(bgimg).on('load', function() {
height = jQuery(bgimg).height();
//alert('height ' + height); //'480px' which is correct!
});
No way to get the value out for further use!? So I try callback: Option 3:
var imageSize = function(url, callback) {
var img = new Image();
img.onload = function(){
var response = {};
var img = new Image();
img.onload = function() {
var x = img.width;
var y = img.height;
var z = y/x;
response = {width:x,height:y};
if(callback) callback(response);
}
img.src = url;
}
img.onload();
}
var getSize = function(url, callback) {
imageSize(url, function(response) {
var dim = response;
})
callback(dim);
}
var h;
imageSize(img.src, function(response) {
h=response.height;
//alert(h); // 800px (OK))
})
//alert(h); //undefined
//alert(imageSize.height); //undefined
//alert(imageSize.h); //undefined
//alert(imageSize.response.h); //undefined
Still no way to get the value into an ordinary variable. Where did I go wrong?
Upvotes: 2
Views: 5404
Reputation: 136174
You've overcomplicated it, but option 3 is one way to do it.
var imageSize = function(url, callback) {
var img = new Image();
img.onload = function(){
if(callback) callback(img.width,img.height);
}
img.src = url;
}
$(function(){
var url = $('#foo').css('background-image').replace(/url\(|\)$|"/ig, '');
imageSize(url,function(w,h){
alert("width=" + w + ", height=" + h);
})
});
#foo{
background-image:url(http://lorempixel.com/100/100/)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">test</div>
The thing to remember is that the method imageSize
is asynchronous, so you must pass it a callback which will be called when the image has loaded. You cant have another method where you treat it as a synchronous call, that just wont work.
Upvotes: 4