Skip to content

Event delegation #262

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,18 @@

<div id="container">
<div class="pane">
<h3>Horse</h3>
<p>The horse is one of two extant subspecies of Equus ferus. It is an odd-toed ungulate mammal belonging to the taxonomic family Equidae. The horse has evolved over the past 45 to 55 million years from a small multi-toed creature, Eohippus, into the large, single-toed animal of today.</p>
<h3>Кінь</h3>
<p>Кінь є одним із двох існуючих підвидів дикого коня (Equus ferus). Це парнокопитний ссавець, що належить до таксономічної родини коневих (Equidae). За останні 45-55 мільйонів років кінь еволюціонував із маленької багатопалої істоти, Еогіппа (Eohippus), до великої однопалої тварини сучасності.</p>
<button class="remove-button">[x]</button>
</div>
<div class="pane">
<h3>Donkey</h3>
<p>The donkey or ass (Equus africanus asinus) is a domesticated member of the horse family, Equidae. The wild ancestor of the donkey is the African wild ass, E. africanus. The donkey has been used as a working animal for at least 5000 years.</p>
<h3>Осел</h3>
<p>Осел (Equus africanus asinus) є одомашненим представником сімейства коней (Equidae). Диким предком осла є африканський дикий осел (E. africanus). Осел використовувався як робоча тварина щонайменше 5000 років.</p>
<button class="remove-button">[x]</button>
</div>
<div class="pane">
<h3>Cat</h3>
<p>The domestic cat (Latin: Felis catus) is a small, typically furry, carnivorous mammal. They are often called house cats when kept as indoor pets or simply cats when there is no need to distinguish them from other felids and felines. Cats are often valued by humans for companionship and for their ability to hunt vermin.
<h3>Кіт</h3>
<p>Домашній кіт (лат. Felis catus) — невеликий, типово пухнастий, хижий ссавець. Їх часто називають домашніми котами, якщо їх триваюсь вдома, або просто котами, коли немає необхідності відрізняти їх від інших котячих. Люди часто цінують котів за товариські стосунки і за їх здатність полювати на шкідників.
</p>
<button class="remove-button">[x]</button>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,25 +10,25 @@

<div id="container">
<div class="pane">
<h3>Horse</h3>
<p>The horse is one of two extant subspecies of Equus ferus. It is an odd-toed ungulate mammal belonging to the taxonomic family Equidae. The horse has evolved over the past 45 to 55 million years from a small multi-toed creature, Eohippus, into the large, single-toed animal of today.</p>
<h3>Кінь</h3>
<p>Кінь є одним із двох існуючих підвидів дикого коня (Equus ferus). Це парнокопитний ссавець, що належить до таксономічної родини коневих (Equidae). За останні 45-55 мільйонів років кінь еволюціонував із маленької багатопалої істоти, Еогіппа (Eohippus), до великої однопалої тварини сучасності.</p>
<button class="remove-button">[x]</button>
</div>
<div class="pane">
<h3>Donkey</h3>
<p>The donkey or ass (Equus africanus asinus) is a domesticated member of the horse family, Equidae. The wild ancestor of the donkey is the African wild ass, E. africanus. The donkey has been used as a working animal for at least 5000 years.</p>
<h3>Осел</h3>
<p>Осел (Equus africanus asinus) є одомашненим представником сімейства коней (Equidae). Диким предком осла є африканський дикий осел (E. africanus). Осел використовувався як робоча тварина щонайменше 5000 років.</p>
<button class="remove-button">[x]</button>
</div>
<div class="pane">
<h3>Cat</h3>
<p>The domestic cat (Latin: Felis catus) is a small, typically furry, carnivorous mammal. They are often called house cats when kept as indoor pets or simply cats when there is no need to distinguish them from other felids and felines. Cats are often valued by humans for companionship and for their ability to hunt vermin.
<h3>Кіт</h3>
<p>Домашній кіт (лат. Felis catus) — невеликий, типово пухнастий, хижий ссавець. Їх часто називають домашніми котами, якщо їх триваюсь вдома, або просто котами, коли немає необхідності відрізняти їх від інших котячих. Люди часто цінують котів за товариські стосунки і за їх здатність полювати на шкідників.
</p>
<button class="remove-button">[x]</button>
</div>
</div>

