How do I know if a visible scrollbar is visible in a browser window in jQuery?

I was wondering if there is a way to find out if there is a visible scrollbar in the browser window in jQuery?

Here is 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 much appreciated, thanks

+4
source share
2 answers

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 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; } 
+10
source

What happens if you compare (window).height() with (document).height() , if the height of the document is greater than the height of the window, then the scroll bar should be visible, but it also depends on your CSS settings and on hidden or visible overflow.

EDIT

You need to create a listener so that the code works at the right time. This should work when resizing the browser window:

 $(window).resize(function(){ var hContent = $("body").height(); var hWindow = $(window).height(); if(hContent>hWindow) { $('#scroll-top').fadeIn(250); } else { $('#scroll-top').fadeOut(250); } } 
+3
source

Source: https://habr.com/ru/post/1334485/


All Articles