2

I want to tag some words like Facebook when you are posting and tag some people, mixed with text, using jQuery.

This is the example:
enter image description here

vsync
  • 118,978
  • 58
  • 307
  • 400
Richard
  • 333
  • 1
  • 3
  • 6

2 Answers2

2

Please see my Plunk I believe this to be what you were after! I have added an array of 3 names ("Dave Smith", "Test User", "Jim Dot") to the top of my script.js file. In reality you would query this from a database and take the top 100 or so elements, in the Facebook example I would say take the top 200 friend names based on total interactions.

My code works for Google Chrome Version 40.0.2214.115 (I have not tested other browsers yet): enter image description here

The important code is the div with the contenteditable attribute set to true:

<div id="tag-area" class="tag-area" contenteditable="true">
</div>

And the important JavaScript is this code for searching my array of names and wrapping the text in a "span" element:

function ExistsInListOfNamesAndIsNotHiglighted(item) {
   return $("#tag-area").html().indexOf(item) > -1 && $("#tag-area").html().indexOf("<span>" + item + "</span>") === -1;
}

$(function() {
  var tags = ["Dave Smith", "Test User", "Jim Dot"];

  $("#tag-area").keyup(function() {
    $(tags).each(function(index, item) {
      if (ExistsInListOfNamesAndIsNotHiglighted(item)) {
        $("#tag-area").html($("#tag-area").html().replace(item, "<span>" + item + "</span>&nbsp;"));

        cursorToEndOfContentEditable($("#tag-area")[0]);
  }
});

The "cursorToEndOfContentEditable" code was taken from Nico Burn's answer on the thread

How to move cursor to end of contenteditable entity

I have also added a bit of CSS to the span tags which will wrap up the tagged pieces of text:

span {
  background-color: #D8DFEA; 
  border:1px solid #7688a4;
}

Please let me know how you get on! And do not hesitate to ask me for any refinements :)

Community
  • 1
  • 1
JDTLH9
  • 1,765
  • 1
  • 23
  • 34
1

you can use "Mix text tags" option in jquery. Please refer https://yaireo.github.io/tagify/

enter image description here

vsync
  • 118,978
  • 58
  • 307
  • 400
Roshan Perera
  • 780
  • 7
  • 12