How to perform an action when reaching certain height of the scroll?

5

I have a function in which every time I give scroll it calls a certain function, only I want to call it only once

    $(window).on('scroll', function(e){
        //aparece segundo menu
        if($(this).scrollTop() >= navHeight + section01Height){
            navSecundariaShow();
        }
        else if($(this).scrollTop() < navHeight + section01Height){
            navSecundariaHide();
        }

    });

That is, as soon as it reaches a certain height of scroll , it calls this function.

But you can not call every time from there, how do I?

    
asked by anonymous 02.01.2015 / 20:02

2 answers

8

The simplest way to resolve this (if you want the event to be only once every time the user visits the page) would be to use a variable to check if the behavior has already occurred (or not).

var hasBeenTriggered = false;

$(window).on('scroll', function(e){
    //aparece segundo menu
    if($(this).scrollTop() >= navHeight + section01Height && !hasBeenTriggered){
        navSecundariaShow();
        hasBeenTriggered = true;
    }
    else if($(this).scrollTop() < navHeight + section01Height && hasBeenTriggered){
        navSecundariaHide();
    }

});  

You can also change the && of else if to a condition% OR || , according to your need. So at first it checks to see if your dashboard has already been displayed, if it was not, it displays and changes the status to true . So, this code does not run any more, unless you change it in the code later.

In addition, you can leave && hasBeenTriggered of block else if which will always return true if the panel has already been opened, to make sure that the navSecundariaHide() method is not called unnecessarily in the future.

I do not know if that was exactly what it was about. That's the simplest way I can think of right now.


EDIT: Applying the example of @Renato Tavares to the OP example would look something like this:

$(window).one('scroll', function(e){ ... }

Instead of calling the .on(event,handler) method, changing it to .one(event,handler) as suggested would cause the event to be activated only the first time it is called. For other uses you can see the link that our colleague put of jQuery docs. Although I did not have time to test it, it would seem that the use would be even simpler than using the hasBeenTriggered variable as I suggested.

The upside of using the variable would be the case if you want to check if the panel is open or closed, depending on how your code flows and your objective.

    
02.01.2015 / 20:20
2

You've already tried using .one() according to documentation it only runs once. The example is as follows:

$( "#foo" ).one( "click", function() {
  alert( "This will be displayed only once." );
});

In your case a .off(event) should already resolve:

$( "#foo" ).on( "click", function( event ) {
  alert( "This will be displayed only once." );
  $( this ).off( event );
});
    
02.01.2015 / 20:23