Learn how to implement a @mention autocomplete using the At.js plugin.

How to create a @mentions autocomplete with jQuery and AtWho

Autocomplete plugins tends to be always customizable, so you can always implement your own features. If you want an input where you write whatever you want and add an autocomplete when the user types an special character, isn't so easy to implement with an existent plugin as most of them doesn't offer such feature. If you are looking for not exactly an autocomplete that shows a dropdown for every character you type but for something specifical, you may be looking for a plugin like AtWho.js !

1. Include AtWho.js

Every developer knows Github and it's useful issues system, well , atwho.js is an autocompletion library to autocomplete mentions, smileys etc. just like you do in the Github website on any textarea. At.js depends on the Caret.js library, that provides an accurate handling of the cursor position during any of the events triggered by the library.

Having said that, to use the library you will need specifically at least:

You will need to include at least 3 JS files and 1 CSS file to make the plugin work, the basic CSS style that can be found on the repository as well:

<!-- Add default autocomplete style (github style) -->
<link href="css/jquery.atwho.css" rel="stylesheet">

<!-- Include jQuery from a CDN or a local copy -->
<script src="http://code.jquery.com/jquery.js"></script>

<!-- Use Caret.js -->
<script src="js/jquery.caret.js"></script>

<!-- Include atwho.js -->
<script src="js/jquery.atwho.js"></script>

The autocomplete works on textareas elements on Chrome, Safari, Firefox, IE7+ (maybe IE6) and if you use it inside contentEditable elements in Chrome, Safari, Firefox, IE9+. For more information about this library, please don't forget to visit the official repository at Github here. The most known features of the plugin are:

  • Support IE 7+ for textarea.
  • Supports HTML5 contentEditable elements (NOT including IE 8)
  • Can listen to any character and not just '@'. Can set up multiple listeners for different characters with different behavior and data
  • Listener events can be bound to multiple inputors.
  • Format returned data using templates
  • Keyboard controls in addition to mouse
    • Tab or Enter keys select the value
    • Up and Down navigate between values (and Ctrl-P and Ctrl-N also)
    • Right and left will re-search the keyword.
  • Custom data handlers and template renderers using a group of configurable callbacks
  • Supports AMD

2. Using the autocomplete

The usage of the autocomplete is very simple and can be easily understood with examples:

Basic user autocomplete

The most used example, is the user mention autocomplete that can be triggered when the user types @, then the autocomplete shows up and the user can either select the user from the list or just type its name until it's filtered, then pressing either ENTER, TAB or Click the item is selected:

<textarea id="your-input"></textarea>

<script>
    $('#your-input').atwho({
        at: "@",
        data:['Hans', 'Peter', 'Tom', 'Anne']
    });
</script>

Using a contentEditable element

Instead of using a textarea, you can use it inside a div that implements the contenteditable property:

<div id="your-input" contenteditable="true" style="background-color: gray;"></div>

<script>
    $('#your-input').atwho({
        at: "@",
        data:['Hans', 'Peter', 'Tom', 'Anne']
    });
</script>

Multiple autocomplete (user and emojis)

If you are willing to implement multiple autocompletes inside a single input, you can achieve as long as every initializator uses a different at property e.g : and @:

<textarea id="your-input"></textarea>

<script>
    // Create Emojis Structure
    var emojis = $.map([
        "smile", "iphone", "girl", "smiley", "heart", "kiss", "copyright", "coffee",
        "a", "ab", "airplane", "alien", "ambulance", "angel", "anger", "angry",
        "arrow_forward", "arrow_left", "arrow_lower_left", "arrow_lower_right",
        "arrow_right", "arrow_up", "arrow_upper_left", "arrow_upper_right",
        "art", "astonished", "atm", "b", "baby", "baby_chick", "baby_symbol",
        "balloon", "bamboo", "bank", "barber", "baseball", "basketball", "bath",
        "bear", "beer", "beers", "beginner", "bell", "bento", "bike", "bikini",
        "bird", "birthday", "black_square", "blue_car", "blue_heart", "blush",
        "boar", "boat", "bomb", "book", "boot", "bouquet", "bow", "bowtie",
        "boy", "bread", "briefcase", "broken_heart", "bug", "bulb",
        "person_with_blond_hair", "phone", "pig", "pill", "pisces", "plus1",
        "point_down", "point_left", "point_right", "point_up", "point_up_2",
        "police_car", "poop", "post_office", "postbox", "pray", "princess",
        "punch", "purple_heart", "question", "rabbit", "racehorse", "radio",
        "up", "us", "v", "vhs", "vibration_mode", "virgo", "vs", "walking",
        "warning", "watermelon", "wave", "wc", "wedding", "whale", "wheelchair",
        "white_square", "wind_chime", "wink", "wink2", "wolf", "woman",
        "womans_hat", "womens", "x", "yellow_heart", "zap", "zzz", "+1",
        "-1"
    ], function(value, i) {
        return {
            key: value, 
            name:value
        };
    });

    var EmojiSettings = {
        at: ":",
        data: emojis,
        displayTpl: "<li>${name} <img src='https://assets-cdn.github.com/images/icons/emoji/${key}.png'  height='20' width='20' /></li>",
        insertTpl: "<img src='https://assets-cdn.github.com/images/icons/emoji/${name}.png'  height='20' width='20' />",
        insertTpl: ':${key}:',
        delay: 400
    };

    var UserSettings = {
        at: "@",
        data:['Hans', 'Peter', 'Tom', 'Anne']
    };

    // Initialize Emojis and User Settings on the same autocomplete field
    $('#your-input').atwho(EmojiSettings).atwho(UserSettings);
</script>

Live example

Play with the following fiddle that implements an useful autocomplete to write emojis, mention some user or complete a city:

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors