Reputation: 1276
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');
}
};
Upvotes: 0
Views: 5710
Reputation: 324640
Try attaching the event to document.documentElement
instead of just document
.
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.documentElement
instead, or attached to all frames as explained here
Upvotes: 5
Reputation: 324567
document
is fine for attaching key events. Also, keyCode
is the correct property in all major browsers for keydown
and keyup
events, so there's no need to mess around with which
.
For attaching to the parent document from within an iframe, as one of your comments suggests, you need to use parent
(for the immediate parent document's window) or top
(the outermost document's window):
parent.document.onkeydown = function(e) {
e = e || parent.event;
var keyCode = e.keyCode;
if (keyCode == 37) {
pageTurn('right');
} else if (keyCode == 39) {
pageTurn('left');
}
};
Upvotes: 0
Reputation: 328594
Maybe your key codes are wrong. Here is a page which shows you the codes for your browser: http://asquare.net/javascript/tests/KeyCode.html
If the codes are correct, compare the event handling code on this page with your version.
Upvotes: -2