<script>
// ...your code...
// ...Ваш код...
</script>

</body>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ importance: 5

---

# Hide messages with delegation
# Приховайте повідомлення за допомогою делегування

There's a list of messages with removal buttons `[x]`. Make the buttons work.
Є список повідомлень із кнопками видалення `[x]`. Зробіть так, щоб кнопки працювали.

Like this:
В результаті має працювати наступним чином:

[iframe src="solution" height=420]

P.S. Should be only one event listener on the container, use event delegation.
P.S. У контейнері має бути лише один прослуховувач подій, використовуйте делегування.
6 changes: 3 additions & 3 deletions 2-ui/2-events/03-event-delegation/2-sliding-tree/solution.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
The solution has two parts.
Рішення складається з двох частин.

1. Wrap every tree node title into `<span>`. Then we can CSS-style them on `:hover` and handle clicks exactly on text, because `<span>` width is exactly the text width (unlike without it).
2. Set a handler to the `tree` root node and handle clicks on that `<span>` titles.
1. Обертаємо кожен заголовок дерева в `<span>`. Тоді ми можемо додати їм CSS стилі на `:hover` і обробляти клік саме по тексту, тому що ширина `<span>` повністю співпадає з шириною тексту.
2. Встановлюємо обробник на кореневий вузол `tree` та обробляємо кліки на елементах `<span>`, які містять заголовки.
Original file line number Diff line number Diff line change
Expand Up @@ -17,60 +17,60 @@
<body>

<ul class="tree" id="tree">
<li>Animals
<li>Тварини
<ul>
<li>Mammals
<li>Ссавці
<ul>
<li>Cows</li>
<li>Donkeys</li>
<li>Dogs</li>
<li>Tigers</li>
<li>Корови</li>
<li>Осли</li>
<li>Собаки</li>
<li>Тигри</li>
</ul>
</li>
<li>Other
<li>Інші
<ul>
<li>Snakes</li>
<li>Birds</li>
<li>Lizards</li>
<li>Змії</li>
<li>Птахи</li>
<li>Ящірки</li>
</ul>
</li>
</ul>
</li>
<li>Fishes
<li>Риби
<ul>
<li>Aquarium
<li>Акваріумні
<ul>
<li>Guppy</li>
<li>Angelfish</li>
<li>Гуппі</li>
<li>Риба-янгол</li>
</ul>
</li>
<li>Sea
<li>Морські
<ul>
<li>Sea trout</li>
<li>Морська форель</li>
</ul>
</li>
</ul>
</li>
</ul>

<script>
// move all text into <span>
// they occupy exactly the place necessary for the text,
// помістіть кожен текстовий вузол у елемент <span>
// він займає саме те місце, яке необхідне для тексту,
for (let li of tree.querySelectorAll('li')) {
let span = document.createElement('span');
li.prepend(span);
span.append(span.nextSibling); // move the text node into span
span.append(span.nextSibling); // поміщаємо текстовий вузол у span
}

