Place emoticons in my website’s chat

Asked

Viewed 2,156 times

5

I would like to know how in php or javascript to put emoticons according to the person typing the text and a command, ex:

Hello good morning [/sun] or I am fine [:Mile]

Anyway independent of the command how to do so that it is replaced by an image in the text be it . png or . gif?

1 answer

2

In javascript you can do so:

Use [:Smile] and [:Sad] to generate the emoticons.

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

<textarea id="input"></textarea>
<div id="result"></div>

<script>
  $('#input').keyup(function() {
    var emoticonsMap = {
      '[:smile]': 'https://cdn2.macworld.co.uk/cmsdata/features/3595098/smiley_face_thumb.png',
      '[:sad]': 'http://orig14.deviantart.net/ef35/f/2016/036/c/c/sad_emoji_by_catstam-d9qkdaq.png'
    }

    var formatedWord = this.value.split(' ').map(function(word, i) {
      if(emoticonsMap[word]) {
        word = "<img src='" + emoticonsMap[word] + "'>";
      }
      return word;
    });

    $('#result').html(formatedWord.join(' '));
  });
</script>

It takes the text every time the user types in something new and maps the words separated by space, to add a new Emoticon just put the key and link inside the json emoticonsMap.

====================================================================

Down here is a more streamlined form and one that I believe has a great performance gain compared to top code in large texts:

But then we can’t use the brackets on the Keys.*

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="input"></textarea>
<div id="result"></div>
<script>
  var emoticonsMap = {
    ':smile:': 'https://cdn2.macworld.co.uk/cmsdata/features/3595098/smiley_face_thumb.png',
    ':sad:': 'http://orig14.deviantart.net/ef35/f/2016/036/c/c/sad_emoji_by_catstam-d9qkdaq.png',
  }

  $('#input').keyup(function() {
    var text = this.value;

    $.each(emoticonsMap, function(key, link) {
      text = text.replace(new RegExp(key, 'g'), "<img src='" + link + "'>");
    });

    $('#result').html(text);
  });
</script>

It picks up the text every time the user types in something new and loops all the emoticons to search and replace if it finds.

*NOTE: Be careful when using elements in your Keys that can be interpreted by Regexp.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.