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();
}
});
});
Use $(window).focus();
(with jQuery):
$(document).ready(function() {
$(window).focus();
$(document).keyup(function(e) {
if (e.keyCode === 36) {
alert("Home Key Pressed");
}
});
});
EDIT: Here's the solution in native JavaScript:
function check_focus() {
if (!document.hasFocus()) {
window.focus();
}
}
// EXAMPLE USAGE
(() => {
check_focus();
document.addEventListener("keydown", function (event) {
var key = event.keyCode;
if (key === 36) {
alert("Home Key Pressed");
event.preventDefault();
}
});
})();
First the check_focus()
function focuses on the window if the document doesnt have focus and then an event listener is added.
Hope this helps.