Onclick with alternate calls

1

I would like to know if there is any way to implement an alternate call in the onclick function, so when I click it once it executes a function, and when I click again call another function ...

An example would be using checkbox . When I click the first time it displays a message "You selected this option" and does a calculation of addition, so if I click again it will appear a message "You have deselected this option", and do a subtraction calculation ... The checkbox generally does not work like this, but could also be for example a simple power button on and off. Lastly, I wonder if it is possible to perform this switch using onclick and how it would be.

Thank you.

    
asked by anonymous 27.11.2016 / 19:00

1 answer

2

Yes it is possible, you 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>
    
27.11.2016 / 19:09