4

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.

BigDog
  • 41
  • 1
  • 3
  • you could check the absolute scroll position, http://stackoverflow.com/questions/3464876/javascript-get-window-x-y-position-for-scroll – Robin Manoli May 22 '13 at 19:37

2 Answers2

7

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.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Gacha
  • 1,037
  • 8
  • 18
1

Without jQuery, you can achieve the same thing like this:

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
    }
});
SwankyLegg
  • 473
  • 4
  • 14