Onclick with alternate calls

Asked

Viewed 39 times

1

I wonder if there is any way to implement an alternate call in the function onclick, so that when I click once it performs a function, and when I click again call another function ...

An example would be using a checkbox. When I click the first time it displays a message "You have selected this option" and makes an addition calculation, then if I click again it appears a message "You have unchecked this option", and do a subtraction calculation... The checkbox usually does not work like this, but could also be for example a simple on and off button. Finally, I would like to know if it is possible to perform this alternation using the onclick and how it would be.

Thank you.

1 answer

2


Yes it is possible, just have a click counter and know if the count is even or odd.

It could be something like this:

var alternador = (function(contador) {
    return function(e) {
        contador++;
        if (contador % 2 == 0) {
            // fazer algo
            console.log(contador, 'par');
        } else {
            // fazer outra coisa
            console.log(contador, 'impar');
        }
    }
})(0);
var elemento = document.querySelector('button');
elemento.addEventListener('click', alternador);
<button type="'button">Clica aqui!</button>

Browser other questions tagged

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