Vipina K
Vipina K

Reputation: 65

Insert text at cursor position in wysihtml5 editor

I have a text area and list box with some values. When user places the cursor anywhere inside the text area and select the value from list box it should be injected in the specific position where the cursor placed .

I have tried some solution, where the text is always appending at the end .Not able to append at the cursor position.

Upvotes: 0

Views: 1771

Answers (3)

estani
estani

Reputation: 26527

To complete Oliver's answer:

$('.textarea').data('wysihtml5').editor.composer.commands.exec("insertHTML", "<b>hi!</b>");

see: http://jsfiddle.net/estani/pfm2bx6j/1/

If you use rails https://github.com/Nerian/bootstrap-wysihtml5-rails gem, and add it over simple_for ... as: :wsyihtml5 then the selector should be:

$('textarea.wysihtml5').data('wysihtml5').editor//...

Upvotes: 0

Pratik Kumar
Pratik Kumar

Reputation: 66

for bootstrap-wysihtml5 use following function it working for me :

<script>

  $(function () {
    // Replace the <textarea id="editor1"> with a CKEditor
    // instance, using default configuration.
  //  CKEDITOR.replace('editor1');
    //bootstrap WYSIHTML5 - text editor
    $(".textarea").wysihtml5();

  });



function injectString(str){
   var sel=frames[0].getSelection();
   var nd=sel.anchorNode;
   var txt=nd.data+'';
   var pos=sel.anchorOffset||0;
   sel.anchorNode.data=txt.slice(0,pos)+str+txt.slice(pos);
 }</script>

use like this

<button id="name" data-wysihtml5-command="foreFrac" onclick="injectString('{name}')" type="button" class="btn btn-block btn-success btn-lg">Name </button>

Upvotes: 0

Oliver Pulges
Oliver Pulges

Reputation: 111

In wysihtml editor there is a command named insertHTML that shoult do exactly that: inject whatever code you like at cursor position/selection (https://github.com/Voog/wysihtml/wiki/Supported-Commands#inserthtml-):

editorInstance.composer.commands.exec("insertHTML", "<blockquote>foobar</blockquote>");

If your toolbar looses focus on editable area (like select dropdown might do or input), you have to save selection on toolbar opening and restore selection before executing command with

var b = editorInstance.composer.selection.getBookmark();

and

var editorInstance.composer.selection.setBookmark(b);

Like here is done: https://github.com/Voog/wysihtml/blob/master/examples/wotoolbar.html#L351

Upvotes: 1

Related Questions