jQuery plugin to tagging like a charm!

Overview

taggingJS

Build Status

jQuery plugin to tagging like a charm!

taggingJS is a jQuery plugin to create an high customizable front-end tag system. It is like 5 kb and support major browsers in the world!

Actual version is 1.3.3.

Example Image

Getting Started

You can find a working example in Codepen.io or in the project's GitHub page.

Simplest

  1. Download the tagging.min.js file from this repository;

  2. Include <script src="path/to/tagging.min.js"></script> to the bottom of your page;

  3. Optional - Include the basic CSS tag style <link href="tag-basic-style.css" rel="stylesheet"> to the <head> of your page;

  4. Add to your page something like <div data-tags-input-name="tag" id="tagBox">preexisting-tag</div>;

  5. Add to your main JavaScript file $("#tagBox").tagging();;

The data-tags-input-name="tag" is the name attribute used by each input inside the tagBox.

Manipulate tags with methods

Here there are some common pattern to manipulate tags inside the tag box:

N.B.: $tag_box is the tag box object. To get it:

var t, $tag_box;

// We call taggingJS init on all "#tag" divs
t = $( "#tag" ).tagging();

// This is the $tag_box object of the first captured div
$tag_box = t[0];

Get all tags (object)

// To get all tags inside tag box as an array of String
$tag_box.tagging( "getTags" );
>>> ["preexisting-tag", "another-tag"]

// To get all tags inside tag box as an array of jQuery Object
$tag_box.tagging( "getTagsObj" );
>>> [x.fn.x.init[1], x.fn.x.init[1]]

Add new tags

// To add a tag with "A new tag added via JS" as text
$tag_box.tagging( "add", "A new tag added via JS" );
>>> true

// To add two tag, one with "tag 1" and the other with "tag 2" as text
$tag_box.tagging( "add", ["tag 1", "tag 2"] );
>>> ["tag 1", "tag 2"]

Remove a tag

// To remove a tag with text "A new tag added via JS" as text
$tag_box.tagging( "remove", "A new tag added via JS" );
>>> $_obj

// To remove two tag, one with "tag 1" and the other with "tag 2" as text
$tag_box.tagging( "remove", ["tag 1", "tag 2"] );
>>> [$_obj]

// Suppose that $tag is the jQuerify object of a tag inside the tag box, you can also do
$tag_box.tagging( "remove", $tag] );
>>> $_obj

Remove all tags

// To remove all tags
$tag_box.tagging( "removeAll" );

// or
$tag_box.tagging( "reset" );

Get Special Keys

// To get special Keys without distinctions
$tag_box.tagging( "getSpecialKeys" );
>>> Object {comma: 188, enter: 13, spacebar: 32, del: 46, backspace: 8}

// To get special Keys with distinctions
$tag_box.tagging( "getSpecialKeysD" );
>>> Object {add: Object, remove: Object}

Add or Remove a Special Key

// To add the "left arrow" as a special key to add a new tag
$tag_box.tagging( "addSpecialKeys", [ "add", { left_arrow: 37 } ] );

// To add the "right arrow" as a special key to remove a tag
$tag_box.tagging( "addSpecialKeys", [ "remove", { right_arrow: 39 } ] );

// To remove the "right arrow" as a special key
$tag_box.tagging( "removeSpecialKeys", ["remove", 39] );

Disable taggingJS

// To disable taggingJS
$tag_box.tagging( "destroy" );

Empty the type_zone

// To disable taggingJS
$tag_box.tagging( "emptyInput" );

Get or Set the value of type_zone

// To set "value" as value of the input
$tag_box.tagging( "valInput", "value" );

// To get the value of the input
$tag_box.tagging( "valInput" );

Trigger Focus event the type_zone

// To Trigger Focus event the input
$tag_box.tagging( "focusInput" );

Detect when a Tag is Added or Removed

// Execute callback when a tag is added
$tag_box.on( "add:after", function ( el, text, tagging ) {
  console.log( "Added tag: ", text );
});

// Execute callback when a tag is removed
$tag_box.on( "remove:after", function ( el, text, tagging ) {
  console.log( "Removed tag: ", text );
});

