Problem with "on change" followed by "on click"

Asked

Viewed 251 times

1

I have the following HTML code:

<input type="text" id="esc" />
<input type="button" value="Ok" id="ok" />

And jquery/javascript:

$(document).on("change", "#esc", function(){
    alert("esc");
});

$(document).on("click", "#ok", function(){
    alert("ok");
});

When I type a text in a textbox and right click on Ok it does not execute the code within the click function. Only the code of the change function.

Follow me on the fiddle: http://jsfiddle.net/8389g5rj/1/

What is the reason for this and how can I resolve this "conflict" ?

1 answer

5


Joao,

What happens is this.

When you change the text, thus releasing Trigger from the textbox change and trying to click the button. The event is triggered before the click and Alert is called, so cancel your click event.

If you change the code to the following.

$(document).on("change", "#esc", function(){
    console.log("esc");
});

$(document).on("click", "#ok", function(){
    console.log("ok");
});

You will see that the two events are fired normally. The problem with your example is Alert, which becomes preemptive and prevents you from triggering the button click event, because it "passes ahead".

It seemed?

To explain better. Is your button event the right "click"? It is triggered when the user clicks the button. But in your text input it triggers the change event as soon as you leave the text input, and per milliseconds (perspective for us humans) it triggers the change event and inside the change event calls the Alert BEFORE that you were able to effectively click the button. And when Alert was called "canceled" your click, why in fact you couldn’t click the button OK.

  • 1

    So if I don’t have any Alert in my actual code this problem won’t occur? I didn’t get the preemptive definition

  • 1

    @Joaopaulo If you have nothing to "interrupt" the next event. Why Alert is called, it depends on a user action and it is preemptive, in other words for the browser an Alert is more important than the next event (for example). Simply without the Alerts your event will be shot normally.

  • Interestingly, I wasn’t aware of that kind of behavior!

  • See my latest issue where I try to explain better.

Browser other questions tagged

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