Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trigger function if scroll reaches a certain point only once. Not every time

I want to check if my users arrive at a certain point in my page. SO I created the following JS code:

$(document).on('scroll', function() {
    if($(this).scrollTop()>=$('#page2').position().top){

    alert("trigger");
    }
})

Which checks if the users reached my id="page2". But I want this to trigger ONLY once, no matter if the users goes back up and back down, right now it gets trigger everytime the page2.position().top = scrollTop.

How can I do this ?

like image 933
user3011784 Avatar asked Dec 19 '16 07:12

user3011784


1 Answers

You can use event.namespace and off() to unbind event handler after execution of desired statement.

$(document).on('scroll.something', function() {
    if ($(this).scrollTop() >= $('#page2').position().top) {
        //Do something

        //Unbind the event
        $(document).off('scroll.something')
    }
})
like image 151
Satpal Avatar answered Nov 01 '22 16:11

Satpal