0

Hi I've written a script that creates a black bar over an image on the hover event. That vlack bar disappears when the user starts scrolling. Because there is no ScrollEnd event I've created a timer like suggested here Event when user stops scrolling

It works well but when I violently scroll back and forth the black bar begins to reappear. I'm not quite sure why this happening but I assume the timer is assigned to a different scroll event each time.

Any Idea on how to fix this?

JsFiddle: http://jsfiddle.net/7kw8z/29/

Scroll event code:

function scroll(imageContainer, menu){
imageContainer.mousewheel(function(event, delta, deltaX, deltaY) {
    event.preventDefault();
    $("p").text(delta);
    menu.css("visibility", "hidden");

    $.data(this, 'timer', setTimeout(function() {
    menu.css("visibility", "visible");
      }, 1000));
});

}

Community
  • 1
  • 1
Ryan King
  • 3,538
  • 12
  • 48
  • 72
  • possible duplicate of [jQuery: Event, when User stops scrolling](http://stackoverflow.com/questions/3701311/jquery-event-when-user-stops-scrolling) – Stephan Muller Sep 22 '14 at 20:44

1 Answers1

1

You should stop the old timeout before starting the new one. You get a timeoutId back when you call setTimeout(). Holding on to that id doesn't affect whether or not the timeout will execute after the delay. It just gives you a way to cancel it if you need to.

var existingTimeout = $(this).data("timer");

if(existingTimeout)
{
    clearTimeout(existingTimeout);
}

$(this).data("timer", setTimeout(function() { 
  menu.css("visibility", "visible"); 
}, 1000));
Patrick Hallisey
  • 888
  • 6
  • 11