Reputation: 14052
I have a website were I'd like to react upon arrow key events. I added a keydown
listener, which works as long as I don't click in the site. After clicking, the keydown
no longer gets triggered.
Since the behavior is the same for Chrome and Firefox I suspect I am missing something.
Following the source code:
<!DOCTYPE html>
<html>
<head>
<style>
html, body, embed
{
position: absolute;
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
border: 0px;
}
</style>
<script>
var keyHandler = function(event) {
alert( "EV" + event );
};
window.addEventListener( 'keydown', keyHandler, true );
</script>
</head>
<body>
<embed src="http://upload.wikimedia.org/wikipedia/commons/6/6b/Bitmap_VS_SVG.svg"/>
</body>
</html>
Could someone point out, what I am missing?
Upvotes: 0
Views: 257
Reputation: 14052
What I ended up doing was loading the external SVG into the document body. The whole problem goes away then (while others surface). With jquery this would look like so:
<body>
<script>
$(document.body).load("mygreat.svg");
</script>
</body>
Upvotes: 0
Reputation: 50563
Brent's answer gave you the rationale for this and the clean solution, I will give you the crude workaround in case you can't stop using an embed
tag.
That is to place an invisible span or div element above your embed viewport, that way when people click over the embed content they will be really clicking on your invisible element so the focus is not transfered to the embededd element and so your window.keydown
handler will be fired.
See https://stackoverflow.com/a/9614949/352672 for an example code for this workaround.
Upvotes: 1
Reputation: 2971
The problem is that you're using an embed
element for the entire viewport. Embed elements are for embedding multimedia into your site. Once the focus is moved to that element (by clicking), it hijacks your events.
You can see this in action here: http://jsfiddle.net/blineberry/p6rXP/ Click in the results window but not on the image and press a key. Then click on the image and press a key. Then click off the image and press a key.
If you use an img
element instead of an embed
the problem is resolved: http://jsfiddle.net/blineberry/p6rXP/1/
Upvotes: 3