9

Possible Duplicate:
Detecting presence of a scroll bar in a DIV using jQuery?

There is markup as below,

<div class="content">Lorem</div>
<div class="content">Lorem Iorem Lorem Iorem Lorem Iorem Lorem Iorem Lorem IoremLorem Iorem Lorem Iorem Lorem Iorem</div>
<div class="content">Lorem</div>
<div class="content">Lorem</div>

If content have scroll bar, then it should add class to that div like "scroll-image".

Height can be different for DIVs. Any jQuery solution for this.

Community
  • 1
  • 1
Wasim Shaikh
  • 6,880
  • 18
  • 61
  • 88

4 Answers4

34
(function($) {
    $.fn.hasScrollBar = function() {
        return this.get(0).scrollHeight > this.height();
    }
})(jQuery);

$('#my_div1').hasScrollBar(); // returns true if there's a `vertical` scrollbar, false otherwise..

Taken from How can I check if a scrollbar is visible?

Community
  • 1
  • 1
472084
  • 17,666
  • 10
  • 63
  • 81
  • 2
    You have the rep, why no closevote? – Esailija Jun 08 '12 at 11:38
  • 1
    I had a problem for mobile screen having .5 pixels, adding `Math.round` resolved the problem for me: `return Math.round(this.get(0).scrollHeight) > Math.round(this.outerHeight());` – Guillaume Lhz Nov 22 '21 at 19:09
5

You need to compare scrollHeight with height of the element like this:

$('.content').each(function(){
  if ($(this)[0].scrollHeight > $(this).height()) {
    $(this).addClass('scroll-image');
  }
});
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
2

As esailija said, duplicate of: Detecting presence of a scroll bar in a DIV using jQuery?

The solution there was the following

var div= document.getElementById('something'); // need real DOM Node, not jQuery wrapper
var hasVerticalScrollbar= div.scrollHeight>div.clientHeight;
var hasHorizontalScrollbar= div.scrollWidth>div.clientWidth;
Community
  • 1
  • 1
altschuler
  • 3,694
  • 2
  • 28
  • 55
0
(function($) {
$.fn.hasScrollBar = function() {
    return this.get(0).scrollHeight > this.height();
}
})(jQuery);

$('div').hasScrollBar(); //return true if it has one

Source: How can I check if a scrollbar is visible?

Community
  • 1
  • 1
Johan
  • 35,120
  • 54
  • 178
  • 293