Skip to content

Instantly share code, notes, and snippets.

@Spirit-act
Last active March 8, 2022 20:49
Show Gist options
  • Save Spirit-act/826bddd6a19126e4c2b924bf4cd15f5b to your computer and use it in GitHub Desktop.
Save Spirit-act/826bddd6a19126e4c2b924bf4cd15f5b to your computer and use it in GitHub Desktop.
Tag Input Script
body {
background-color: #222;
color: white;
}
.input-wrapper{
background: transparent;
padding: 10px;
border-radius: 4px;
border: 1px solid #ccc
}
.input-wrapper input{
border: none;
background: transparent;
outline: none;
width: 140px;
margin-left: 8px;
color: white;
}
.input-wrapper .tag{
display: inline-block;
background-color: limegreen;
color: white;
border-radius: 2px;
padding: 0px 3px 0px 7px;
margin-right: 5px;
}
.input-wrapper .tag a {
margin: 0 7px 3px;
display: inline-block;
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form>
<div class="input-wrapper" id="wrapper">
<input type="text" id="wrapper-input">
</div>
<input type="text" id="names" hidden=true>
</form>
<script src="tags.js"></script>
</body>
</html>
class TagsInput {
constructor() {
this.tags = [];
this.el = document.getElementById("wrapper");
this.input = document.getElementById("wrapper-input");
this.input.addEventListener("keydown", (e) => {
if (!!~["Tab", "Enter", "NumpadDecimal"].indexOf(e.code)) {
e.preventDefault();
let str = this.input.value.trim();
this.input.value = "";
if (str != "") {
this.add(str);
}
}
});
}
add(tag) {
this.tags.push(tag);
this.render();
this.sendEvent(this.tags);
}
render() {
this.removeAllChildren();
this.tags.forEach((item) => {
let tag = document.createElement("span");
tag.className = "tag";
tag.innerText = item;
let ci = document.createElement("a");
ci.innerHTML = "&times;";
ci.addEventListener("click", (e) => {
const index = this.tags.indexOf(e.target.parentNode.firstChild.textContent);
if (index > -1) {
this.tags.splice(index, 1);
e.target.parentNode.remove();
this.sendEvent(this.tags);
}
});
tag.appendChild(ci);
this.el.insertBefore(tag, this.input);
});
}
removeAllChildren() {
while (this.el.firstChild.id !== "wrapper-input") {
this.el.firstChild.remove();
}
}
sendEvent(detail) {
document.dispatchEvent(
new CustomEvent("userUpdate", { detail: detail })
);
}
getElements() {
return this.tags;
}
}
const x = new TagsInput();
x.add('tag1');
x.add('tag-2');
x.add('tag_3');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment