Alexis Q.D Alexis Q.D - 1 year ago 68
jQuery Question

Doesn't work onclick properly in chrome

The first button

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

This is the code of the web:,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 Source

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

function stopChrono() {
    $(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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download