Search code examples
javascriptjqueryjquery-events

Execute and Stop JavaScript when page reach a certain position


I have a script that I want to execute only when a user reaches a position X (under my Nav bar) and to stop only when the user reaches this position X again (under my Nav bar).

How to achieve this effect?

EDIT:

How can I implement this code:

    var reachedFromTop = false;
var reachedFromBottom = false;
$(window).scroll(function() {
    //After scrolling 100px from the top...
    if ($(window).scrollTop() > 100 ) {
        if (!reachedFromTop) something();
        reachedFromTop = true;
    } else if (reachedFromTop && otherCondition) {
        if (!reachedFromBottom) somethingElse();
        reachedFromBottom = true;
    }  
});

in my existing script:

var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('.main-navigation').outerHeight();

$(window).scroll(function(event){
    didScroll = true;
});

setInterval(function() {
    if (didScroll) {
        hasScrolled();
        didScroll = false;
    }
}, 250);

function hasScrolled() {
    var st = $(this).scrollTop();

   if(Math.abs(lastScrollTop - st) <= delta)
        return;

if (st > lastScrollTop && st > navbarHeight){
$('.main-navigation').removeClass('nav-down').addClass('nav-up');
} else {
if(st + $(window).height() < $(document).height()) {
$('.main-navigation').removeClass('nav-up').addClass('nav-down');
}
}

lastScrollTop = st;
}

Solution

  • you should be able to do something like this.

    var reachedFromTop = false;
    var reachedFromBottom = false;
    $(window).scroll(function() {
        //After scrolling 100px from the top...
        if ($(window).scrollTop() > 100 ) {
            if (!reachedFromTop) something();
            reachedFromTop = true;
        } else if (reachedFromTop && otherCondition) {
            if (!reachedFromBottom) somethingElse();
            reachedFromBottom = true;
        }  
    });
    

    and you need to include jquery as your dependency