Hashtag client side implementation using jquery & javascript

1k views Asked by At

#input {
    -moz-appearance: textfield-multiline;
    -webkit-appearance: textarea;
    border: 1px solid gray;
    font: medium -moz-fixed;
    font: -webkit-small-control;
    height: 28px;
    overflow: auto;
    padding: 2px;
    resize: both;
    width: 400px;
}
<div id="input" placeholder="testing" contenteditable>listening music #music</div>

I'm implementing hashtag feature (ex:- #music, #dance).

if user enter '#' character I want to hit search Api.

for Example: user updating status "listening music #music #dance let's rock"

here "listening music, let's rock" is normal text and "#music", "#dance" are hashtag.

whenever user enters "#m" after "listening music", i need to hit api like "/search?q=m"

var searchData = ["music", "mango", "marks", "moon"]

user able to select one of the suggestion and space will come after hashtag automatically.

whenever user enters "#d" after "#music ", i need to hit api like "/search?q=d"

var searchData = ["dance", "danger", "dad"]

user able to select one of the suggestion and space will come after hashtag automatically.

"let's rock" is normal text.

differentiating color of "hashtag" and search only when user enters "#"

2

There are 2 answers

9
rabelloo On

You could bind the keyup event to your input to check for hashtag starting words. When a match is found, you call your AJAX. Like so:

var ajax;

$('#input').keyup(function() {

    var tags = $(this).val().split(' ');
    var lastTag = tags.pop();

    if (/#\S+\b/.test(lastTag)) {
        // abort previous ajax if still running
        if (ajax && ajax.abort && ajax.readyState !== 4)
            ajax.abort();

        // hit your search api
        ajax = $.getJson('/search', { q: lastTag })
               .done(function (data) {
                   // manage your response data here
                   // show suggestions and handle picking one
               });
    }
});

EDIT: Completely redone logic, much simpler and more compact

1
kemal akoğlu On

I think this works for you

var inputData = "listening music #music #dance let's rock";
var arrayData = inputData.split(" ");

arrayData.forEach(function(entry) {
     if(entry.startsWith(("#music") || ("#etc"))){
     // hit your api
     }
});