Html
<button id="keyBtn">Click ME</button>
const btn = document.getElementById('keyBtn')
btn.addEventListener('click', () => {
console.log('btn-clicked')
})
result: btn-clicked
Html
<button id="keyBtn">Click ME</button>
window.addEventListener('click', () => {
console.log('window got clicked')
})
window got clicked
window.addEventListener('keydown', () => {
console.log('a key was pressed DOWN')
})
result: a key was pressed DOWN
// clicking any key on the keyboards
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"
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
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');
}
Monitor result ⬇️