Reputation: 15006
I'm working on a script that adds a class to images, based on if the background-image is landscape or portrait.
Here is the function:
function loadImg (mythis, callback) {
var src = getUrl($(mythis).css('background-image'));
var t = new Image();
t.src = src;
console.log(t.height);
var height = t.height;
var width = t.width;
if(width > height){
$(mythis).parent().addClass('panorama');
$(mythis).parent().parent().removeClass('smallpost');
}
This great in Webkit, but not in Firefox or IE. The problem is with t.height and t.width, they are always Zero in these browsers. One challenge with this solution is that the images needs to be loaded before the function is run. Because the images are background-images and not in the DOM, I ended up just adding a delay before the script runs. I know it's a bit sinful, but really an acceptable solution in this case. Not sure if that has anything to do with my problems though.
Full javascript: $(function(){
setTimeout(function(){
var elems = $('.post .crop'), count = elems.length;
$(elems).each(function(i){
//Rezise image
loadImg(this, function callback(){
//Run masonry afte last image
if (i = count-1){
$('#content').imagesLoaded(function(){
$('#content').masonry({
itemSelector : '.post',
gutterWidth: 15,
columnWidth: 320
});
});
};
});
})
},5000);
//getImgSize('http://25.media.tumblr.com/83c73059a904b46afba332f26e33c5bd/tumblr_mmvwy7XjKq1sqsf7io1_500h.jpg')
function getUrl(styling){
styling = styling.replace('url(','').replace(')','');
return (styling);
}
function loadImg (mythis, callback) {
var src = getUrl($(mythis).css('background-image'));
var t = new Image();
t.src = src;
console.log(t.height);
var height = t.height;
var width = t.width;
if(width > height){
$(mythis).parent().addClass('panorama');
$(mythis).parent().parent().removeClass('smallpost');
}
callback();
}
});
Upvotes: 0
Views: 81
Reputation: 382170
The difference you see is usually related to caching state of your image : if the image is already available, the dimensions may be immediately known.
You need to handle the load
event :
var t = new Image();
t.onload = function(){
var height = t.height;
var width = t.width;
if(width > height){
$(mythis).parent().addClass('panorama');
$(mythis).parent().parent().removeClass('smallpost');
}
};
t.src = src;
EDIT :
you have another problem in your getUrl
function : it doesn't remove the quotes that some browsers may add to the style.
Change
styling = styling.replace('url(','').replace(')','');
to
styling = styling.replace('url(','').replace(')','').replace(/"/g,'');
Upvotes: 1