zuba
zuba

Reputation: 1508

How to promote DOM range after inserting a Node?

I insert a node and when insert another it substitutes the previously inserted one.

I guess I need to put the range after the firstly inserted node, but how?

I define a function:

function EmoticonsMenu(jquery_element){
  var e = jquery_element;
  var top  = e.offset().top;
  var left = e.offset().left;
  var onIconClick_callback;

  this.onIconClick = function(eventObject){
    var html = $(eventObject.target).parent().html().replace(/\n\s+|\s+\n/g, '');
    onIconClick_callback(html);
    };

  e.blur(function(){
    e.css({visibility:'hidden'});
    e.hide();
    });

  this.attach_to = function(element, callback){
    onIconClick_callback = callback;
    var newTop  = element.offset().top  - top  - 10 - e.height();
    var newLeft = element.offset().left - left + 10;
    e.css({top:newTop, left:newLeft});
    e.css({visibility:'visible'});
    e.focus();
    };
};

and there is a place where I bind Emoticon to my nicEditor custom button

  nicEditorExampleButton = nicEditorButton.extend({   
    mouseClick : function(eventObject) {
    // get nicEdit selected instance - se
    var se = this.ne.selectedInstance;

    var paste_icon_html = function(html){
      // create a DOM node from the string
      //var html = '<img src="/assets/emoticons/ac.gif">admin is here!</img>';
      var div = document.createElement('div');
      div.innerHTML = html;
      var node = div.childNodes[0];

      // get selection if any, insert html as a Node
      var range = se.getRng();
      range.deleteContents();
      range.insertNode(node.cloneNode(true));
      //range.setStart(node,0);
      //range.setEnd(node,0);
      };

    emoticonsMenu.attach_to($(this.button), paste_icon_html);
    }
  });
  nicEditors.registerPlugin(nicPlugin,nicExampleOptions);

Upvotes: 0

Views: 1240

Answers (2)

zuba
zuba

Reputation: 1508

Here is code change required. Instead of:

  range.insertNode(node.cloneNode(true));
  //range.setStart(node,0);
  //range.setEnd(node,0);
  };

should be

  range.insertNode(node);
  range.setEndAfter(node);    //++
  range.setStartAfter(node);  //++
  };

Upvotes: 0

Bergi
Bergi

Reputation: 664648

If you don't want to substitute anything, remove the call to deleteContents.

Also you might have the problem that while calling this snippet repeatedly you always refer to the same nodes[0], and it can only exist once - to insert it multiple times, you'd need to clone it:

range.insertNode(nodes[0].cloneNode(true));

Upvotes: 1

Related Questions