Target selected text in Javascript

Looking for a method to target selected text and perform actions on it in Javascript. What methods should I use? Is this work for jQuery? Many thanks!

EDIT: Earlier answers were seen as targeting a CSS class. I am looking for a click and a selection / selection of text, and then an action on JS. Thanks!

EDIT 2: I was asked to give an example of this function. Here , but the code has bad reviews. Let me know what you think.

+6
source share
2 answers

It’s hard to write a cross browser, the general β€œget selected text” function. If you can limit your requirements to say only the text selected on the page, then life is easier.

But if you want to receive text selections from anywhere (inside format controls, button shortcuts, common text), then life is tough.

Here is some function that I wrote some time ago, it worked well enough for the application in which it was used:

/* * This function returns the selected text in a document. * If no text selected, returns an empty string. * * Call on one of the following events: * * mouseup - most appropriate event * for selection by mousedown, drag to select, mouseup * may select only whitespace * * dblclick - not as appropriate as mouseup * for selection of word by double click * may select only whitespace * * Note that text can be selected in ways that do not dispatch * an event, eg selecting all the text in the document using: * ctrl + a * context menu -> Select All * edit menu -> Select All * programmatically selecting text */ function checkForSelectedText(e) { var e = e || window.event; var el = e.target || e.srcElement; var tagName = el.tagName && el.tagName.toLowerCase(); var t; var d = document; // Try DOM 2 Range - for most browsers, including IE 6+ // However, doesn't get text selected inside form controls // that allow selection of text content (input type text, // textarea) if (d && d.selection && d.selection.createRange) { t = d.selection.createRange().text; // Otherwise try HTML5 - note that getSelection returns // a string with extra properties. This may also get // text within input and textarea } else if (d.getSelection) { t = d.getSelection(); } // If didn't get any text, see if event was inside // inupt@type =text or textarea and look for text if (t == '') { if (tagName == 'textarea' || (tagName == 'input' && el.type == 'text')) { // Check selectionStart/End as otherwise if no text // selected, IE returns entire text of element if (typeof el.selectionStart == 'number' && el.selectionStart != el.selectionEnd) { t = el.value.substring(el.selectionStart, el.selectionEnd) } } } return t; } 
+4
source

Try window.getSelection , you should also read on Selection and Range .

+4
source

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


All Articles