Reputation: 3064
This is a follow up from a question I asked earlier but although mostly working now, the function is taking the first of 3 images as it's reference to addClass()
and not following the if / else
. Any idea why?
Image 1 & 3 = Landscape - correctly adding .heightDefine
Image 2 = Portrait - incorrectly also adding .heightDefine
instead of .widthDefine
jQuery.fn.galDisplay = function () {
var galSingleImgH = this.height();
var galSingleImgW = this.width();
if(galSingleImgW > galSingleImgH){
this.addClass('heightDefine');
} else if(galSingleImgW < galSingleImgH){
this.addClass('widthDefine');
}
}
jQuery('.notFirst img').galDisplay();
Upvotes: 0
Views: 58
Reputation: 251082
jQuery will actually give you a collection of matching elements, so this
is the collection, not a single result.
To deal with this, iterate the collection using each
:
jQuery.fn.galDisplay = function () {
this.each(function () {
var $self = $(this);
var galSingleImgH = $self.height();
var galSingleImgW = $self.width();
alert(galSingleImgW + ' ' + galSingleImgH);
if(galSingleImgW > galSingleImgH){
$self.addClass('heightDefine');
} else if(galSingleImgW < galSingleImgH){
$self.addClass('widthDefine');
}
// else it is square!
});
}
jQuery('.notFirst img').galDisplay();
And the only other thing I would add is that if you are relying on working out the image size you don't want to run this until the image is loaded.
Upvotes: 3
Reputation: 27364
Try
(function($)
{
$.fn.galDisplay = function(params)
{
//params = $.extend( {minlength: 0, maxlength: 99999}, params);
//above code extends options passed
this.each(function()
{
var galSingleImgH = this.height();
var galSingleImgW = this.width();
if(galSingleImgW > galSingleImgH)
{
this.addClass('heightDefine');
}
else if(galSingleImgW < galSingleImgH)
{
this.addClass('widthDefine');
}
});
return this;
};
})(jQuery);
Upvotes: 0
Reputation: 318302
You're running the same function on the whole collection, you need to run the if/else on each element:
jQuery.fn.galDisplay = function (){
return this.each(function() {
var galSingleImgH = $(this).height(),
galSingleImgW = $(this).width();
if (galSingleImgW > galSingleImgH) {
$(this).addClass('heightDefine');
} else if (galSingleImgW < galSingleImgH) {
$(this).addClass('widthDefine');
}
});
}
jQuery('.notFirst img').galDisplay();
Upvotes: 2