-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkeyEvent.js
More file actions
62 lines (41 loc) · 1.31 KB
/
keyEvent.js
File metadata and controls
62 lines (41 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// addEventListener = listen ofr specific events to create a interactive webpage
// Event:keydown,keyUp ,keypress
// ---------------------------------example-1
let my_box = document.getElementById('mybox');
document.addEventListener('keydown',event =>{
my_box.textContent = '😉';
my_box.style.backgroundColor = 'tomato'
console.log(`key up ${event.key}`);
})
document.addEventListener('keyup',event =>{
console.log(`key up ${event.key}`);
my_box.textContent = '😎';
my_box.style.backgroundColor = 'wheat';
})
// ---------------------------example-2
let mybox = document.getElementById('mybox');
const moveamount = 10;
let x = 0;
let y = 0;
document.addEventListener('keydown', event => {
if (event.key.startsWith('Arrow')) {
event.preventDefault();
switch (event.key) {
case 'ArrowUp':
y -= moveamount;
break;
case "ArrowDown":
y += moveamount;
break;
case 'ArrowLeft':
x-= moveamount;
break;
case 'ArrowRight':
x+= moveamount;
break;
}
mybox.style.top = `${y}px`
mybox.style.left = `${x}px`
mybox.style.right = `${x}px`
}
})