Execute event only if another event has already been executed [closed]

0

I have two listeners for the scroll event, and I need the second to be executed only if the first one has already been executed previously, only once, until the first event is executed again. For example, I have event X and Y; X can only be run if event Y has already been run previously and can only be run again when Y is also run again as a sort of restart event of X.

How to do something like this in JavaScript?

    
asked by anonymous 06.06.2018 / 05:15

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 look like 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 click event on button B only occur if button A 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>

Notice that the event in B will only be triggered if the event in A has been triggered only once.

    
07.06.2018 / 15:44