bigdave
bigdave

Reputation: 337

add/remove class depending on element height on the fly

I have an element that needs to change height depending on the height of its child p tag:

<div id="eventpg" class="bg-pink linkbox">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec</p>
</div>

I've achived the desired change by adding a class if the paragraph is over a certain height:

var divheight = $("#eventpg p").height();
if ( divheight > 173) {
    $("#eventpg").addClass("height535");
}

Which adds this class this class:

. height535{height:535px;}

This works fine in most instances but if the user rotates their device from portrait to landscape the added class still remains and the page has to be reloaded to remove it.

How do I achieve the height change 'on the fly' as it were? So if the browser window changes causing the paragraph to change height the container changes to reflect this?

Thanks

Upvotes: 1

Views: 437

Answers (3)

bigdave
bigdave

Reputation: 337

Thanks for your help guys. using a combo of The One and Only ChemistryBlob's and Derek Story's answers, the follwoing has worked successfully:

$(window).on('load resize', function() {
    var divheight = $("#eventpg p").height();
    if ( divheight > 173) {
        $("#eventpg").addClass("height535");
    } else {
        $("#eventpg").removeClass("height535");
    }
});

Upvotes: 0

You can listen for a resize event, adding or removing the class as necessary:

var heightThreshold = 173; // controlling the height globally may be easier

$(window).resize(function () {

    var el        = $("#eventpg"),
        divheight = el.find("p").height();

    if ( divheight > heightThreshold ) {
        el.addClass("height535");
    } else {
        el.removeClass("height535");
    }

});

or do something similar with e.g. jQuery Mobile's orientationchange event - see here

Upvotes: 0

Derek Story
Derek Story

Reputation: 9593

You should be able to run the function on load and resize:

$(window).on('load resize', function() {
   var divheight = $("#eventpg p").height();
   if ( divheight > 173) {
       $("#eventpg").addClass("height535");
   }
})'

Upvotes: 1

Related Questions