Keyup event listener fires when a Chrome Ominbox button is clicked

In the Chrome browser when using this snippet:

$(document).on('keyup', function(){ alert("Hey"); }); 

Each time I press enter in the url line (for example, when I cut and paste the URL of the page itself), an event listener fires. Why is this happening?

EDIT:

This surprised me because the url string is not in document (possibly in window ?), And firefox does not have this behavior. When I search for e.target , the Chrome Inspector shows body .

I thought this could be triggered by an event bubble, so I tried this:

  $(document).on('keyup', function(e){ e.stopPropagation(); alert("Hey"); }); 

But that will not work. How can I prevent it from starting?

+7
source share
5 answers

This is because, as soon as you press enter in the omnibox, focus moves to the page. If you tried to do the same with onkeydown , omnibox will not change anything, because, as you said, this is not part of the document. One way to filter out the omnibox false event is to verify that each keyup has a pair of keystrokes.

 <script> var down = false; document.addEventListener('keydown', function (){ down = true; }, false); document.addEventListener('keyup', function (){ if(down === true){ alert('It was from the page!'); } else{ alert('Omnibox. Ignore it.'); } down = false; }, false); </script> 

Demo version

Create your own HTML page and try it because PasteHTML.com embeds it in an iframe. To make it work correctly, first click on the text to get the iframe focus.

Demo Remember to use the mouse to focus on omnibox and enter, not a keyboard shortcut. (This fires the onkeydown event, creating a false positive)

Update:. As for Chrome 35, this is no longer happening. However, I do not know which version they fixed.

+8
source

The solution for Chrome is simple: use keypress instead of keyup . This does not work in all cases (IE), so you may need to add a condition to switch the type depending on the browser. However, this will solve your problem.

Please note that searching for a specific code can negate your problem. Good luck.

+2
source

Because keyup happens when any key is issued on the keyboard, which causes an event. Chrome just fires this event when the document has no focus, apparently when using a fragment.

+1
source

You can filter the key code ... if that helps ... 13 enter the key

 $(document).on('keyup', function(event){ if( parseInt(event.keyCode,10) !== 13 ){ alert("Hey"); } });โ€‹ 
0
source

A possible solution is to slightly delay the registration of the keyup event handler. This will miss the first โ€œfalseโ€ trigger that seems to happen in Chrome and Safari.

 $(function() { setTimeout( function() { console.log("Delayed event attachment"); $(document).bind('keyup', log); }, 10); }); function log(e) { console.log(e.target.localName); } 
0
source

All Articles