Simple Javascript Tagging Widget (Free Download)

Welcome to a tutorial on how to create a simple tagging widget with Javascript. Need to add tags to your audio, video, post, product, or whatever else? Well, we don’t actually need any third-party frameworks – Here is a simple example with pure Javascript – Read on!

 

 

TABLE OF CONTENTS

 

JAVASCRIPT TAGGING WIDGET

All right, let us now get into some details of the Javascript itself. This is for you guys who want to “deep customize” it.

 

QUICK START

1-tag.html
<!-- (A) JS & CSS -->
<script src="2-tag.js"></script>
<link rel="stylesheet" href="3-tag.css">
 
<!-- (B) ATTACH TAGGING HERE -->
<div id="demo"></div>
<small>Hit enter or comma to add a tag.</small>
 
<!-- (C) THE JAVASCRIPT -->
<script>
// (C1) TO ATTACH TAGGER
taggr.attach({
  target : document.getElementById("demo"), // required, target <div>
  tags : ["Doge", "Cate"], // optional, default tags
  maxLength : 12, // optional, max tag characters
  maxTags : 3 // optional, max number of tags
});
 
// (C2) TO GET TAGS
// var tags = document.getElementById("demo").getTags()
</script>

For you guys who just want to use this as a “plugin”:

  1. Captain Obvious at your service, load the Javascript and CSS.
  2. Create an empty <div> to generate the tags widget.
  3. Call taggr.attach() to create the tags widget.
    • target Target HTML element to generate the tags widget, required.
    • tags Default tags to append, optional.
    • maxLength The maximum number of characters, optional.
    • maxTags The maximum number of tags, optional.
    • To get the list of tags in your own function, use document.getElementById("TAGS").getTags().

 

 

THE JAVASCRIPT

2-tags.js
var taggr = {
  // (A) ATTACH TAGGING
  len : 0, // track number of characters for "backspace remove tag"
  attach : instance => {
    // (A1) TAGS WRAPPER
    instance.target.classList.add("tagwrap");
 
    // (A2) ATTACH INPUT FIELD
    instance.tagin = document.createElement("input");
    instance.tagin.type = "text";
    instance.tagin.className = "tagin";
    if (instance.maxLength !== undefined) { instance.tagin.maxLength = instance.maxLength; }
    instance.target.appendChild(instance.tagin);
 
    // (A3) COMMA OR ENTER TO ADD TAG
    instance.tagin.onkeyup = evt => {
      // (A3-1) COMMA OR ENTER TO ADD TAG
      if (evt.code=="Comma" || evt.code=="Enter") {
        if (instance.tagin.value=="," || instance.tagin.value=="") {
          instance.tagin.value = "";
        } else {
          taggr.add(instance, instance.tagin.value.replace(/,/g, ""));
        }
      }
 
      // (A3-2) BACKSPACE TO REMOVE LAST TAG (IF CURRENT VALUE IS EMPTY)
      if (evt.code=="Backspace" && taggr.len == 0) {
        let last = instance.target.querySelectorAll(".tag");
        if (last.length>0) { last[last.length - 1].remove(); }
      }
    };
 
    // (A4) ATTACH DEFAULT TAGS
    if (instance.tags !== undefined) {
      instance.tags.forEach((name, i) => taggr.add(instance, name));
    }
 
    // (A5) GET TAGS
    instance.target.getTags = () => {
      let tags = [];
      Array.from(instance.target.querySelectorAll(".tag"))
      .forEach(tag => tags.push(tag.innerHTML));
      return tags;
    };
  },
 
  // (B) ADD A NEW TAG
  add : (instance, name) => {
    // (B1) CHECK MAX TAGS
    if (instance.maxTags !== undefined) {
      let count = instance.target.querySelectorAll(".tag").length;
      if (count >= instance.maxTags) {
        alert(`Maximum ${instance.maxTags} tags allowed.`);
        return;
      }
    }
 
    // (B2) CREATE & APPEND NEW TAG
    let tag = document.createElement("div");
    tag.className = "tag";
    tag.innerHTML = name;
    tag.onclick = () => tag.remove();
    instance.target.insertBefore(tag, instance.tagin);
 
    // (B3) EMPTY TAG INPUT
    instance.tagin.value = "";
  }
};

Uh oh, this looks “very confusing”, but keep calm and look carefully. There are only 2 functions here.

  • taggr.attach() You already know this, we use it to create the “tags widget”. Not going to explain line-by-line, read through the sections and they are very straightforward… It’s just long-winded.
  • taggr.add() Fired when the user hits “enter” or “comma”, appends a new tag in the wrapper.

 

 

GENERATED HTML

<div id="demo">
  <div class="tag">Doge</div>
  <div class="tag">Cate</div>
  <input type="text" class="tagin">
</div>

Yep, this is what taggr.attach() generates. Don’t think this needs an explanation…

 

THE CSS

3-tag.css
/* (A) WRAPPER */
.tagwrap {
  display: flex;
  border: 2px solid #aaa;
}
 
/* (B) SHARED TAGS */
.tagwrap .tag, .tagwrap .tagin {
  margin: 10px 5px;
  padding: 10px;
}
 
/* (C) TAGS */
.tagwrap .tag {
  color: #fff;
  background: #2d7dc1;
  cursor: pointer;
}
.tagwrap .tag::after {
  content: "X";
  padding-left: 20px;
}
 
/* (D) TAG INPUT */
.tagwrap .tagin {
  flex-grow: 1;
  background: none;
  border: 0;
}
.tagwrap .tagin:focus {
  outline-width: 0;
  outline: none;
}

Lastly, just CSS cosmetics to make things look better. Nothing much really… We simply set the <div> wrapper to display: flex, the tags and text input field will “flow” quite flawlessly.

 

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here to download. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

EXTRA BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

COMPATIBILITY CHECKS

This example will work on all modern “Grade A” browsers.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *