TinyMCE move caret after inserting span
Asked Answered
B

1

6

I am creating a TinyMCE plugin with custom button that insert <span>test</span> in current caret position. Moreover clicking this button again while caret is in previously inserted text is removing current <span>test</span> and replacing it with new inserted <span>test</span>.

tinymce.PluginManager.add('test_plugin', function(editor) {
   editor.addButton('test-button', {
      text: 'Insert span',
      onclick: function() {
         var current_node = editor.selection.getNode();

         if(current_node.tagName === 'SPAN') {
            current_node.remove();
         }

         editor.insertContent('<span>test</span>');
      }
   });
});

It works great but after inserting <span>test</span> the caret get stuck in this span node and I can't move it outside of this span.

Adding &#32; (whitespace) at the end (<span>test</span>&#32;) solves the problem of stucking caret but it is adding redundant spaces every reinsert.

How to solve stucking caret problem?

OR

How to remove redundant &#32; when reinserting?

Batangas answered 28/7, 2017 at 20:32 Comment(1)
This question was the answer I was looking for (:D), your code works at my end (tinyMCE 5.x.x). Thanks!Demisec
P
0

Hmm, sounds wierd. You could try to reset the caret after inserting the span. This might help.

Insert the span in this form <span id="my_new_span">test</span>.

var my_span = ed.getBody().querySelector('#my_new_span');
ed.selection.select(my_span);
ed.selection.getRng(1).collapse(0);

// remove the id attribute
my_span.removeAttribute("id");
Picasso answered 31/7, 2017 at 9:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.