vortek
vortek

Reputation: 43

Detect Scroll event while already on top

I have a menu bar on the top of my page which i want to show if i scroll up while already on top. Imagine you scroll up, and while beeing there, you scroll up again, the bar would show.

I have this code using jquery

// listen for the scroll to show the top menu
var was_on_top = false;
$(function () {
    $(window).bind("scroll", function (e) {

        if ($(window).scrollTop() == 0) {
            if ($('.menu').css('display') == "none" && was_on_top) {
                $('.menu').slideDown();
            } else {
                was_on_top = true;
            }
        } else {
            was_on_top = false;
        }
    });
});

But the scroll event does not fire while already on top. Any ideas?

EDIT: Here goes the working code. Tested on FF, Chrome and IE9

// listen for the scroll to show the top menu
var was_on_top = false;
$(function () {
    if (window.addEventListener) {
        window.addEventListener('DOMMouseScroll', onMouseWheelSpin, false); // FireFox
        window.addEventListener('mousewheel', onMouseWheelSpin, false); // Chrome
    } else {
        window.onmousewheel = onMouseWheelSpin;
    }
});

function onMouseWheelSpin(event) {

    if (!event) // IE sucks
        event = window.event;

    if ($(window).scrollTop() == 0 &&
          (
            event.detail < 0 // Firefox
            ||
            (event.wheelDelta && (
                                    (window.opera && event.wheelDelta < 0) // Opera
                                    ||
                                    event.wheelDelta > 0 // IE
                                 )
            )
          )
        ) {
        if ($('.menu').css('display') == "none" && was_on_top) {
            $('.menu').slideDown();
        } else {
            was_on_top = true;
        }
    } else {
        was_on_top = false;
    }
}

Upvotes: 3

Views: 3616

Answers (1)

Kevin Boucher
Kevin Boucher

Reputation: 16675

The scroll event does not fire, because the window is no longer scrolling.

You will likely need to create a custom event for the mouse wheel itself.

This might be helpful: Javascript: Capture mouse wheel event and do not scroll the page?

Upvotes: 1

Related Questions