Click Me! Js $('#clickMe').button();...">

JQuery UI click event fires twice when a key is pressed

HTML

<button id="clickMe" tabindex=0>Click Me!</button> 

Js

 $('#clickMe').button(); $('#clickMe').click(function() { alert('hey'); }); $(document).keypress(function (e) { var key = e.keyCode ? e.keyCode : e.which; //detect when the user has hit enter if (key == 13) { //click the focused element $(document.activeElement).click(); } }); 

Why does this warning fire twice when you press the tab to focus the button and enter for the key press event, but only fire once when you press the button with the mouse?

Demonstration

EDIT : tab + enter doesn't work at all in IE 10

+1
source share
2 answers

Since pressing "Enter" when the focus is on the button, triggers the "click" event initially. You also get the "keypress" event, and from that you fire the "click" event again.

+7
source

I am responding here to Pointy's comment instead of comments due to lack of space;

I can confirm that I see that the button click starts in JSbin, but I'm not sure how to explain the difference between my actual application code code and what is on the page. Perhaps this is due to the fact that I attached my "click" to a separate line, rather than binding it.

I have not yet learned how to use JSBin, but I solemnly promise to do it soon. However, my information was obtained from an experiment in my own code:

 $(settings.selectors.patientSearchSubmitButton).click(validatePatientSearch); 

Followed

 $(settings.selectors.patientSearchSubmitButton).click(alertOnClick); 

I also had another binding:

  $(settings.selectors.patientSearchParameter).keypress(function (e) { if (e.which == 13) {//Enter key pressed validatePatientSearch(); } }); 

patientSearchParameter was the box next to the button. When I focused on the field and hit enter in chrome, ff, plain IE11, the validatePatientSearch function was executed once, and the alertOnClick function did not start. When I did the same in IE11 compatibility mode for IE8, 9, 10; the function was executed twice, and alertOnClick was called. I'm not sure how I can prove this, but it was my experience, and it was repeated behavior after more than 20 or so tests. I am using the 64-bit version of Windows 7. Not sure what else could make it behave that way, but I hope this can be useful to someone.

Maybe because my click was tied to a button, and not to a field?

0
source

Source: https://habr.com/ru/post/983952/


All Articles