HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

.hasScroll function, checking if a scrollbar is visible in an element

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
visiblecheckinghasscrollfunctionelementscrollbar

Problem

I have constructed a function that checks whether an element has a scrollbar or not, and can also check individual axes.

I don't know if this works in all major browsers and am unsure about the performance.

Is there any way to improve upon the code, did I miss anything?

How would a javascript equivalent look like?

Note: I first asked this question on Stack Overflow, but someone suggested I should post it here instead.

Code | Example

`$.fn.hasScroll = function(axis){
var sX = this.css("overflow-x"),
sY = this.css("overflow-y");

if(typeof axis == "undefined"){
//Check both x and y declarations
if(
(sX == "hidden" && sY == "hidden") ||
(sX == "visible" && sY == "visible")
){
return false;
}

if(sX == "scroll" || sY == "scroll"){
return true;
}
}else{
//Check individual axis declarations
switch(axis){
case "x":
if(sX == "hidden" || sX == "visible") return false;
if(sX == "scroll") return true;
break;
case "y":
if(sY == "hidden" || sY == "visible") return false;
if(sY == "scroll") return true;
break;
}
}

//Compare client and scroll dimensions to see if a scrollbar is needed
var bVertical = this[0].clientHeight

Solution

=== > == (Not that it really matters in this case, but it's still better.)

Also, IIRC clientHeight etc are not cross-browser, this is why jQuery provides .position(), .offset(), .scrollTop() and .height() (whichever one best suits your needs).

Context

StackExchange Code Review Q#13338, answer score: 8

Revisions (0)

No revisions yet.