I am trying to create a .js file for a website that upon entering the konami code Up, Up, Down, Down, Left, Right, Left, Right, B, A, Start(enter) it will embed a video. However while entering the right keys the webpage should display something like "keep going", if a wrong key is entered it should display "wrong, try again", and allow them to start over.
I've manged to get the JavaScript working where upon entering the right code it displays an alert, and entering the wrong code displays a different code.
i've manged to get this much code using online resources but none of them explain how to get wrong, try again part
if (window.addEventListener) {
var keys = [],
konami = "38,38,40,40,37,39,37,39,66,65,13";
window.addEventListener("keydown", function(e){
keys.push(e.keyCode);
if (keys.toString().indexOf(konami) >= 0)
{
alert('Right');
keys = [];
};
if (keys.toString().indexOf(konami) < 0)
{
alert('Wrong');
keys = [];
}
}, true);
};
Any help would be greatly appreciated.
if (window.addEventListener) {
var index = 0;
var konami = [38,38,40,40,37,39,37,39,66,65,13];
window.addEventListener("keydown", function(e){
if (e.keyCode === konami[index])
{
index++; //valid key at the valid point
if (index == konami.length)
{
alert("Correct");
} else {
alert("Keep going");
}
} else {
// incorrect code restart
index = 0;
alert("Wrong");
}
});
}
You could do something like
if (window.addEventListener) {
var keys = [],
konami = "38,38,40,40,37,39,37,39,66,65,13".split(',');
window.addEventListener("keydown", function(e){
keys.push(e.keyCode);
console.log(e.keyCode);
var lengthOfKeys = keys.length -1;
if (konami[lengthOfKeys] == keys[lengthOfKeys])
{
alert('Right');
if(konami.length === keys.length){
alert('complete!');
}
}else{
alert('Wrong');
keys = [];
}
}, true);
};
fiddle here http://jsfiddle.net/b6kuZ/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With