Today I am going to tell you how to create Facebook Style Tag Selector using jQuery. This kind of tag selectors are used in many popular sites like facebook, twitter, linkedIn & even in gmail also.
In my previous article I had explained how to design css3 tags . If you want to add tags separated by comma, I am sure that this tutorial will help you a lot.
In many social networking sites this kind of Tag text boxes are used to collect user’s Interest, adding categories, adding skills, adding tags etc
Contents
jQuery Code
$(document).on('keydown', '#tag_list', function (e) {
if (e.keyCode == 13) {
createTag($(this).val());
}
});
$(document).on('click', '.delete', function () {
$(this).parent().remove();
});
function createTag(text) {
if (text != '') {
var tag = $('<div class="tags">' + text + '<a class="delete"></a></div>');
tag.insertBefore($('#tag_list'), $('#tag_list'));
$('#tag_list').val('');
}
}
Keycode – 13 is for Enter Key. Once user pressed the enter key, createTag function will called with typed text.
Delete button is used to delete the added text
CSS Code
.tags {
float: left;
margin-right: 2px;
margin-bottom: 7px;
margin-top:1px;
height: 22px;
border-radius: 4px;
border: 1px solid #cccccc;
font: normal 14px/20px 'Sanchez';
background: #ebeaea;
background: -o-linear-gradient(top, #C4CDE0, #C4CDE0);
background: -webkit-linear-gradient(top, #C4CDE0, #C4CDE0);
background: -moz-linear-gradient(top, #C4CDE0, #C4CDE0);
background: -ms-linear-gradient(top, #C4CDE0, #C4CDE0);
background: linear-gradient(top, #C4CDE0, #C4CDE0);
filter: progid:DXImageTransform.Microsoft.Gradient(startColorStr="#C4CDE0", endColorStr="#C4CDE0");
border-color: #cccccc;
cursor: pointer;
box-shadow: inset 0 2px 0 rgba(255, 255, 255, 0.3);
padding-left: 6px;
padding-right: 28px;
position: relative;
}
.tags .delete {
display: block;
width: 20px;
height: inherit;
float: right;
background: rgba(255, 255, 255, 0.5) url('delete.png') center no-repeat;
margin-left: 6px;
border-left: 1px solid #ccc;
position: absolute;
top: 0;
right: 0;
}
.text {
height: 30px;
border-radius: 2px;
border: 1px solid #e9e8e8;
box-sizing: border-box;
-moz-box-sizing: border-box;
margin-bottom: 20px;
width: 95%;
background: #fff;
margin:10px;
}
.text input {
border: 0;
background: none;
width: 100%;
box-sizing: border-box;
-moz-box-sizing: border-box;
padding: 5 5px;
margin-top: 3px;
font: 400 14px/18px 'Sanchez';
}
.text input:active {
border:0;
}
.text input {
width: 200px;
overflow: hidden;
}
HTML Code
<div class="text">
<input type="text" placeholder="Type & Enter" id="tag_list"/>
</div>
Please don’t forget to share and subscribe to latest updates of the blog.
Thanks!
Its not working
Hi.. In which browser? Is there any error?