jquery - prevent selecting next dom when dbclicking text in contenteditable -
i have following contenteditable div, mixed text , dom inside follow :
some text<span> </span><span>like select </span>
my problem is, prevent double clicking word select span arround. exemple, if double click word 'which', selects word , it's needed behavior. problem is, if select word 'would', selects 'would '. how can select 'would' without span on double clic event ?
i tried add whitespace before , after, no result.
just add small snippet of javascript , single words selectable within span elements:
$('span').dblclick(function(e){ e.preventdefault(); var selection = window.getselection(); if (selection.tostring().indexof(' ') > -1) { var range = selection.getrangeat(0); var start = range.startoffset; var finish = range.endoffset - 1; setselectionrange(this, start, finish); } }); function gettextnodesin(node) { var textnodes = []; if (node.nodetype == 3) { textnodes.push(node); } else { var children = node.childnodes; (var = 0, len = children.length; < len; ++i) { textnodes.push.apply(textnodes, gettextnodesin(children[i])); } } return textnodes; } function setselectionrange(el, start, end) { if (document.createrange && window.getselection) { var range = document.createrange(); range.selectnodecontents(el); var textnodes = gettextnodesin(el); var foundstart = false; var charcount = 0, endcharcount; (var = 0, textnode; textnode = textnodes[i++]; ) { endcharcount = charcount + textnode.length; if (!foundstart && start >= charcount && (start < endcharcount || (start == endcharcount && <= textnodes.length))) { range.setstart(textnode, start - charcount); foundstart = true; } if (foundstart && end <= endcharcount) { range.setend(textnode, end - charcount); break; } charcount = endcharcount; } var sel = window.getselection(); sel.removeallranges(); sel.addrange(range); } else if (document.selection && document.body.createtextrange) { var textrange = document.body.createtextrange(); textrange.movetoelementtext(el); textrange.collapse(true); textrange.moveend("character", end); textrange.movestart("character", start); textrange.select(); } }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> text<span> </span><span>like select </span>
Comments
Post a Comment