// catch clicks on whole tree
// ловимо кліки на всьому дереві
tree.onclick = function(event) {

if (event.target.tagName != 'SPAN') {
return;
}

let childrenContainer = event.target.parentNode.querySelector('ul');
if (!childrenContainer) return; // no children
if (!childrenContainer) return; // дітей немає

childrenContainer.hidden = !childrenContainer.hidden;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,36 +6,36 @@
<body>

<ul class="tree" id="tree">
<li>Animals
<li>Тварини
<ul>
<li>Mammals
<li>Ссавці
<ul>
<li>Cows</li>
<li>Donkeys</li>
<li>Dogs</li>
<li>Tigers</li>
<li>Корови</li>
<li>Осли</li>
<li>Собаки</li>
<li>Тигри</li>
</ul>
</li>
<li>Other
<li>Інші
<ul>
<li>Snakes</li>
<li>Birds</li>
<li>Lizards</li>
<li>Змії</li>
<li>Птахи</li>
<li>Ящірки</li>
</ul>
</li>
</ul>
</li>
<li>Fishes
<li>Риби
<ul>
<li>Aquarium
<li>Акваріумні
<ul>
<li>Guppy</li>
<li>Angelfish</li>
<li>Гуппі</li>
<li>Риба-янгол</li>
</ul>
</li>
<li>Sea
<li>Морські
<ul>
<li>Sea trout</li>
<li>Морська форель</li>
</ul>
</li>
</ul>
Expand Down
10 changes: 5 additions & 5 deletions 2-ui/2-events/03-event-delegation/2-sliding-tree/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ importance: 5

---

# Tree menu
# Деревоподібне меню

Create a tree that shows/hides node children on click:
Створіть дерево, яке показує/приховує дочірні вузли при кліці:

[iframe border=1 src="solution"]

Requirements:
Вимоги:

- Only one event handler (use delegation)
- A click outside the node title (on an empty space) should not do anything.
- Тільки один обробник подій (використовуйте делегування)
- Клік поза заголовком вузла (на порожньому місці) не має нічого робити.
Original file line number Diff line number Diff line change
Expand Up @@ -25,30 +25,30 @@
<table id="grid">
<thead>
<tr>
<th data-type="number">Age</th>
<th data-type="string">Name</th>
<th data-type="number">Вік</th>
<th data-type="string">Ім’я</th>
</tr>
</thead>
<tbody>
<tr>
<td>5</td>
<td>John</td>
<td>Іван</td>
</tr>
<tr>
<td>2</td>
<td>Pete</td>
<td>Петро</td>
</tr>
<tr>
<td>12</td>
<td>Ann</td>
<td>Ганна</td>
</tr>
<tr>
<td>9</td>
<td>Eugene</td>
<td>Євген</td>
</tr>
<tr>
<td>1</td>
<td>Ilya</td>
<td>Ілля</td>
</tr>
</tbody>
</table>
Expand All @@ -59,10 +59,10 @@
if (e.target.tagName != 'TH') return;

let th = e.target;
// if TH, then sort
// cellIndex is the number of th:
// 0 for the first column
// 1 for the second column, etc
// якщо клітинка TH, тоді сортувати
// cellIndex - це номер клітинки th:
// 0 для першого стовпця
// 1 для другого і т.д.
sortGrid(th.cellIndex, th.dataset.type);
};

Expand All @@ -71,7 +71,7 @@

let rowsArray = Array.from(tbody.rows);

// compare(a, b) compares two rows, need for sorting
// compare(a, b) порівнює два рядки, необхідно для сортування
let compare;

switch (type) {
Expand All @@ -87,7 +87,7 @@
break;
}

// sort
// сортування
rowsArray.sort(compare);

tbody.append(...rowsArray);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@
<meta charset="utf-8">
<style>
table {
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding: 4px;
}
th {
cursor: pointer;
}
th:hover {
background: yellow;
}
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding: 4px;
}
th {
cursor: pointer;
}
th:hover {
background: yellow;
}
</style>
</head>

Expand All @@ -25,36 +25,36 @@
<table id="grid">
<thead>
<tr>
<th data-type="number">Age</th>
<th data-type="string">Name</th>
<th data-type="number">Вік</th>
<th data-type="string">Ім’я</th>
</tr>
</thead>
<tbody>
<tr>
<td>5</td>
<td>John</td>
<td>Іван</td>
</tr>
<tr>
<td>2</td>
<td>Pete</td>
<td>Петро</td>
</tr>
<tr>
<td>12</td>
<td>Ann</td>
<td>Ганна</td>
</tr>
<tr>
<td>9</td>
<td>Eugene</td>
<td>Євген</td>
</tr>
<tr>
<td>1</td>
<td>Ilya</td>
<td>Ілля</td>
</tr>
</tbody>
</table>

<script>
// ...your code...
// ...Ваш код...
</script>

</body>
Expand Down
Loading