Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I launch a JavaScript or jQuery event when I reach the top of my page?

I have a simple problem, but I can't find the solution ... I just want to launch an event (which execute a method) when I scroll my page up and I "touch" the top of it. I'm using JavaScript and jQuery in my page. Thanks in advance !

like image 421
DaveLeGO Avatar asked Nov 28 '22 08:11

DaveLeGO


1 Answers

You should use the scroll event for that purpose:

$(window).scroll(function() {
    if ($(this).scrollTop() == 0) {
        //Do whatever you want to do
    }
});

One thing you should notice is that this way when somebody scrolls to top continuously the even will be fired although you only want it once the top is hit, for this you can define the event handler as a function and put the last scrolltop value into a function local variable.

$(window).scroll(handleHitTop);

function handleHitTop(event) {
    var currentScrollTopValue = $(this).scrollTop();

    if (handleHitTop.lastTop === undefined) {
        handleHitTop.lastTop = currentScrollTopValue ;

        return;
    }

    if (handleHitTop.lastTop == 0 && currentScrollTopValue == 0) {
        return;
    }

    handleHitTop.lastTop = currentScrollTopValue;

    if (handleHitTop.lastTop == 0) {
        //Call your event here
    }
}
like image 96
Mohammed R. El-Khoudary Avatar answered Dec 10 '22 21:12

Mohammed R. El-Khoudary