Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keyup event listener fires when enter is pressed on Chrome's Ominbox

In chrome browser, when using this snippet:

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

Every time I press enter in the url bar (for example when I cut and paste the url of the page itself) the event listener fires. Why does it happen?

EDIT:

It surprised me because url bar is not in document (maybe in window?) and firefox does not have this behaviour. When I look for e.target, Chrome Inspector shows body.

I thought this could be caused by event bubbling so I tried this:

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

But it doesn't work. How can I prevent it from being triggered?

like image 616
Manuel Bitto Avatar asked Aug 16 '12 15:08

Manuel Bitto


2 Answers

This happens because once you hit enter in the omnibox, the focus turns to the page. If you tried the same thing with onkeydown, the omnibox would change nothing, because as you said, it isn't a part of the document. One way to filter the omnibox's false event out would be to check that every keyup has a pair keydown.

<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.

Make your own HTML page and try it preferably, because PasteHTML.com stuffs it into an iframe. For it to work correctly there, click on the text first to give the iframe focus.

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

Update: As of Chrome 35, this doesn't happen anymore. I don't know which version they fixed it on, however.

like image 122
Some Guy Avatar answered Sep 20 '22 23:09

Some Guy


The solution for Chrome is simple: use keypress instead of keyup. This doesn't work in all cases (IE), so you may have to add a conditional to switch the type depending on the browser. However, this will solve your issue.

Note that looking for a specific keycode may negate your issue. Good luck.

like image 23
jedd.ahyoung Avatar answered Sep 18 '22 23:09

jedd.ahyoung