Choosing the position of selected div text with javascript

I need to get the position of the selected text in a non editable content div (not a text box, not an rtf editor, just a simple div)

I want to do this so that users can select fragments of the article and "select it", wrapping it in the interval with a different background and, of course, the article is built with divs and / or ps, etc., and not textareas or rtfs

Any ideas?

Ps You can also use jQuery: D

Pss I need a position of choice, not the choice itself. Aka: it starts with index I to index J. I need this because the usual method of finding text in the parent object does not always return a unique result, which suck :)

+4
source share
5 answers

If you just want to change the background of the selected text, the easiest way to do this is to use document.execCommand() . See My answer here: Change CSS of selected text using Javascript

+3
source
 //Wrap selected text in span tags with the class 'hl' //Take some action after (in this case, a simple alert) $("p").live("mouseup", function() { selection = getSelectedText(); if(selection.length >= 3) { $(this).html($(this).html().replace(selection, $('<\/span>').attr({'class':'hl'}).html(selection).parent().html()) ); alert(selection); } } ); //Grab selected text function getSelectedText(){ if(window.getSelection){ return window.getSelection().toString(); } else if(document.getSelection){ return document.getSelection(); } else if(document.selection){ return document.selection.createRange().text; } } 

The code comes from here: http://esbueno.noahstokes.com/post/92274686/highlight-selected-text-with-jquery

+2
source

You can check if the text is selected at startup:

 window.getSelection and document.getSelection() and document.selection 

(because browsers can check this in different ways) and then find the div containing this text.

0
source

Well, although you have found a solution to the problem outlined in your second paragraph, I don’t think the answer to your main question has been given. :)

The Selection object has a property called anchorOffset , giving what you requested (the position of the selected text inside the element). The link above talks about which browsers support it, I'm afraid IE <9 cannot.

 function show_selected() { var sel = selection(); console.log(sel.anchorOffset + ':' + sel); } 

Now, if you show_selected to, say, mouseup , you will see the offset and selected text printed on the js console.

The frontsia selection may be as follows, supposedly cross-browser:

 function selection() { var sel; if(window.getSelection){ sel = window.getSelection() } else if(document.getSelection){ sel = document.getSelection() } else if(document.selection){ sel = document.selection.createRange() } return sel } 
0
source

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


All Articles