I have a page in a modal window where I am displaying a slide show. The intended audience is for tablet users and they navigate the show by swiping from the right to the left or the left to the right to see the next or previous slide. This all works beautifully.
However, in the event that someone does view the page using a computer, I would like them to be able to navigate using the arrow keys on their keyboard. I’m able to detect the keystroke, but only after the user has clicked inside the modal window. I would really like the user to not have to click anywhere before the keyboard navigation shows up. It doesn’t seem to matter what I try, this is always the problem.
Please note, because this is a modal window, it brings its contents in through the use of an iFrame.
Here is the code. I have confirmed that it does run when the page loads, and the pageTurn function works with other events:
document.onkeydown = function(e){
if (e == null) {
keycode = event.keyCode;
} else {
keycode = e.which;
}
if(keycode == 37){
pageTurn('right');
} else if(keycode == 39){
pageTurn('left');
}
};
Try attaching the event to
document.documentElementinstead of justdocument.If this fails, try adding
document.body.focus()to ensure the document is ready to receive keyboard input.EDIT: Inside an iFrame, the event needs to be attached to the
top.document.documentElementinstead, or attached to all frames as explained here