The simplest way to solve this (if you want the event to be activated only once each time the user visits the page. ) would 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
by a conditional OR ||
, as per your need. So at first it checks whether your panel has already been displayed, if it has not, it displays and changes the state to true
. Thus, this code is no longer executed, unless you change this in the code later.
Additionally, you can leave the && hasBeenTriggered
block else if
who will always return true
if the panel has already been opened, to ensure that the navSecundariaHide()
not be called unnecessarily in the future.
I don’t know if that was exactly your goal. That’s the simplest way I can think of at the moment.
EDIT: Applying the @Renato Tavares example to the OP example, it would look something like this:
$(window).one('scroll', function(e){ ... }
Instead of calling the method .on(event,handler)
, exchange it for .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 placed of the Docs of jQuery. Although it did not have time to test it, it seems that the use would be even simpler than the use of the variable hasBeenTriggered
as I suggested.
The Upside to use the variable would be the case you want to check whether the panel yet is open or closed, depending on what the flow of your code and your goal is.
sensational, I can’t even thank you man.
– Fábio Chiquezi