javascriptjqueryhtml

Assign the "/" hotkey to create focus user on search box


The website I'm building has a searchbar at the top of it. Similar to Trello or Gmail I want to make it so when the user pushes the "/" key, their focus goes to that searchbox.

My javascript looks like this:

document.onkeydown = checkShortcuts;
function checkShortcuts(event) {
    console.log(event.keyCode);
    if (event.keyCode == 191) {  // 191 == "/" key
        var text_input = document.getElementById ('sitesearch');
        text_input.focus ();
        text_input.select ();
        $('#sitesearch').val("");
    }
}

The problem I'm having is that upon hitting the / key, not only is the focus put on my search bar, but the "/" character is ALSO displayed in my search bar. I've tried to remove that by doing a jquery .val("") but that gets conducted before the letter is typed.

If I move the onkeydown to onkeyup, then when I type "/" I get the quick find window in firefox which isn't what I want either.

Any ideas how I can set focus but then not type that character onto the text field?


Solution

  • If you already mixing JS/jQuery you could make it shorter e.g.

    $(document).keydown(function() {
      if(event.keyCode == 191) {
         $('#sitesearch').focus();
         return false;
      }
    });