paganotti
paganotti

Reputation: 5661

jquery remove text selection range after pasteHTML

I have a JavaScript snippet:

// IE < 9
r = document.selection.createRange();
r.collapse(true);
r.pasteHTML("<p> test html </p>");

This works but what I want is that once the HTML is pasted, it must lose the selection.

In other words, what happens is that after pasteHtml method executes, the text "test html" is selected on the page. I don't want this. I want text to be unselected but the cursor should be positioned at end of "test html" text. I'm doing this in:

<div contenteditable="true"> </div>

How can I do this?

Upvotes: 1

Views: 2187

Answers (1)

Tim Down
Tim Down

Reputation: 324627

Easy: collapse the selected TextRange and reselect it:

var r = document.selection.createRange();
r.collapse(true);
r.pasteHTML("<p> test html </p>");

var selectedRange = document.selection.createRange();
selectedRange.collapse(false);
selectedRange.select();

Upvotes: 1

Related Questions