I have seen sites like Twitter
, Facebook
, Bitbucket
, Github
, Gmail
, among others. They add emojis
after typing a certain set of characters or some add them after posting the content. Something like:
:D - -> ?
I imagine there is a listener, programmed with regular expressions JavaScript
waiting for content that matches that pattern and then replacing it with images or unicode (such as Font Awesome).
I would like to know what happens to achieve that. Is there a design pattern I can use? Do I need to have any special configuration in my DB( MySQL
)?
Note: More than using a framework (if it exists) I would like to know how it is achieved.
You do not need any database configuration, because to save resources, the rendering is done on the client's PC. Design patterns in javascript I don't know, but in other languages you would make a static and public class that contains a table ( hash ) of all the emoticons, in case you use it extensively.
Process
You find the string in the text when the person types and replace it with an image tag , ideally you should use an HTML component or something that doesn't limit you to just entering text as is the case with
input
, the easiest way is to add the propertycontenteditable
that will allow you to edit a fragment of theDOM
.Here is a small example with jquery
Here's an example of how to do what you want without any framework class, just vanilla-script:
Note: I didn't have time to correctly implement the regex to capture the smile code :), but the general idea is functional:
Code:
The most basic thing I can think of:
$(document).ready()
) that it evaluates the content of the<p>
so<div>
s where you need to replace the content of symbols such as:)
and:D
with labels<img>
or<span>
that represent parts of the image via CSS such as explained here . To make things easier, you could have CSS classes that already contain as background the exact sprite you need from the main image. To identify the<p>
s and<div>
s, you could use a CSS class, so that you reduce the analysis of the text where the change should be applied, and also reduce that somewhere in the generated HTML this replacement happens.