Double-click text selection in div (contenteditable)

I have a div with some text and contenteditable = "true". When I click on this div - some of my scripts work, this is not very important. And when I double click on this div - I need to edit the text in the div. You need to edit the text only after a double click, and not after the single. And very intensively, when I double-click on div-caret, I need to stay under the mouse cursor. There is no text of choice of necessity. I found several script for one / two. But there is a problem. When I double click on a div - text is a choice. No choice needed. I need an editor where I clicked. I don’t understand how to do this. http://jsfiddle.net/X6auM/

+6
source share
2 answers

Each current main browser provides an API for creating a range from a mouse event, although four different code branches are required.

Here is the background:

Here is a demo: http://jsfiddle.net/timdown/krtTD/10/

And here is some code:

function getMouseEventCaretRange(evt) { var range, x = evt.clientX, y = evt.clientY; // Try the simple IE way first if (document.body.createTextRange) { range = document.body.createTextRange(); range.moveToPoint(x, y); } else if (typeof document.createRange != "undefined") { // Try Mozilla rangeOffset and rangeParent properties, // which are exactly what we want if (typeof evt.rangeParent != "undefined") { range = document.createRange(); range.setStart(evt.rangeParent, evt.rangeOffset); range.collapse(true); } // Try the standards-based way next else if (document.caretPositionFromPoint) { var pos = document.caretPositionFromPoint(x, y); range = document.createRange(); range.setStart(pos.offsetNode, pos.offset); range.collapse(true); } // Next, the WebKit way else if (document.caretRangeFromPoint) { range = document.caretRangeFromPoint(x, y); } } return range; } function selectRange(range) { if (range) { if (typeof range.select != "undefined") { range.select(); } else if (typeof window.getSelection != "undefined") { var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } } } document.getElementById("editor").ondblclick = function(evt) { evt = evt || window.event; this.contentEditable = true; this.focus(); var caretRange = getMouseEventCaretRange(evt); // Set a timer to allow the selection to happen and the dust settle first window.setTimeout(function() { selectRange(caretRange); }, 10); return false; }; 
+17
source
 $('p').dblclick(function(event) { $this = $(this); $this.attr('contenteditable', "true"); $this.blur(); $this.focus(); }); 

http://jsfiddle.net/krtTD/90/

+1
source

Source: https://habr.com/ru/post/927865/


All Articles