Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery .scroll - How do I retrieve the distance scrolled down OR up the page?

I have a Position Fixed Nav at the top of my webpage. The Nav also has a drop down menu which slides down and stays down until it is clicked again.

What I am trying to achieve is, if the sub menu is open, and the user decides to scroll down the page a bit, the sub menu will automatically close.

What I currently have is:

$(document).scroll(function() {

$(".subMenu").slideUp(300);

 });

But this method is far to sensitive and closes the drop down with the slightest scroll.

Ideally I could have the menu slide back up AFTER I scroll UP or DOWN 300px, so that there is some sort of "buffer" room.

like image 572
BigDog Avatar asked Feb 16 '23 11:02

BigDog


1 Answers

You can use jquery's $(window).scrollTop() to determinate current position. I created 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 take an action.

like image 84
Gacha Avatar answered Feb 19 '23 02:02

Gacha