Please, see all Available Methods.

Customize

There are several ways to customize the default behavior of taggingJS:

  1. Use a JavaScript custom_options object to customize the global taggingJS behavior (see First Way);

  2. Use data attributes in the tagBox HTML Markup (see Second Way);

  3. Use a combination of the first two way (see Third Way);

N.B.: Be careful! data attributes have an higher priority than the custom_options object, because each data attribute overwrite the global behavior. In other words, the global settings work for all tags box captured, unless in these are specified data attributes (which may change the behavior).

First Way - Global Object

  1. Create a custom options object, like this my_custom_options (see Available Options):

    var my_custom_options = {
    	"no-duplicate": true,
    	"no-duplicate-callback": window.alert,
    	"no-duplicate-text": "Duplicate tags",
    	"type-zone-class": "type-zone",
    	"tag-box-class": "tagging",
    	"forbidden-chars": [",", ".", "_", "?"]
    };
  2. Create a tag box (or multiple tag box) like this:

    <div id="tagBox">preexisting-tag</div>
  3. Add to your main JavaScript file:

    $("#tagBox").tagging( my_custom_options );

In this way, we customize the global behavior of taggingJS for all tag box caught with selector.

Second Way - Data Attributes

  1. Create a tag box with some data attributes, like this (see Available Options):

    <div
    	data-no-duplicate="true"
    	data-pre-tags-separator="\n"
    	data-no-duplicate-text="Duplicate tags"
    	data-type-zone-class="type-zone"
    	data-tag-box-class="tagging"
    	data-edit-on-delete="true"
    id="tagBox">preexisting-tag</div>
  2. Add to your main JavaScript file:

    $("#tagBox").tagging();

N.B.: Use data method with no-duplicate-callback and forbidden-chars can cause some problems. Avoid it.

Third Way - Mixed Way

In this way, we mix data attributes and options object to customize taggingJS behavior for each tag box.

  1. Create a tag box with some data attributes, like this:

    <div class="tag-box"
    	data-no-duplicate="true"
    	data-tags-input-name="tag"
    id="tagBox1">preexisting-tag</div>
  2. Create another tag box with no data attributes:

    <div id="tagBox1" class="tag-box">preexisting-tag</div>
  3. Create a custom options object, like this my_custom_options (see Available Options):

    var my_custom_options = {
    	"no-duplicate": false,
    	"tags-input-name": "taggone",
    	"edit-on-delete": false,
    };
  4. Add to your main JavaScript file

    $(".tag-box").tagging( my_custom_options );

Now you may see that:

  • The #tagBox1 has a behavior that overwrite some my_custom_options options:

    • Does not accept duplicate tag (for the respective data attribute);
    • For each tag, it has tag as input name (for the respective data attribute);
    • On delete, the tag is completely removed (for the my_custom_options);
  • The #tagBox2 has a behavior dictated only by my_custom_options:

    • Accept duplicate tag (for the my_custom_options);
    • For each tag, it has tag as input name (for the my_custom_options);
    • On delete, the tag is completely removed (for the my_custom_options);

Available Options

Below there are the available options to customize taggingJS with type, a little description and the default value:

