JQuery.scroll - How to get the distance scrolling down or up the page?

I have a fixed Nav position at the top of my web page. Nav also has a drop-down menu that slides down and stays down until it is pressed again.

I try to reach, if the submenu is open, and the user decides to scroll down a bit, the submenu will automatically close.

I currently have:

$(document).scroll(function() { $(".subMenu").slideUp(300); }); 

But this method is very sensitive and closes the drop-down menu with the slightest scroll.

Ideally, I could create a menu slide back AFTER I scroll UP or DOWN 300px, so there is some kind of β€œbuffer” room.

+4
source share
2 answers

You can use jquery $(window).scrollTop() to determine the current position. I demonstrated a simple example to demonstrate it.

 var lastFixPos = 0; var threshold = 200; $(window).on('scroll', function(){ var diff = Math.abs($(window).scrollTop() - lastFixPos); if(diff > threshold){ alert('Do something'); lastFixPos = $(window).scrollTop(); } }); 

You can change the threshold to increase / decrease sensitivity before taking action.

+7
source

Without jQuery, you can achieve the same as here:

 var winPos = { y: 0, yDiff: 0, moveY: function(diff) { this.yDiff = -(this.y - diff); this.y = diff; } }; window.onscroll(function(){ var threshold = 10; winPos.moveY(window.scrollTop); // Check against position if (winPos.y > threshold) { // Do something } // Check against difference if (winPos.yDiff > threshold) { // Do something } }); 
+1
source

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


All Articles