最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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 !

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 !

Share Improve this question asked Feb 27, 2013 at 21:47 DaveLeGODaveLeGO 871 silver badge9 bronze badges 5
  • Should it also be launched when you open the page (because you're always on top when you open a website)? – Manticore Commented Feb 27, 2013 at 21:49
  • 1 api.jquery.com/scrollTop – j08691 Commented Feb 27, 2013 at 21:49
  • body.on.scroll = function() { if (window.is.top || document.above.fold && google.search.is.not.done() || I put(no.effort.into.this) ) alert('I'll do more research!'); } – adeneo Commented Feb 27, 2013 at 22:05
  • 1 @adeneo The string you're passing to alert contains an unterminated string literal! :D – bfavaretto Commented Feb 28, 2013 at 0:29
  • @adeneo : I know that I can easily find a solution online ;-), but like manticore says, I prefere to avoid this event when I open the page. And all the solutions I found launch it at the openning ... – DaveLeGO Commented Mar 1, 2013 at 10:24
Add a comment  | 

3 Answers 3

Reset to default 9

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
    }
}

Use the onscroll event. Vanilla js example:

window.onscroll = function() {
    if(document.body.scrollTop == 0) {
        alert('yay!');
    }
}

http://jsfiddle.net/kuWuf/

Use a .scroll() handler and .scrollTop():

$(window).scroll( function() {
    if($(this).scrollTop() == 0) {
        alert("Top!!!");
    }
});

http://jsfiddle.net/jtbowden/wvJ9r/

发布评论

评论列表(0)

  1. 暂无评论