Option Type Default Description
case-sensitive Boolean false If false, all text is treated like lowercase.
close-char String "&times;" Single Tag close character.
close-class String "tag-i" Single Tag close class.
edit-on-delete Boolean true true to edit tag that has just been removed from tag box.
forbidden-chars Array ["," , ".", "_", "?"] Array of forbidden characters.
forbidden-chars-callback Function window.alert Function to call when is detected a forbidden character.
forbidden-chars-text String "Forbidden character:" Basic text passed to forbidden-chars-callback.
forbidden-words Array [] Array of forbidden words.
forbidden-words-callback Function window.alert Function to call when is detected a forbidden words.
forbidden-words-text String "Forbidden word:" Basic text passed to forbidden-words-callback.
no-backspace Boolean false Backspace key remove last tag by default, true to avoid that.
no-comma Boolean false Comma "," key add a new tag by default, true to avoid that.
no-del Boolean false Del key remove last tag by default, true to avoid that.
no-duplicate Boolean true If true, there will be no duplicate tag's name in the tag box.
no-duplicate-callback Function window.alert Function to call when is detected a duplicate tag.
no-duplicate-text String "Duplicate tag:" Basic text passed to no-duplicate-callback.
no-enter Boolean false Enter key add a new tag by default, true to avoid that.
no-spacebar Boolean false Spacebar key add a new tag by default. true to avoid that.
pre-tags-separator String ", " This is used to split the initial text and add preexistint-tag. By default, you must put new tags using a comma and a space (", ").
tag-box-class String "tagging" Class of the tag box.
tag-box-editable-class String "editable" Class of the tag box when editable, used together with tags-limit option for css targeting.
tag-char String "#" Single Tag char.
tag-class String "tag" Single Tag class.
tag-on-blur Boolean true If true, clicking away from the $type_zone will add a new tag.
tags-input-name String "tag" Name to use as name="" in single tags' input. By default, all tags being passed as array like tag[].
tags-limit Integer 0 Limit the number of tags that can be added, zero for no limit.
type-zone-class String "type-zone" Class of the type-zone.

Available Methods

Below there are the available methods of taggingJS with a little description, the argument that it can take and the return type:

Method Description Argument Return
add( text or [text] ) Add a new tag. A String (or an Array of String) to add as tag, if null we get the content of tag box type_zone. Boolean or Funtion
add:after( function ) Execute the function after add a Tag. Depends on the function used as callback. Generic
addSpecialKeys( [ "type", obj ] ) Add a special keys to add or remove a tag. Array - Where "type" is "add" or "remove", obj is like { key_name: key_code } (it can be also an Array of obj). A String for error or Object Actually "type"_key (add_key or remove_key).
destroy() Remove type_zone, all tags and other things. void Boolean
emptyInput() Empty tag box's type_zone. void $_obj - The jQuerified type_zone itself.
focusInput() Trigger focus on tag box's type_zone. void $_obj - The jQuerified type_zone itself.
getDataOptions() Get Data attributes custom options. void Object - tag box data attributes custom options.
getSpecialKeys() Return all special keys inside an object (without distinction) void Object - All tags as member of strings.
getSpecialKeysD() Return all special keys inside an object (with distinction) void An Object with an add and remove properties.
getTagsObj() Return all tags as object void Array - All tags as member of objects.
init() Init method to bootstrap all things void $_obj - The jQuerify tag box.
refresh( text ) Remove and insert all tag A String with all tags separated by pre-tags-separator option value (if null, we call getTags method) Boolean
remove( text or $_obj ) Remove last tag or the specified ones in tag box's type_zone. A String or $_obj (or an Array of them) of the tag to remove. A String with error message or $_obj of the removed tag.
remove:after( function ) Execute the function after remove a Tag. Depends on the function used as callback. Generic
removeAll() Alias of reset void Array - All removed tags.
removeSpecialKeys( [ "type", obj ] ) Remove a special key . Array - Where "type" is "add" or "remove", obj is like { key_name: key_code } (it can be also an Array of obj). Object - Actually "type"_key (add_key or remove_key).
reset() Remove all tags from tag box's type_zone void Array - All removed tags.
valInput( text ) Get or set the tag box type_zone's value A String to put as tag box type_zone's value. The value String or $_obj of tag box's type_zone.

You can find example here.

Contribute

Set Up nodeJS and Grunt

  1. Fork the repository;

  2. Open a shell in project's directory;

  3. Type npm install (make sure you have installed nodeJS);

  4. Type grunt to execute the default script (without minification), grunt dist to also minify the script (make sure you have installed Grunt).

JavaScript Style Guide

I follow the jQuery's JavaScript style guide, please follow it you too :D

Also take a look to IdiomaticJS (Principles of Writing Consistent, Idiomatic JavaScript).

Requirements

  • jQuery (1.5.X or more, also 2.X works);

Browser Support

Supports all major browsers in the world (IE 6+, Mozilla Firefox 1+, Google Chrome 1+, Safari 5.1+).

License

(C) Fabrizio Fallico 2014, released under the MIT license.

Changelog (v1.3.X)

1.3.3 - [Oct 24, 2014]

