detect elements overflow using jquery

Viewed 51696

CSS:

 .blue
    {
     width:200px;
     height:200px;
     background-color:blue;
     color:#000000;
     overflow:auto;
    }

JavaScript:

function addChar() {
    $('.blue').append('some text  ');
}

HTML:

<div id='blue1' class="blue"></div><br />
<a href='javascript:void(0)' onclick='addChar()'>Add</a>

div id='blue1' has overflow property set to auto. I want to detect overflow when it happens.

10 Answers
$.fn.HasScrollBar = function() {
    //note: clientHeight= height of holder
    //scrollHeight= we have content till this height
    var _elm = $(this)[0];
    var _hasScrollBar = false; 
    if ((_elm.clientHeight < _elm.scrollHeight) || (_elm.clientWidth < _elm.scrollWidth)) {
        _hasScrollBar = true;
    }
    return _hasScrollBar;
}

/// this is my solution

As far as I know you will have to compare the width/clientWidth and height/clientHeight in your addChar() function. When that changes you've got scrollbars (unless you moddify the dimensions somewhere else ...)

Something like this:

function addChar () {
    var blueEl = $( '.blue' );
    blueEl.append ( 'some text  ' );

    if ( blueEl.width () !== blueEl[0].clientWidth || blueEl.height () !== blueEl[0].clientHeight ) {
        // element just got scrollbars
    }
}

The only way I can think of is to create a nested DIV and compare the outer div height with the inner div. If you don't want to modify existing markup you can append it using jQuery like this:

var outer = $('.blue'),
    inner = $('<div>').appendTo(outer);

function addChar() {
    inner.append('some text ');
    if (inner.height() > outer.height()) {
        console.log('overflowed');
    }
}

Here's a plugin i wrote, which might come in handy if you want to find out if an element is overflown or not: https://github.com/ZetaSoftware/jquery-overflown-plugin.

With this plugin, in the original example, you could just do: $("#blue1").overflown() to find out of children of #blue1 are overflowing.

Related