Is there a way to find out if an element has a scroll bar using jQuery?

Say I have such an element

<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

+6
javascript jquery jquery-selectors
source share
3 answers

This should work

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

Using

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

EDIT:

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

 var clone = $('#mydivid').clone(); clone.css('opacity', '0').appendTo('body'); if (clone.hasHorizontalScrollBar()) { //do the job here } clone.remove(); 
+11
source share

You can wrap the text in another div and compare the width / height of this with #myDiv . If it is higher, there is a scroll bar:

 <div id="myDiv" style="..."> <div id="inner">random amount of lorem ipsum...</div> </div> 

Example:

 if( $('#inner').height() > $('#myDiv').height() ){ alert('vertical scrollbar'); } if( $('#inner').width() > $('#myDiv').width() ){ alert('horizontal scrollbar'); } 
0
source share

All Articles