Insert HTML in NicEdit WYSIWYG
Asked Answered
I

7

5

How can I insert text/code at the cursors place in a div created by NicEdit?

I've tried to read the documentation and create my own plugin, but I want it to work without the tool bar (Modal Window)

Inmate answered 28/4, 2010 at 14:40 Comment(0)
I
7

This is a quick solution and tested in firefox only. But it works and should be adaptable for IE and other browsers.

function insertAtCursor(editor, value){
    var editor = nicEditors.findEditor(editor);
    var range = editor.getRng();                    
    var editorField = editor.selElm();
    editorField.nodeValue = editorField.nodeValue.substring(0, range.startOffset) +
                            value +
                            editorField.nodeValue.substring(range.endOffset, editorField.nodeValue.length);
}
Idiomorphic answered 2/5, 2010 at 0:52 Comment(2)
but Above code will not work if textarea is empty or blank ...or user has not entered the text..see my ansCovariance
Also Does not work in IE .. as getRng() has issues in IE use Rangy library from gitHubCovariance
P
2

Insert Html Plugin

Don't know if this will help or not, but this is the plugin I created for inserting Html at the cursor position. The button opens a content pane and I just paste in the html I want and submit. Works for me!

var nicMyhtmlOptions = {
    buttons : {
      'html' : {name : 'Insert Html', type : 'nicMyhtmlButton'}
    },iconFiles : {'html' : '/nicedit/html_add.gif'}

};

var nicMyhtmlButton=nicEditorAdvancedButton.extend({
      addPane: function () {
      this.addForm({
        '': { type: 'title', txt: 'Insert Html' },
        'code' : {type : 'content', 'value' : '', style : {width: '340px', height : '200px'}}
      });
    },

    submit : function(e) {
      var mycode = this.inputs['code'].value;
      this.removePane();
      this.ne.nicCommand('insertHTML', mycode );
    }

});
nicEditors.registerPlugin(nicPlugin,nicMyhtmlOptions);

I used the html_add icon from Silk Icons, pasted onto a transparent 18 x 18 and saved as gif in the same folder as nicEditorIcons.gif.

Presumptuous answered 13/10, 2012 at 2:1 Comment(0)
C
2

It works for me when I use:

function neInsertHTML(value){
    $('.nicEdit-main').focus(); // Without focus it wont work!
    // Inserts into first instance, you can replace it by nicEditors.findEditor('ID');
    myNicEditor.nicInstances[0].nicCommand('InsertHTML', value); 
}
Callipygian answered 10/2, 2013 at 13:44 Comment(1)
This definitely works. You could also use myNicEditor.selectedInstance.nicCommand(...) to target the editor with the current focusKnockout
U
1

The way I solved this was to make the nicEdit Instance div droppable, using jQuery UI; but to also make all of the elements within the div droppable.

$('div.nicEdit-main').droppable({
    activeClass: 'dropReady',
    hoverClass: 'dropPending',
    drop: function(event,ui) {
    $(this).find('.cursor').removeClass('cursor');
  },
  over: function(event, ui) {
    if($(this).find('.cursor').length == 0) {
      var insertEl = $('<span class="cursor"/>').append($(ui.draggable).attr('value'));
      $(this).append(insertEl);
    }
  },
  out: function(event, ui) {
    $(this).find('.cursor').remove();
  },
  greedy: true
});

$('div.nicEdit-main').find('*').droppable({
  activeClass: 'dropReady',
  hoverClass: 'dropPending',
  drop: function(event,ui) {
    $(this).find('.cursor').removeClass('cursor');
  },
  over: function(event, ui) {
    var insertEl = $('<span class="cursor"/>').append($(ui.draggable).attr('value'));
    $(this).append(insertEl);
  },
  out: function(event, ui) {
    $(this).find('.cursor').remove();
  },
  greedy: true
});

Then make your code or text draggable:

$('.field').draggable({
                appendTo: '.content', //This is just a higher level DOM element
                revert: true,
                cursor: 'pointer',
                zIndex: 1500, // Make sure draggable drags above everything else
                containment: 'DOM',
                helper: 'clone' //Clone it while dragging (keep original intact)
            });            

Then finally make sure you set the value of the draggable element to what you want to insert, and/or modify the code below to insert the element (span) of your choice.

        $sHTML .= "<div class='field' value='{{".$config[0]."}}'>".$config[1]."</div>";
Underdone answered 19/4, 2012 at 17:40 Comment(0)
B
0

A response to @Reto: This code works, I just needed to add some fix because it doesn't insert anything if text area is empty. Also it adds only plain text. Here is the code if anybody need it:

if(editorField.nodeValue==null){
  editor.setContent('<strong>Your content</strong>');
}else{        
  editorField.nodeValue = editorField.nodeValue.substring(0, range.startOffset) +
                          '<strong>Your content</strong>' +
                          editorField.nodeValue.substring(range.endOffset, editorField.nodeValue.length);
  editor.setContent(editorField.nodeValue);
}
Barrister answered 13/9, 2012 at 7:12 Comment(1)
IT WILL FAIL if you write a sentence in line one and try to enter in a new line (which has no text yet)...It will reset the whole editor contentCovariance
C
0

Change follwoing in NicEdit.js File

Updated from Reto Aebersold Ans It will handle Null Node exception, if text area is empty

update: function (A) {
    (this.options.command);
        if (this.options.command == 'InsertBookmark') {
            var editor = nicEditors.findEditor("cpMain_area2");
            var range = editor.getRng();
            var editorField = editor.selElm();
            //  alert(editorField.content);
            if (editorField.nodeValue == null) {
                //  editorField.setContent('"' + A + '"')
                var oldStr = A.replace("<<", "").replace(">>", "");
                editorField.setContent("&lt;&lt;" + oldStr + "&gt;&gt;");
            }
            else {
                // alert('Not Null');
                // alert(editorField.nodeValue + '  ' + A);
                editorField.nodeValue = editorField.nodeValue.substring(0, range.startOffset) + A + editorField.nodeValue.substring(range.endOffset, editorField.nodeValue.length);
            }
        }
        else {
            // alert(A);  
            /* END HERE */
            this.ne.nicCommand(this.options.command, A);
        }
Covariance answered 29/10, 2014 at 4:26 Comment(0)
A
0

This function work when nicEdit textarea is empty or cursor is in the blank or new line.

function addToCursorPosition(textareaId,value) {
            var editor = nicEditors.findEditor(textareaId);
            var range = editor.getRng();
            var editorField = editor.selElm();
            var start = range.startOffset;
            var end = range.endOffset;
            if (editorField.nodeValue != null) {
                editorField.nodeValue = editorField.nodeValue.substring(0, start) +
                            value +
                            editorField.nodeValue.substring(end, editorField.nodeValue.length);
            }
            else {
                var content = nicEditors.findEditor(textareaId).getContent().split("<br>");
                var linesCount = 0;
                var before = "";
                var after = "";
                for (var i = 0; i < content.length; i++) {
                    if (linesCount < start) {
                        before += content[i] + "<br>";
                    }
                    else {
                        after += content[i] + "<br>";
                    }
                    linesCount++;
                    if (content[i]!="") {
                        linesCount++;
                    }
                }
                nicEditors.findEditor(textareaId).setContent(before + value + after);
            }

        }
Aliber answered 17/1, 2017 at 18:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.