Split div content at cursor position

I need to break an element after the user clicks on it and attr 'contenteditable' becomes true. This script works for the first paragraph, but not the second, because the last is in the p tag. Similary in this script you will see that when an element has html tags in it, the counter loses accuracy and, therefore, the text before and after the cursor is not what you expect.

Users are expected to share data so that the help tags remain intact. As indicated by the dandavis here, for example, a div has <i>Hello</i> <b>Wo*rld</b> , the user will only need to split the div into two divs, first there will be <i>Hello</i> , and the second div will have <b>Wo*rld</b> in it.

Html:

 <div><mark>{DATE}</mark><i>via email: </i><mark><i>{EMAIL- BROKER OR TENANT}</i></mark></div> 

JS:

 var $splitbut = $('<p class="split-but">Split</p>'); $(this).attr('contenteditable', 'true').addClass('editing').append($splitbut); var userSelection; if (window.getSelection) { userSelection = window.getSelection(); } var start = userSelection.anchorOffset; var end = userSelection.focusOffset; var before = $(this).html().substr(0, start); var after = $(this).html().substr(start, $(this).html().length); 

The "Split" button does not work, since html generation is not a problem when I get the correct text "after" and "before". Any ideas on what I'm doing wrong here?

+7
javascript jquery html
source share
1 answer

Something like this might work for the specific case you are describing

 $('div, textarea').on('click', function(e) { var userSelection; if (window.getSelection) { userSelection = window.getSelection(); } var start = userSelection.anchorOffset, end = userSelection.focusOffset, node = userSelection.anchorNode, allText = $(this).text(), nodeText = $(node).text(); // before and after inside node var nodeBefore = nodeText.substr(0, start); var nodeAfter = nodeText.substr(start, nodeText.length); // before and after for whole of text var allExceptNode = allText.split(nodeText), before = allExceptNode[0] + nodeBefore, after = nodeAfter + allExceptNode[1]; console.log('Before: ', before); console.log('------'); console.log('After: ', after); }); 

Updated demo at https://jsfiddle.net/gaby/vaLz55fv/10/


It can be problematic if there are tags whose contents are repeated throughout the text. (problem due to splitting)

+1
source share

All Articles