Keyboard Sequence Detection
Today we'll be making a Key Sequencing Detection that is when some one inputs a certain sequence of keys into your window then something happens, used most of the time online for Konami Code.
First of all we would we would create an empty array to store all the keys we type and also create a secret code of our choice.
const pressed = [];
const secretCode = "harsh";
Now we would add a keyup
event on the window and we and we would extract the keycode
and add it into the array.
window.addEventListener("keyup", (e) => {
pressed.push(e.key);
);
But this would keep increasing the size of the array as we go on typing so we need to trim the array to the maximum size we would ever need that is the size of our secret code.
For that we would use splice()
and since we want to trim the array from the back that is as soon as the array goes beyond the required size it will start removing elements from the start.
window.addEventListener("keyup", (e) => {
pressed.push(e.key);
pressed.splice(
-secretCode.length - 1,
pressed.length - secretCode.length
);
Now finally we would check if the array contains our secret code or not and for that we would convert the individual array elements into a string using .join()
and then use includes()
function to see if our secret code is present in the array.
window.addEventListener("keyup", (e) => {
pressed.push(e.key);
pressed.splice(
-secretCode.length - 1,
pressed.length - secretCode.length
);
if (pressed.join("").includes(secretCode)) {
console.log("secretCode Matched");
cornify_add();
}
});
We also used
<script
type="text/javascript"
src="https://www.cornify.com/js/cornify.js"
></script>
and with this our project for the day was completed.
GitHub repo:
Blog on Day-11 of javascript30
Blog on Day-10 of javascript30
Blog on Day-9 of javascript30
Follow me on Twitter
Follow me on Linkedin
DEV Profile
You can also do the challenge at javascript30
Thanks @wesbos , WesBos to share this with us! ππ
Please comment and let me know your views
Top comments (10)
coolππ
thanks
thanks.
Unicornππ
yup loved them.
can add this too
add what?
a failed attempt of uploading img
cool
thanks