Keshav Vasudevan Keshav Vasudevan - 2 months ago 25
CSS Question

Creating a tag box

I'm making a tag box similar to that of StackOverflow. I see that this question has already been asked here (How to make a "tags box" using jQuery (with text input field + tags separated by comma)) but I'm having a question with regards to the Javascript.

HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='tag-container' id = "tag-container">
<span class='dashfolio-tag'>Tag1</span>
<span class='dashfolio-tag'>Tag2</span>
<span class='dashfolio-tag'>Tag3</span>
</div>


<input type="text" value="" placeholder="Add a tag" id = "add-tag-input" />


CSS:

.tag-container {
max-width: 300px; /* helps wrap the tags in a specific width */

}

.dashfolio-tag {
cursor:pointer;
background-color: blue;
padding: 5px 10px 5px 10px;
display: inline-block;
margin-top: 3px; /*incase tags go in next line, will space */
color:#fff;
background:#789;
padding-right: 20px; /* adds space inside the tags for the 'x' button */
}

.dashfolio-tag:hover{
opacity:0.7;
}

.dashfolio-tag:after {

position:absolute;
content:"×";
padding:2px 2px;
margin-left:2px;
font-size:11px;
}

#add-tag-input {
background:#eee;
border:0;
margin:6px 6px 6px 0px ; /* t r b l */
padding:5px;
width:auto;
}


JS:

$(document).ready(function(){
$(function(){

$("#add-tag-input").on({
focusout : function() {
var txt = this.value.replace(/[^a-z0-9\+\-\.\#]/ig,''); // allowed characters
if(txt) $("<span/>", {text:txt.toLowerCase(), insertBefore:this});


this.value = "";
},
keyup : function(ev) {
// if: comma|enter (delimit more keyCodes with | pipe)
if(/(188|13)/.test(ev.which)) $(this).focusout();
}
});
$('.tag-container').on('click', 'span', function() {
if(confirm("Remove "+ $(this).text() +"?")) $(this).remove();
});

});

});


My question is pretty simple, how do I add the new input as a span with class
dashfolio-tag
inside the
#tag-container
? I dabbled with the
insertBefore
property trying to add it to the right node, but to no avail. Thanks in advance guys!

Answer

Change this line of code,

if(txt) $("<span/>", {text:txt.toLowerCase(), insertBefore:this});

to

if(txt) {
    $("<span/>", {
        text:txt.toLowerCase(),
        appendTo:"#tag-container",
        class:"dashfolio-tag"
    });
}

See the demo: https://jsfiddle.net/2gvdsvos/4/


To fix the margins in between tags,

Update HTML to,

<div>
  <div class="tag-container" id="tag-container">
    <span class='dashfolio-tag'>tag1</span>
    <span class='dashfolio-tag'>tag2</span>
    <span class='dashfolio-tag'>tag3</span>
  </div>
</div>
<div>
  <input type="text" value="" placeholder="Add a tag" id="add-tag-input" />
</div>

And add this to CSS,

.tag-container:after {
  visibility: hidden;
  display: block;
  font-size: 0;
  content: " ";
  clear: both;
  height: 0;
}

.dashfolio-tag {
  ...
  margin-right: 4px;
  float: left;
}

Hope this helps! ;)

https://jsfiddle.net/2gvdsvos/5/