Shival Gupta Shival Gupta - 1 year ago 110
CSS Question

Implementing Hashtags using Jquery

What I want to do is basically is that whenever I write anything that starts with a #, the color of the tagged string should change to some other color, say blue, immediately. And when I press space to end the string, the color should change back to black. I tried a logic like this on a contenteditable div:

if (# is pressed)
hashtagging = true
append "<span>" to div

if (space is pressed and hashtagging is true)
hashtagging = false
append "</span>" to div

This is not working as expected.

Answer Source

Something like this should do:

$(function() {

    var hashtags = false;

    $(document).on('keydown', '#myInputField', function (e) {        
        arrow = {
            hashtag: 51,
            space: 32

        var input_field = $(this);
        switch (e.which) {
            case arrow.hashtag:
                input_field.val(input_field.val() + "<span class='highlight'>");
                hashtags = true;
                if(hashtags) {
                    input_field.val(input_field.val() + "</span>");
                    hashtags = false;



Now this code checks on keydown if the hashtag or space is pressed and adds a span with a class for styling to it. Reason for checking for keydown instead of keyup is to add the tags before the actual input is added to the textfield. I used a text-field as input, but modify it with whatever you need.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download