1

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

bigdave
  • 337
  • 3
  • 15
  • Wrap your statement in a function, then fire that function on window.resize. – James Sep 14 '16 at 14:55
  • You’ll need a handler function for the relevant events (resize and orientationchange), and in there perform your check again. (Whether using fixed heights is a good solution at all, depends. For example if the user changes the font-size, this might easily break.) – CBroe Sep 14 '16 at 14:55

3 Answers3

1

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");
   }
})'
Derek Story
  • 9,518
  • 1
  • 24
  • 34
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

0

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");
    }
});
bigdave
  • 337
  • 3
  • 15