Select Page

Demo

See the Pen Script to add emoticons in input on focused area by Puneet Sharma (@webdevpuneet) on CodePen.

Script

<script type="module">
    import { createPicker } from 'https://unpkg.com/picmo@latest/dist/index.js';

    let lastCursorPosition = 0;

    $(document).on('click', function(event) {
        // Check if the click target is not inside any pickerContainer
        if (!$(event.target).closest('.pickerContainer, .vihmLG__typePanel-buttons-smiley').length) {
            $('.pickerContainer').hide();
            $('.pickerContainer').html('');
        }
    });

    $(document).on('click', '.vihmLG__typePanel-buttons-smiley', function(){
        if( !$(this).parent().find('.pickerContainer').length ){
            $(this).parent().append('<div class="pickerContainer"></div>');
        }
        const containerEmoji = $(this).parent().find('.pickerContainer')[0];
        const picker = createPicker({
            rootElement: containerEmoji
        });
        $(containerEmoji).show();

        picker.addEventListener('emoji:select', selection => {
            const input = $(this).closest('.vihmLG__typePanel').find('.vihmLG__typePanel-input');
            const currentValue = input.val();
            const newValue = currentValue.substring(0, lastCursorPosition) + ' ' + selection.emoji + currentValue.substring(lastCursorPosition);
            input.val(newValue).trigger('input');
            $(containerEmoji).hide();
            $(containerEmoji).html('');
        });
    });

    $(document).on('focus click keyup', '.vihmLG__typePanel-input', function() {
        lastCursorPosition = this.selectionStart;
    });
    
  </script>