keyboard events


Window, KeyUp, KeyDown


Html

<button id="keyBtn">Click ME</button>

const btn = document.getElementById('keyBtn')
btn.addEventListener('click', () => {
console.log('btn-clicked')
})

result: btn-clicked

The window object


clicking anywhere on the screen, we would get the result. Not just clicking on the button

Html

<button id="keyBtn">Click ME</button>

window.addEventListener('click', () => {
console.log('window got clicked')
})

window got clicked

keyup and keydown


Passing 2 event listener on the window object (window is an object)

- keyUp event, will be activated all time you press a key and then leave it

- instead, KeyDown will be activated in the same time you press it

window.addEventListener('keydown', () => {
console.log('a key was pressed DOWN')
})

result: a key was pressed DOWN


// clicking any key on the keyboards

keyup and keydown


window.addEventListener('keydown', () => {
console.log('a key was pressed DOWN')
})

result: holding down the key the count on console goes on



window.addEventListener('keyup', () => {
console.log('a key was let UP')
})

result: releasing the key, it stops, and warns us that "a key was let UP"


To find code and Key property


window.addEventListener('keydown', function(e) {
console.log('Key:', e.key)
console.log('Code:', e.code)
})

pressing 'm' on the keyboard

result: Key: m
Code: KeyM


Traversing boxes


Html

<section id="section"> </section>

Javascript


let position = 1;
let length = 0;


window.addEventListener('keydown', function(e) {
switch (e.code) {
case 'ArrowLeft':
if (length > 0) {
moveLeft();
}
break;
case 'ArrowRight':
if (length > 0) {
moveRight();
}
break;
case 'Space':
addBox();
break;
case 'Backspace':
if (length > 0) {
removeBox();
}
}
});


function addBox() {
const newDiv = document.createElement('div');
const section = document.getElementById('section');
section.append(newDiv);
if (length === 0) {
newDiv.classList.add('active');
}
length++;
}


function removeBox() {
if (position === length) {
moveLeft();
}
document.querySelector('div:last-child').remove();
length--;
}


function moveLeft() {
document.querySelector(`div:nth-of-type(${position})`).classList.remove('active');
position--;
if (position < 1) {
position = length;
}
document.querySelector(`div:nth-of-type(${position})`).classList.add('active');
}


function moveRight() {
document.querySelector(`div:nth-of-type(${position})`).classList.remove('active');
position++;
if (position > length) {
position = 1;
}
document.querySelector(`div:nth-of-type(${position})`).classList.add('active');
}

Controls


Monitor result ⬇️