Skip to content

Commit dec664e

Browse files
committed
[LES-17.4/st-compl] handling-keydown-event
Practice with "keydown" event. Getting "event.code === Enter". Worth noting: - both the lesson material and additional practice. FS-dev: B-3 / JS basic
1 parent 072f172 commit dec664e

File tree

7 files changed

+218
-0
lines changed

7 files changed

+218
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
4+
<head>
5+
<meta charset="UTF-8">
6+
<meta http-equiv="X-UA-Compatible" content="IE=edge">
7+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
8+
<title>DOM</title>
9+
<link rel="stylesheet" href="./styles.css">
10+
<script src="./index.js" defer></script>
11+
</head>
12+
13+
<body style="background-color: #1c1b21; text-align: center">
14+
<img src="./logo.svg" alt>
15+
<div class="panel">I love this!</div>
16+
<input class="input" id="input">
17+
<button class="button">Change</button>
18+
</body>
19+
20+
</html>
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
'use strict';
2+
3+
const panelMessage = document.querySelector('.panel');
4+
const input = document.querySelector('.input');
5+
const button = document.querySelector('.button');
6+
7+
// DRY
8+
function changeMessage() {
9+
const inputValue = input.value;
10+
11+
if (!inputValue) {
12+
return;
13+
}
14+
15+
panelMessage.textContent = inputValue;
16+
input.value = '';
17+
}
18+
19+
// изменения сообщения через "click" по кнопке
20+
function changeMessageByClick() {
21+
changeMessage();
22+
}
23+
24+
button.addEventListener('click', changeMessageByClick);
25+
26+
// изменения сообщения через "keydown/Enter" в поле input
27+
function changeMessageByKeydown(event) {
28+
// без объекта event не обойтись, т.к. в нём определяем code кнопки.. "Enter"
29+
if (event.code === 'Enter') {
30+
changeMessage();
31+
}
32+
}
33+
34+
input.addEventListener('keydown', changeMessageByKeydown);
Lines changed: 25 additions & 0 deletions
Loading
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
4+
<head>
5+
<meta charset="UTF-8">
6+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
7+
<title>DOM - practice</title>
8+
<link rel="stylesheet" href="./style.css">
9+
<script src="./index.js" defer></script>
10+
</head>
11+
12+
<body id="body">
13+
<input id="myInput" type="text" placeholder="Нажми пробел здесь...">
14+
15+
<form>
16+
<input id="itemInput" type="text" placeholder="Новый пункт и нажми Enter">
17+
</form>
18+
19+
<ul id="itemList"></ul>
20+
</body>
21+
22+
</html>
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
'use strict';
2+
3+
// Задание 1:
4+
// У тебя есть простое текстовое поле. Напиши HTML и JavaScript код, который будет выводить в консоль сообщение 'Привет!' каждый раз, когда пользователь нажимает клавишу Пробел, находясь в этом поле.
5+
// <input type="text" id="myInput" placeholder="Нажми пробел здесь...">
6+
7+
const input = document.querySelector('#myInput');
8+
9+
function sayHi(event) {
10+
if (event.code === 'Space') {
11+
console.log('Привет!');
12+
}
13+
}
14+
15+
input.addEventListener('keydown', sayHi);
16+
17+
// Задание 2:
18+
// У тебя есть поле для ввода и пустой список под ним.
19+
// Задача: Напиши скрипт, который по нажатию на Enter в поле ввода будет:
20+
// 1. Создавать новый пункт списка (<li>) с текстом из поля ввода.
21+
// 2. Добавлять этот новый пункт в список (<ul>).
22+
// 3. Очищать поле ввода, чтобы можно было вводить следующую задачу.
23+
// 4. И, конечно же, предотвращать перезагрузку страницы.
24+
// <form>
25+
// <input type="text" id="itemInput" placeholder="Новый пункт и нажми Enter">
26+
// </form>
27+
// <ul id="itemList"></ul>
28+
29+
const itemInput = document.querySelector('#itemInput');
30+
const itemList = document.querySelector('#itemList');
31+
32+
function addItem(event) {
33+
if (event.code === 'Enter') {
34+
const inputValue = itemInput.value;
35+
36+
if (!inputValue) {
37+
return;
38+
}
39+
40+
const element = document.createElement('li');
41+
element.textContent = inputValue;
42+
itemList.append(element);
43+
44+
itemInput.value = '';
45+
event.preventDefault();
46+
}
47+
}
48+
49+
itemInput.addEventListener('keydown', addItem);
50+
51+
// Задание 3:
52+
// Представь, что на твоём сайте есть "тёмная тема". Нужно сделать её переключение с помощью "горячей клавиши".
53+
// Задача: Напиши скрипт, который будет переключать (то есть добавлять, если нет, и убирать, если есть) CSS-класс dark-mode на элементе <body> по нажатию комбинации клавиш Alt + M.
54+
// Подсказки:
55+
// 1. Чтобы комбинация работала в любом месте страницы, а не только в поле ввода, "слушателя" событий нужно вешать на весь document.
56+
// 2. Для переключения класса есть очень удобный метод: element.classList.toggle('имя-класса').
57+
// У тебя уже есть весь document.
58+
59+
const body = document.querySelector('#body');
60+
61+
function changeTheme(event) {
62+
if (event.altKey && event.code === 'KeyM') {
63+
body.classList.toggle('dark-theme');
64+
}
65+
}
66+
67+
document.addEventListener('keydown', changeTheme);
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
body {
2+
background-color: #fff;
3+
color: #222;
4+
}
5+
6+
body.dark-theme {
7+
background-color: #121212;
8+
color: #eee;
9+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
.panel {
2+
margin-bottom: 20px;
3+
border-radius: 10px;
4+
padding: 40px;
5+
font-size: 18px;
6+
color: white;
7+
background: rgba(255, 255, 255, .05);
8+
}
9+
10+
.input {
11+
border: 1px solid rgba(212, 212, 212, .05);
12+
border-radius: 10px;
13+
padding: 15px 16px;
14+
height: 56px;
15+
box-sizing: border-box;
16+
font-size: 18px;
17+
line-height: 21px;
18+
color: white;
19+
box-shadow: none;
20+
outline: none;
21+
background: rgba(255, 255, 255, .05);
22+
}
23+
24+
.button {
25+
display: inline-flex;
26+
justify-content: center;
27+
align-items: center;
28+
border: none;
29+
border-radius: 10px;
30+
padding: 20px 40px;
31+
box-sizing: border-box;
32+
text-align: center;
33+
color: white;
34+
background: #6c38cc;
35+
cursor: pointer;
36+
transition: all .2s;
37+
}
38+
39+
.button:hover {
40+
background-color: #844fe6;
41+
}

0 commit comments

Comments
 (0)