I was wondering if there is a way of finding out whether a browser window has a scrollbar visible, in JQuery?
Here's the code I'm working with:
var hContent = $("body").height();
var hWindow = $(window).height();
if(hContent>hWindow) {
$('#scroll-top').fadeIn(250);
}
else {
$('#scroll-top').fadeOut(250);
}
Any help is Greatly Appreciated, Thanks
-
What is wrong with the code then? isn't it working for you?niksvp– niksvp2011年01月06日 11:33:23 +00:00Commented Jan 6, 2011 at 11:33
-
@niksvp - I need to somehow implement live to this so it picks up when there isnt a scrollbar visible...any ideas? I cant really test it at the moment because the page height is always greater than the viewport on page loadNasir– Nasir2011年01月06日 11:44:58 +00:00Commented Jan 6, 2011 at 11:44
-
your problem is not clear. is that you are not getting jQuery effect? fadeIn/Out?niksvp– niksvp2011年01月06日 11:56:58 +00:00Commented Jan 6, 2011 at 11:56
-
@niksvp - OK let me simplify, if the browser window has a vertical scroll, show #scroll-top...else hide #scroll-top. Problem: I have elements on my page that I can toggle therefore adjusting the page height...how do I get #scroll-top to disappear if I collapse/toggle all elements on the page?Nasir– Nasir2011年01月06日 12:38:37 +00:00Commented Jan 6, 2011 at 12:38
-
Check this url Detect if a page has a vertical scrollbar?User4567– User45672015年10月26日 08:27:59 +00:00Commented Oct 26, 2015 at 8:27
2 Answers 2
Use the following function.
function checkScrollBar() {
var hContent = $("body").height(); // get the height of your content
var hWindow = $(window).height(); // get the height of the visitor's browser window
// if the height of your content is bigger than the height of the
// browser window, we have a scroll bar
if(hContent>hWindow) {
return true;
}
return false;
}
1 Comment
What happens if you compare (window).height() to (document).height() if the document height is greater than the window height then a scrollbar should be visible but this also depends on your CSS settings and whether overflow is hidden or visible.
EDIT
You need to create a listener in order for the code to run at the right time. This should work when the browser window is resized:
$(window).resize(function(){
var hContent = $("body").height();
var hWindow = $(window).height();
if(hContent>hWindow) {
$('#scroll-top').fadeIn(250);
}
else {
$('#scroll-top').fadeOut(250);
}
}