0

I've made a little inline editor with some clean up logic. So if you paste from a word file it deletes all the formatting.

My problem is, that if you select e.g. one sentence and paste, it doesn't get replaced. This is duo to the cleanUp logic. Now I need to know, how I can delete a range with rangy, so I can delete this range before I paste.

http://jsfiddle.net/eJNKy/3/

xotix
  • 347
  • 1
  • 11
  • 33

1 Answers1

4

You can delete a range using its deleteContents() method.

Rangy also deals with a lot of the cross-browser issues you're attempting to fix in your jsFiddle. It provides a createContextualFragment() implementation and a selection object with getRangeAt(). Also, you should use the ctrlKey property of the keydown event. Here's an updated jsFiddle:

http://jsfiddle.net/timdown/eJNKy/6/

The crucial function is

function paste(html) {
    var sel = rangy.getSelection();
    if (html && sel.rangeCount > 0) {
        var range = sel.getRangeAt(0);
        range.deleteContents();
        var frag = range.createContextualFragment(html);
        var lastChild = frag.lastChild;
        range.insertNode(frag);
        range.collapseAfter(lastChild);
        sel.setSingleRange(range);
    }
}
Tim Down
  • 292,637
  • 67
  • 429
  • 506
  • Thanks a lot! Haven't found this. That's some kind of nice help! Thanks for doing much more then i asked for. :) – xotix Jun 26 '12 at 14:13
  • Do you maybe have any tips for detecting pastings which are made via the context menu or browser menu? – xotix Jun 26 '12 at 14:45
  • @xotix: Not really. The redirecting trick doesn't work in some browsers once the paste event has fired. Here's an answer by Nico Burns that may help: http://stackoverflow.com/a/6804718, plus a jsFiddle I added in the comments for that answer: http://jsfiddle.net/bQeWC/4/ – Tim Down Jun 26 '12 at 15:10