1.3.1 - [Apr 28, 2014]

  • Radically changed the architecture of the plugin. Now we are more flexible to changes and pull requests.
  • Added basic methods.
  • Now you can add (and remove) custom special keys to add or remove tags (see Available Methods).
  • Fix #6, #8, #16, #17, #19 issues.
Comments
  • some problem in taggingJS

    some problem in taggingJS

    Hi, first, very thanks for great taggingJS plugin.

    first issue:you must prevent duplicate tag. second issue:after first line in textbox is fulled,next line will drop out of textbox While height of textbox must be grow, also between each line must exist little gap.

    tag

    bug enhancement 
    opened by KiarashS 5
  • this.tags is on the prototype instead of the element.

    this.tags is on the prototype instead of the element.

    This:

    Tagging.prototype = {
            tags: [],
    ...
    

    Should be:

    var Tagging = function(elem, options) {
            this.elem = elem;
            this.$elem = $(elem);
            this.options = options;
            this.tags = [];
    }
    

    In order to allow a user to use more than one tagging block per page.

    opened by ScarletCarson 3
  • Zero Width Chars

    Zero Width Chars

    I believe these two should be implemented in the system, two. http://www.fileformat.info/info/unicode/char/200c/index.htm http://www.fileformat.info/info/unicode/char/200B/index.htm

    question 
    opened by MHM5000 3
  • removing and then adding same tag didn't work

    removing and then adding same tag didn't work

    removing tags only removed the related DOM element. now also iterates over the "tags" array and removes entry there since this array is used to detect duplicates. don't forget to change minified version. :)

    bug 
    opened by loilo 2
  • add another same tag as a deleted one, then alert duplicate tag

    add another same tag as a deleted one, then alert duplicate tag

    1.I add a tag named 'test'. 2.I delete the tag. 3.I add another tag named 'test'. 4.I see the alert

    this is a bug

    http://codepen.io/sniperwolf/pen/geFxq/

    bug 
    opened by bennyzhao 2
  • Removing existing tags -- reappear.

    Removing existing tags -- reappear.

    On http://codepen.io/sniperwolf/pen/geFxq/

    1. I add a new tag after the existing tags
    2. I click the (x) to remove the second tag (another-tag)
    3. I backspace erase the new tag I added, backspace again and 'another-tag' text appears even tho I already clicked (x) to remove it previously.
    bug 
    opened by Braunson 2
  • Add citation marks around CSS selectors

    Add citation marks around CSS selectors

    In tagging.js on line 617, there should be citation marks around the CSS selector like this: $tag = self.$elem.find( "input[value='" + text + "']" ).parent(); rather than: $tag = self.$elem.find( "input[value=" + text + "]" ).parent();

    As it is now, the selector will fail finding tags e.g. containing a fullstop or an at (@).

    Error messages from a simple usage example:

    $("#tagBox").tagging("remove", "tag.1");
    Uncaught Error: Syntax error, unrecognized expression: input[value=tag.1]
        jQuery 5
        remove tagging.js:617
        tagging tagging.js:806
        jQuery 2
        tagging tagging.js:786
        <anonymous> debugger eval code:1
    

    Maybe there is even some more work to do to make it function correctly even with tags containing citation marks. Otherwise, thank you for this great project!

    opened by d-tamm 1
  • An option to limit the number of tags that can be added.

    An option to limit the number of tags that can be added.

    The number of tags that can be added can now be limited with the 'tags-limit' option. Default value is zero which equals to no limit.

    Also added an option 'tag-box-editable-class' which defines the name of the class that will be added to the tag box when new tags can be added. This can be used with css to for example to show the text-cursor when the tag box can be edited and to show a normal cursor otherwise.

    opened by harzzn 1
  • Raise event when tag is added and removed

    Raise event when tag is added and removed

    Hope it is useful to someone else, I need to listen to these events in my implementation:

    $("#tagBox").on('add:after', function(el, text, tagging) {
       console.log('Added tag: ', text);
    });
    
    opened by mattriverm 1
  • new instance issue

    new instance issue

    I have been using backbone to the create multiple tagging boxes in the same page. The issue is that no matter how I did the naming on the Id of each tagging div box and all the child tags will be always group into the first div tagging container box. It is related the new instance issue. Please fix it asap. thanks!

    keep appending new boxes and initialize your tagging() and the previous tags will always stick into the first box. this.tagbox = this.$('#tag-' + firstobject.id + '.btn-grou'); this.tagbox.tagging();

    opened by jjhesk 1
  • tags-limit seem to be broken with taggingJS (1.3.3) and jquery (3.2.1)

    tags-limit seem to be broken with taggingJS (1.3.3) and jquery (3.2.1)

    var t = $("#tag").tagging({ 'edit-on-delete': false, 'tags-limit': 5 }); t[0].addClass("form-control");

    Still allows the input of more then 5 tags

    opened by ole1986 0
  • taggingJS throws an error while typing . AKA fullstop

    taggingJS throws an error while typing . AKA fullstop

    I'm using below code to initialise the taaggingJS

    var myOptions =
            {
                "no-duplicate": true,
                "no-duplicate-callback": null,
                "type-zone-class": "type-zone",
                "tag-box-class": "tagging",
                "forbidden-chars": ["!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "_", "=", "+", "`", "~", "[", "]", "{", "}", "|", ";", ":", "'", "<", ">", ",", ".", "/", "?"],
                "forbidden-chars-callback": null
                // chars not included ", 
            };
    
    $("#post_tags").tagging(myOptions);
    

    Whenever i am typing . (fullstop) in the div, it responds with an error stating

    Uncaught TypeError: b is not a function at n.throwError (tagging.min.js:1)

    Not able to figure out why? Could anyone help with this issue?

    opened by akshayshrivastav866 0
  • tag_box.on

    tag_box.on "add:after" or "remove:after" not triggering

    Hello,

    I'm using your plugin to display some tags, and it works really good. but there I have a problem that I cannot solve. When I try to add a trigger to the add or remove tag actions, the code tag_box.on("add:after", some function()) is not triggered.

    Any idea why?

    thanks in advance

    opened by Schewns 2
  • Wrap text value in escaped quotes to allow for spaces in tags.

    Wrap text value in escaped quotes to allow for spaces in tags.

    Anytime I would remove a tag with a space in the text, it would throw an error in the jquery selector. Adding these escaped quotes has fixed this bug for me.

    opened by MaxHershey 0
Releases(v1.3.3)
  • v1.3.3(Oct 24, 2014)

  • v1.3.1(Apr 28, 2014)

  • v1.2.5(Apr 10, 2014)

  • v1.2.3(Apr 6, 2014)

    1.2.3 - [Apr 06, 2014]

    • Add case-sensitive option;
    • Add forbidden-words option to block some words inside a tag, with callback and text;
    • Add callback and text to as forbidden-chars option;
    • Fixed i.handler.apply is not function bug;
    • Updated README.md with all Available Options;
    • Improved code formatting;
    • Passed to Semantic Versioning;
    • Add taggingJS to jQuery Plugin Registry;
    • Minor fix;
    Source code(tar.gz)
    Source code(zip)
A work-in-progress HTML sanitizer that strives for: performance like window.Sanitizer, readiness like DOMPurify, and ability to run in a WebWorker like neither of those.

Amuchina A work-in-progress HTML sanitizer that strives for: performance like window.Sanitizer, readiness like DOMPurify, and ability to run in a WebW

Fabio Spampinato 9 Sep 17, 2022
A tiny, plugin extendable JavaScript utility library with a JQuery-like syntax.

Tiny Friggin' Utility Zapper What is it? A tiny ~7kb extendable JavaScript utility library with a JQuery like syntax for getting work done fast! If yo

Bret 4 Jun 25, 2022
🖼 A jQuery plugin to view images just like in Windows. Browser support IE7+!

⚠️ Attention! This repository will be maintained just in small iteration. The plugin is easy to use, but its customization can be troublesome. To impr

Zongbin 191 Dec 30, 2022
A jQuery Plugin for viewing pictures like Wechat moments

A jQuery Plugin for viewing pictures like Wechat moments

馒头饭 25 Nov 10, 2022
jQuery easy ticker is a news ticker like plugin, which scrolls the list infinitely. It is highly customizable, flexible with lot of features and works in all browsers.

jQuery Easy Ticker plugin jQuery easy ticker is a news ticker like plugin which scrolls a list infinitely. It is highly customizable, flexible with lo

Aakash Chakravarthy 208 Dec 20, 2022
JQuery charCounter - jQuery Character Counter Plugin

jQuery Character Counter A jQuery based character counter for <input> and <textarea> HTML tags. What is this? This simple plugin allows you to add a c

mmmm_lemon 1 Aug 10, 2022
jQuery quick notification plugin. jQuery плагин быстрых уведомлений

Note: English translation by Google Translate Notific About Description: this is a jQuery plugin that helps you display notifications on your site. Li

Webarion 2 Nov 7, 2021
A variety of jQuery plugin patterns for jump starting your plugin development

jQuery Plugin Patterns So, you've tried out jQuery Boilerplate or written a few of your own plugins before. They work to a degree and are readable, bu

jQuery Boilerplate 1.6k Dec 31, 2022
This is a simple Image popup Jquery plugin. With a very simple configuration, you can show a popup on your webpage. By the way, this plugin works after page load.

Jquery-SingleImagePopup This is a simple Image popup Jquery plugin. With a very simple configuration, you can show a popup on your webpage. By the way

Rajan Karmaker 1 Aug 22, 2022
Examples of how to do query, style, dom, ajax, event etc like jQuery with plain javascript.

You (Might) Don't Need jQuery Frontend environments evolve rapidly nowadays and modern browsers have already implemented a great deal of DOM/BOM APIs

NEFE 20.3k Dec 24, 2022
we learn the whole concept of JS including Basics like Object, Functions, Array etc. And Advance JS - Understanding DOMs, JQuery, Ajax, Prototypes etc.

JavaScript-for-Complete-Web Development. we learn the whole concept of JS including Basics like Object, Functions, Array etc. And Advance JS - Underst

prasam jain 2 Jul 22, 2022
Page switching like a Boss. Inspired by jQuery mobile

Roadcrew.js / Roadcrew.dart =========================== Roadcrew.js is a simple JavaScript snippet which allows "page transitions" like in jQuery mob

Christian Grobmeier 49 Aug 20, 2018
A tiny, lightning fast jQuery-like library for modern browsers.

Sprint.js Sprint is a high-performance, 5KB (gzipped) DOM library for modern browsers. Sprint notably shines on bandwidth and resource constrained dev

Benjamin De Cock 4.3k Jan 3, 2023
jQuery UI widget for structured queries like "Contacts where Firstname starts with A and Birthday before 1/1/2000 and State in (CA, NY, FL)"...

Structured-Filter · Structured-Filter is a generic Web UI for building structured search or filter queries. With it you can build structured search co

Olivier Giulieri 238 Jan 6, 2023
Javascript library for switching fixed elements on scroll through sections. Like Midnight.js, but without jQuery

Library for Switching Fixed Elements on Scroll Sometimes designers create complex logic and fix parts of the interface. Also they colour page sections

Vladimir Lysov 38 Sep 19, 2022
Jquery-actualizer - jQuery ajax actualizer

jQuery AJAX Actualizer Include jQuery & this plugin into your HTML file and use this js code: $('#target').actualizer('a'); On click at any A element,

Šimon (Simon) Rataj 1 Jul 28, 2020
jquery-input-mask-phone-number.js - A simple, easy jquery format phone number mask library

jquery-input-mask-phone-number A jQuery Plugin to make masks on input field to US phone format. Quick start 1. Add latest jQuery and jquery-input-mask

Raja Rama Mohan Thavalam 12 Aug 25, 2022
Like Obsidian Publish but for self-hosting. Plugin integrations for dataview, admonition, and more.

Obsidian Export Obsidian Publish is great but lacks support for many of the plugins we Obsidian addicts have grown accustomed to — in particular Datav

null 12 Nov 28, 2022
A plugin for generate markdown table quickly like Typora.

Obsidian Table Generator A plugin for generate markdown table quickly like Typora. Features You can use obsidian-table-generator to generate markdown

Boninall 58 Dec 30, 2022