Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to find out if an element has a scrollbar on it using JQuery?

Let say I have an element like so

<div id="myDiv" style="height:10px; width:100px; overflow:scroll;"> 
   random amount of lorem ipsum... 
</div>

Is there a way in JS or Jquery to look at $("#myDiv") and see if it has scrollbars?

Thanks

Dave

like image 285
Dave Avatar asked Nov 10 '10 16:11

Dave


1 Answers

This should work

$.fn.hasVerticalScrollBar = function () {
     return this[0].clientHeight < this[0].scrollHeight;
}

$.fn.hasHorizontalScrollBar = function () {
    return this[0].clientWidth < this[0].scrollWidth;
} 

Usage

alert($('#mydivid').hasHorizontalScrollBar());
alert($('#mydivid').hasVerticalScrollBar());

EDIT:

To use this method with invisible element, clone the div, set its opacity to 0, append the clone to the body, check if the clone has the scroll bar and then remove the clone:

var clone = $('#mydivid').clone();
clone.css('opacity', '0').appendTo('body');
if (clone.hasHorizontalScrollBar()) {
   //do the job here
}
clone.remove();
like image 194
John Hartsock Avatar answered Sep 22 '22 19:09

John Hartsock