Joseph Sjoblom
Joseph Sjoblom

Reputation: 171

AddClass based on element height

I can't figure out why this isn't working. I'm basically trying to add a class (.scroll) to any .panel-body if it is taller than 320px. Otherwise, don't add the .scroll class to the .panel-body.

What am I doing wrong?

I've supplied a jsfiddle:

var maxHeight = 320;
var panelBody = $(this).('.panel-body');
var panelBodyHeight = panelBody.height();

if ( maxHeight < panelBodyHeight ) {
   panelBody.addClass('scroll');
}
else { 
   panelBody.removeClass('scroll');
}

http://jsfiddle.net/8sMX4/1/

Upvotes: 1

Views: 361

Answers (2)

Pete
Pete

Reputation: 58442

You need to do it in an each loop like this:

$('.panel-body').each(function() {
    panel = $(this);
    if (panel.outerHeight() > maxHeight) {
        panel.addClass('scroll');
    } else {
        panel.removeClass('scroll');
    }
})

Example

Or you can use filter:

$('.panel-body').filter(function() {
    return $(this).outerHeight() > maxHeight;
}).addClass('scroll');

Example

Upvotes: 2

Amit Joki
Amit Joki

Reputation: 59252

This is the line where you go wrong:

var panelBody = $(this).('.panel-body');

It should be:

var panelBody = $('.panel-body'); 

Also, you comparison should be if(panelBodyHeight > maxHeight). Thanks @Pete for telling this.

Learn more about selecting elements & Updated Demo

Upvotes: 2

Related Questions