skip to Main Content

I have created a plugin for Suneditor which integrates Emoji button.
The Idea is to insert the emoji where the cursor is and then keep the cursor at the same position (following the newly inserted emoji). But I am getting the issue where the cursor gets reset to the beginning of the document, which is terrible UX, any ideas how to keep the cursor from jumping to the start?
https://jsfiddle.net/na3yxb51/4/

I’ve looked over the docs but haven’t been able to find much about the cursor placement.

action: function (core) {
  const editor = this;
  function handleEmoji(emoji) {
    const tag = editor.util.createElement("span");
    tag.textContent = emoji;
    editor.insertNode(tag, null);

    picker.off('emoji', handleEmoji);
  };
  picker.on('emoji', handleEmoji);
  picker.togglePicker(document.querySelector('#emojianchor'));
}

2

Answers


  1. Chosen as BEST ANSWER

    Solution: https://jsfiddle.net/r7p92m8d/1/

    function resetCursorPos() {
      const core = editor.core;
      const editorNode = core.context.element.wysiwyg;
    
      const lastChild = editorNode.lastChild;
      const range = document.createRange();
      const selection = window.getSelection();
    
      setTimeout(function() {
        range.setStartAfter(lastChild);
        range.collapse(true);
        selection.removeAllRanges();
        selection.addRange(range);
    
        editor.core.focus();
      }, 100);
    }
    

  2. In Suneditor, you must save the current cursor position before inserting an emoji and then restore it later to prevent the pointer from jumping to the start of the document. Suneditor’s core.saveRange() and core.restoreRange() methods can be used to perform this.a

    Here’s a modified version of your plugin to handle cursor position correctly:

    action: function (core) {
      const editor = this;
      function handleEmoji(emoji) {
        core.saveRange();
        const tag = editor.util.createElement("span");
        tag.textContent = emoji;
        editor.insertNode(tag, null);
        core.restoreRange();
        core.focus();
    
        picker.off('emoji', handleEmoji);
      };
      picker.on('emoji', handleEmoji);
      picker.togglePicker(document.querySelector('#emojianchor'));
    }
    

    In this code:

    1. Before the emoji is inserted, {core.saveRange()} is called. The selected range is saved as a result.
    2. Once the emoji has been inserted, `core.restoreRange()} is invoked. By doing this, you can get the selection range back to how it was before the emoji was included.
    3. After the cursor position is restored, `core.focus()} is used to make sure the editor is focused.

    This should prevent the cursor from jumping to the beginning of the document when an emoji is inserted.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search