-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
52 lines (45 loc) · 1.34 KB
/
index.js
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
const tagContainer = document.querySelector('.tag-container');
const input = document.querySelector('.tag-container input');
let tags = [];
function createTag(label) {
const div = document.createElement('div');
div.setAttribute('class', 'tag');
const span = document.createElement('span');
span.innerHTML = label;
// const closeIcon = document.createElement('i');
// closeIcon.innerHTML = 'x';
// closeIcon.setAttribute('data-item', label);
div.appendChild(span);
// div.appendChild(closeIcon);
return div;
}
function clearTags() {
document.querySelectorAll('.tag').forEach(tag => {
tag.parentElement.removeChild(tag);
});
}
function addTags() {
clearTags();
tags.slice().reverse().forEach(tag => {
tagContainer.prepend(createTag(tag));
});
}
input.addEventListener('keyup', (e) => {
if (e.key === 'Enter') {
e.target.value.split(',').forEach(tag => {
tags.push(tag);
});
addTags();
input.value = '';
}
});
document.addEventListener('click', (e) => {
console.log(e.target.tagName);
if (e.target.tagName === 'I') {
const tagLabel = e.target.getAttribute('data-item');
const index = tags.indexOf(tagLabel);
tags = [...tags.slice(0, index), ...tags.slice(index + 1)];
addTags();
}
})
input.focus();