Alexis Q.D Alexis Q.D - 5 months ago 8
jQuery Question

Doesn't work onclick properly in chrome

The first button

onclick
works, but when the
onclick
is set to
stopChrono()
instead of
chrono()
, the
stopChrono()
doesn't work. This only happens in Chrome, because in Mozilla and Edge, works perfectly.

This is the code of the web:
https://jsbin.com/mononohute/edit?html,js,output

P.S: This post isn't the same as the other "Onclick doesn't work in Chrome" because the circunstances are totally diferent.

Answer

jQuery conveniently stores event listeners, so if you define them in separate functions, you can easily remove them:

function stopChrono() {
    clearInterval(chronometer);
    $(this).attr('class', 'w3-btn w3-green')
    $('#start').off('click', stopChrono)
    $('#start').on('click', startChrono)
}

function startChrono(e) {
    $(this).attr('value', function (_, text) {
        $(this).attr("class", "w3-btn w3-red")
        return text === 'Stop!' ? 'Start!' : 'Stop!';
    })
    $('#start').off('click', startChrono)
    $('#start').on('click', stopChrono)
}

$('#start').on('click', startCrono);

Once the chrono is started, I removed the 'click' event listener because the next click should not start the chrono. I also added the stopChrono 'click' event listener because it should stop the chrono.

The reverse is true for stopChrono(): the 'click' listener is disconnected from stopChrono, and reconnected to startChrono.

Now you should be able to go back and forth.