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();
}
});
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With