Run event only if another event has already been run

Asked

Viewed 38 times

0

I have two listeners for the event scroll and I need the second to be executed only if the first has already been executed previously, just once, until the first event runs again. For example, I have the X and Y events; X can only execute if the Y event has already been run before and can only be run again when Y is run again, as a kind of re-start of event X.

How to do something like this in Javascript?

  • For more assertiveness in the answer I could mention what would be the names of these events X and Y?

  • Well, my question is a scroll event on a web page, when the scroll reaches that value, it will make an animation on a logo, and when the value of the scroll goes back to the previous one it will make another animation, but the second animation can only occur if the first one has already been executed before, and just after the second if the value of the scroll changes again you can make the animations A or B only if the previous one is the opposite!

1 answer

2


What you can do is assign the listener of the second event only when the first event occurs; and, when executed, remove the listener, so that it is added again in the execution of the first event. The logic would be similar to this:

function eventoX(event) {
  // ...
  document.removeEventListener('X', eventoX);
}

document.addEventListener('Y', event => {
  // ...
  document.addEventListener('X', eventoX);
});

For example, considering that both events are button clicks, we will make the B button click event occur only if the A button has already been pressed:

const A = document.getElementById('a');
const B = document.getElementById('b');

function eventoEmB(event) {
  console.log('Você pressionou o botão B');
  B.removeEventListener('click', eventoEmB);
}

A.addEventListener('click', event => {
  console.log('Você pressionou o botão A');
  B.addEventListener('click', eventoEmB);
});
<button id="a">Botão A</button>
<button id="b">Botão B</button>

Note that the event in B will only be triggered if the event in A has been fired earlier, just once.

  • As I do from the first time that event B is executed A can only be executed if B is executed, in which case the exception would be only First A at the beginning, the second A would already need B before it!

  • @Arthur74 this didn’t make any sense to me. I could explain in more detail?

  • ex: I can press the A button several times, and all of it is fired, the B depends on a previous shot of the A! It would need that the A can only be executed from the second time, if and only if the B has been fired!

  • @Arthur74 and that’s not exactly what my answer does?

  • the start yes, but from the second shot of the A button it would have to have the conditions equal to the B button, and can only be fired if the B has been fired before and not itself.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.