Reputation: 531
I am trying to provide full screen option in my web-page when the user presses "Space" and "Enter" keys simultaneously. I have the following code. I have the following code. But it is not working. Where am I going wrong? It is working if I give a single key.
<!doctype html>
<html>
<head>
<title>Full Screen Example</title>
<style type="text/css">
:-webkit-full-screen #myimage {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<p>Press "space" and "enter" to enter full screen</p>
<p><strong>To use full-screen mode, you need Firefox 9 or later or Chrome 15 or later.</strong></p>
<img src = "./3.jpg" width="640" height="360" id="myimage">
</body>
<script>
var imageElement = document.getElementById("myimage");
function toggleFullScreen() {
if (!document.mozFullScreen && !document.webkitFullScreen) {
if (imageElement.mozRequestFullScreen) {
imageElement.mozRequestFullScreen();
} else {
imageElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
}
} else {
if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else {
document.webkitCancelFullScreen();
}
}
}
document.addEventListener("keydown", function(e) {
if ((e.keyCode == 13) && (e.keyCode == 32)) {
toggleFullScreen();
}
}, false);
</script>
Upvotes: 1
Views: 140
Reputation: 9466
Remove your current addEventListener() call and augment your script with what I've provided below. Note that this won't work in IE8 (but considering you're using moz and webkit functions I imagine you aren't targeting it anyway).
var keys = [];
function keyIsDown(keyCode) {
return (keys.indexOf(keyCode) > -1);
}
document.addEventListener("keydown", function(e) {
// Remember the key being pressed
keys.push(e.keyCode);
// Check if ENTER and SPACE are both being pressed
if (keyIsDown(13) && keyIsDown(32)) {
toggleFullScreen();
}
}, false);
document.addEventListener("keyup", function(e) {
// Remember that this key is no longer being pressed
var keyIndex = keys.indexOf(e.keyCode);
if (keyIndex > -1) keys.splice(keyIndex, 1);
}, false);
Credit to parjun for the basic idea; I just worked this out without jQuery.
Upvotes: 1
Reputation: 130
You need to maintain an array of the keys being pressed and the keys being released.
var keyArray = [];
function containsAll(firstArray, secondArray){
for(var i = 0 , len = firstArray.length; i < len; i++){
if($.inArray(firstArray[i], secondArray) == -1) return false;
}
return true;
}
document.addEventListener("keydown", function(e) {
if ((e.keyCode == 13) || (e.keyCode == 32)) {
keyArray.push(e.keyCode);
}
if(containsAll(['13','32'],keyArray)){
toggleFullScreen();
}
}, false);
$(document).keyup(function (e) {
keyArray.remove(e.keyCode);
});
Upvotes: 0