Search code examples
javascriptjqueryfocus

use Jquery to set focus to input with keydown


I am using a site that has a search box and I would like it so when you press the space bar but don't have the search text box selected, the search text box gets focus and has it's text cleared. I have it about done, but the check to see if the search box has focus isn't functioning properly. Any suggestions on my code? As is, if you press the space bar, it clears the search box, even if you're typing in the search box.

document.addEventListener('keydown', function (event) {
        if (event.keyCode == 32) {
            if ($('#searchTextBox').not(':focus')) {
                $("#searchTextBox").focus().select();
            }
        }
    });

Solution

  • While you delegate a keydown event on the document, you can also check if the source/target is the textbox itself by using event.target. If the event comes from the text field, just ignore it.

    $(document).on('keydown', function (event) {  
        if (event.which == 32 && event.target.id != 'searchTextBox') 
            $("#searchTextBox").focus().select();                
    });
    

    Working example : https://jsfiddle.net/DinoMyte/mdu5fxkq/3/