Create element example
HTML
<label for="tags">Tags</label> <ul id="mytags"></ul>
CSS
@charset "UTF-8"; /* base */ html { font-size: 62.5%; } a { text-decoration:underline; } p { margin-bottom:10px; line-height:18px; } /* end of base */ body, input, a { font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif; color: #333; font-size:12px; } #content { width:600px; margin:20px 0 20px 40px; } .myform { padding:20px 0px; } .myform div.line { clear:both; min-height:50px; margin-bottom:15px; } .myform label { display:block; font-weight:bold; margin-bottom:5px; }
JavaScript
(function($) {
$.fn.tagit = function(options) {
var el = this;
const BACKSPACE = 8;
const ENTER = 13;
const SPACE = 32;
const COMMA = 44;
// add the tagit CSS class.
el.addClass("tagit");
// create the input field.
var html_input_field = "<li class=\"tagit-new\"><input class=\"tagit-input\" type=\"text\" /></li>\n";
el.html(html_input_field);
tag_input = el.children(".tagit-new").children(".tagit-input");
$(this).click(function(e) {
if (e.target.tagName == 'A') {
// Removes a tag when the little 'x' is clicked.
// Event is binded to the UL, otherwise a new tag (LI > A) wouldn't have this event attached to it.
$(e.target).parent().remove();
}
else {
// Sets the focus() to the input field, if the user clicks anywhere inside the UL.
// This is needed because the input field needs to be of a small size.
tag_input.focus();
}
});
tag_input.keypress(function(event) {
if (event.which == BACKSPACE) {
if (tag_input.val() == "") {
// When backspace is pressed, the last tag is deleted.
$(el).children(".tagit-choice:last").remove();
}
}
// Comma/Space/Enter are all valid delimiters for new tags.
else if (event.which == COMMA || event.which == SPACE || event.which == ENTER) {
event.preventDefault();
var typed = tag_input.val();
typed = typed.replace(/,+$/, "");
typed = typed.trim();
if (typed != "") {
if (is_new(typed)) {
create_choice(typed);
}
// Cleaning the input.
tag_input.val("");
}
...