1

If I have a textbox and a button:

<input id='text'/> <button id='btn'>Click me</button>

And my button sends focus to the text box somewhere in it's click event:

$(document).ready(function(){

  $('#btn').click(function(event){
    console.log('btn ');
    $('#text').focus();
  });

  $('#text').keyup(function(event){
    console.log('key ');
  });

});

...if you use the enter key to trigger the button click, somehow, the text element that is receiving focus also receives the enter keypress.

Here is a fiddle showing this behavior:

https://jsfiddle.net/qup6keLd/

Use the tab key to set focus to the button, then press the Enter key. Both events will be triggered. Using space to trigger the button's click won't do this. Why is this happening, and how do I prevent it (outside of removing the focus() call?)

jgwl
  • 305
  • 1
  • 13
  • I think the event is propagating down the tree. You can consume the event to prevent it from propagating, but I can't remember how. – Carcigenicate Jul 22 '16 at 22:25
  • 1
    @Carcigenicate `e.stopPropgation()` – Polyov Jul 22 '16 at 22:26
  • Here's a good answer that deals with [events in Javascript](http://stackoverflow.com/questions/4616694/what-is-event-bubbling-and-capturing) – Polyov Jul 22 '16 at 22:28
  • @Polyov Thanks. Clojure has pushed all the JS of of my head lol. – Carcigenicate Jul 22 '16 at 22:29
  • I should have added that I tried stopPropagation(), but it didn't change the outcome. I think it's because the two elements are siblings, so standard propagation isn't happening; it's some other mechanism that is passing along the enter key press. – jgwl Jul 25 '16 at 13:53

1 Answers1

1

Use keypress event instead of keyup event.

The jQuery documentation details the differences between the two.

See the updated fiddle:

$(document).ready(function(){
    $('#text').keypress(function(event){
    $('#output').append('key ');
  });
  $('#btn').click(function(event){
    $('#text').focus();
    $('#output').append('btn ');
  });
});

Updated Fiddle

Polyov
  • 2,281
  • 2
  • 26
  • 36
atul
  • 552
  • 4
  • 16
  • Thanks, that does the trick. I think the key sentence in the doc is, "A keypress event handler can be attached to any element, but the event is **only sent to the element that has the focus**" – jgwl Jul 25 '16 at 13:55