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.