Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keydown not detected until window is clicked

In my web application I have an event listener for a key that opens a menu. This works just fine only AFTER I have clicked anywhere on the page. I have tried to add focus to the window onload...but this still does not let the keydown function run until after I have clicked somewhere on the page.

Does anyone know if this is possible? I can't imagine that it is not, but .focus(); is not the goto as far as I have tried

Example of my primary function:

    document.addEventListener('DOMContentLoaded', function() {
        // I have tried window.focus(); and window.document.focus(); 
        document.addEventListener('keydown', function(event) {
            var key = event.keyCode;
            if (key == 36) {
                toggleMenu();
                event.preventDefault();
            }
        });
    });
like image 467
Spencer May Avatar asked Nov 09 '22 21:11

Spencer May


1 Answers

Check this fiddle here : fiddle

Use $(window).focus(); (with jquery)

EDIT : Here's the solution in native javascript : fiddle

First the check_focus() function focuses on the window if the document doesnt have focus and then detects a keypress.

Hope this helps.

like image 147
stark Avatar answered Nov 14 '22 21:11

stark