About this snippet

Allow users to organize content by adding and removing tags dynamically. This script handles creating the tag element when the user presses Enter and provides a simple "x" button to delete them.

Size
1.7 KB
Uses
HTML, CSS, JavaScript
Loads
Nothing external
Views
483
<div class="tag-wrapper">
  <div class="tag-container" id="tagContainer">
    <input type="text" id="tagInput" placeholder="Type and press Enter...">
  </div>
  <p class="helper-text">Press Enter to add a tag</p>
</div>
.tag-wrapper {
  font-family: system-ui, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  max-width: 400px;
}
.tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  background: #fff;
  border: 1px solid #d1d5db;
  padding: 8px;
  border-radius: 8px;
  min-height: 45px;
}
.tag-container:focus-within {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}
.tag {
  background: #e0f2fe;
  color: #0369a1;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 0.85rem;
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
}
.remove-tag {
  cursor: pointer;
  font-size: 1rem;
  line-height: 1;
  color: #0369a1;
}
#tagInput {
  border: none;
  outline: none;
  flex: 1;
  font-size: 0.95rem;
  min-width: 120px;
  padding: 4px;
}
.helper-text {
  color: #9ca3af;
  font-size: 0.8rem;
  margin-top: 5px;
}
const tagInput = document.getElementById("tagInput");
const tagContainer = document.getElementById("tagContainer");

tagInput.addEventListener("keypress", function(e) {
  if (e.key === "Enter" && this.value.trim() !== "") {
    const tagText = this.value.trim();
    createTag(tagText);
    this.value = "";
  }
});

function createTag(text) {
  const tag = document.createElement("div");
  tag.classList.add("tag");
  tag.innerHTML = `${text} <span class="remove-tag" onclick="this.parentElement.remove()">&times;</span>`;
  tagContainer.insertBefore(tag, tagInput);
}
Esc
↑↓ moveEnter select

Start from a template

Open an .html file, or HTML, CSS, JS, Markdown, Less or TypeScript files. You can also drop them here. Styles and scripts go into their panes.

Share

Source

Keyboard shortcuts

Save