91

How to trigger a JavaScript function when someone selects a given text fragment on a page using mouse?
Also, is there any way to find the position of selected text on the page?

Update: To be more clear, text fragment can be part of a sentence or a word or a phrase or whole a paragraph.

el-teedee
  • 1,293
  • 1
  • 15
  • 27

10 Answers10

90

Update: In the meantime, a "Text was selected" (DOM) event was created and is supported by all current browsers: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select_event

Note this event only works on form elements, i.e. added to the HTMLInputElement API


There is no "Text was selected" (DOM) event, but you can bind a mouseup event to the document.body. Within that event handler, you might just check the

document.selection.createRange().text

or

window.getSelection()

methods. There are several topics on Stackoverflow, like this one javascript to get paragraph of selected text in web page.

I'm not sure what you mean with "finding the position", but to stay in my example world you could use the event propertys for X+Y mouse positions.

Example: http://www.jsfiddle.net/2C6fB/1/

Nate Anderson
  • 18,334
  • 18
  • 100
  • 135
jAndy
  • 231,737
  • 57
  • 305
  • 359
  • Thanks Andy, Ya I think best we can get is X+Y mouse positions. –  Aug 23 '10 at 06:15
  • 6
    You should also consider selection via the keyboard. – Tim Down Aug 23 '10 at 08:26
  • Thanks for comments Tim. any pointers to selection via the keyboard? –  Aug 23 '10 at 12:11
  • 6
    There is a "Text was selected" (DOM) event: http://www.w3schools.com/jsref/event_onselect.asp – user681814 Mar 28 '13 at 12:55
  • 5
    When it comes to keyboard selection, I watched for the user releasing shift: `document.addEventListener('keyup', function(e) { var key = e.keyCode || e.which; if (key == 16) highlight(); });` – willlma May 30 '13 at 22:03
  • 4
    The [selectionchange](https://developer.mozilla.org/en-US/docs/Web/Events/selectionchange) event is preferable because `window.getSelection()` might return old `selection` objects on `mouseup` events. – Cani Jan 30 '19 at 11:01
  • 2
    @user681814 - [Only for form controls, not other elements](https://html.spec.whatwg.org/multipage/indices.html#event-select). – T.J. Crowder Sep 13 '21 at 08:25
  • Updated answer: things have changed, now you can use select event. https://developer.mozilla.org/en-US/docs/Web/API/Element/select_event And also selectionchange(https://developer.mozilla.org/en-US/docs/Web/Events/selectionchange), as mentioned above – Guseyn Ismayylov Nov 28 '21 at 13:33
  • 1
    @GuseynIsmayylov: **HTMLInputElement** is the key part in the links you posted. As T.J. Crowder said, these events are triggered only for form controls. – FiddlingAway Mar 05 '23 at 13:05
69

Here's a quick mashup:

$('div').mouseup(function() {
    var text=getSelectedText();
    if (text!='') alert(text);
});

function getSelectedText() {
    if (window.getSelection) {
        return window.getSelection().toString();
    } else if (document.selection) {
        return document.selection.createRange().text;
    }
    return '';
}​

<div>Here is some text</div>

Demo: http://jsfiddle.net/FvnPS/11/

Synetech
  • 9,643
  • 9
  • 64
  • 96
karim79
  • 339,989
  • 67
  • 413
  • 406
  • 9
    There seems to be a pervasive idea that `window.getSelection();` is equivalent to IE's `document.selection.createRange().text;`. Are people copying from the same, inaccurate source? Anyway, `window.getSelection()` returns a `Selection` object while `document.selection.createRange().text;` returns a string, which is a very different object. The confusion arises from the fact that the `toString` method of `Selection` object returns the selected text, meaning that `alert(window.getSelection());` will alert the selected text. – Tim Down Aug 23 '10 at 08:25
  • Fixed. The mozilla docs say: "This makes the selection object appear like a string, when it is really an object with its own properties and methods. Specifically, the return value of calling the toString() method of the Selection object is passed." :) https://developer.mozilla.org/en/window.getSelection – karim79 Aug 23 '10 at 08:58
  • 3
    Heh. I hadn't seen that before. Sorry to whinge on your answer: as you may have inferred, I've corrected this a few times on SO before. – Tim Down Aug 23 '10 at 09:22
  • 4
    @Tim Down - You weren't winging, you were in fact correct and did the right thing in pointing that out. – karim79 Aug 23 '10 at 09:44
  • 1
    MDN link above is not working anymore. The new might be https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection – DerMike Jun 09 '22 at 11:39
  • Yes thanks @DerMike for an updated link, here's a link to the specific section about string representation. https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection#string_representation_of_the_selection_object For anyone reading the comment now, @karim79's original answer just returned `window.getSelection();` directly; but @karim79 edited the answer to explicitly return `...getSelection().toString()`, and therefore I think he addressed @TimDown's concern, (check edit history) – Nate Anderson Apr 17 '23 at 15:57
15

There is a new experimental API that deals with this:

The selectionchange event of the Selection API is fired when the selection object of the document is modified, or when the selection associated with an <input> or a <textarea> changes. The selectionchange event is fired at the document in the first case, on the element in the second case.

https://developer.mozilla.org/en-US/docs/Web/Events/selectionchange

Note that this is bleeding edge and not guaranteed to work across even major browsers.

Ricky Han
  • 1,309
  • 1
  • 15
  • 25
  • 2
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/13804253) – eisbehr Sep 27 '16 at 06:24
  • I have modified the answer – Ricky Han Sep 27 '16 at 06:41
  • The latest standard is also missing a basic "selectable" property; so a vendor prefix is still required as every browser implements it differently. Again, this has existed in ActionScript for 2 decades since v1: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/TextField.html#selectable – Triynko Jan 30 '17 at 19:31
  • It's worth noting that while this is still experimental, at the time of this comment, every major browser implements this, and this will work for 96.7% of web users. https://caniuse.com/?search=selectionchange – talljosh Dec 06 '21 at 10:23
6

I'm not sure about the mouse thing but this line works for mobile, this invoked every time a change made on the text selection -

document.addEventListener('selectionchange', () => {

});
ozd
  • 1,194
  • 10
  • 34
2

When you press the mouse button down, the mousedown event is fired, when the mouse button is released, the mouseup and then click events are fired.

So we listen to the mouseup event and check if any text has been selected, and respective operations are performed.

const p = document.getElementById('interactiveText');

p.addEventListener('mouseup', (e) => {
  const selection = window.getSelection().toString();

  if (selection === '') {
    console.log('click');
  } else {
    console.log('selection', selection);
  }
});
1

AFAIK, there is no such event you described. But you can emulate that function.

Look over here for the code and demo.

vikmalhotra
  • 9,981
  • 20
  • 97
  • 137
1

There is "Text was selected" event. But only for textarea as I hava known.

<textarea onselect="message()" name="summary" cols="60" rows="5">
请写入个人简介,不少于200字!
</textarea>
Macist
  • 11
  • 3
0

There is a shortcut to get the selected text from event object.

event.currentTarget[event.currentTarget.selectedIndex].text
Dharman
  • 30,962
  • 25
  • 85
  • 135
fj.agmedia
  • 87
  • 5
0

You can check it out on MDN. It's exactly what you need.

https://developer.mozilla.org/en-US/docs/Web/API/Element/select_event

The event is trigger and return the selected text when the selection is done.

If you want the selected text on every time the selection change. There is the selectionchange event for document and html input and textarea. Selectionchange event for document is supported on most browsers but it is supported only on Firefox for html input and textarea elements.

There is a polyfill for that which will support for all browsers.

https://github.com/channyeintun/selection

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 25 '21 at 11:50
-1
var selectedText = "";

if (window.getSelection) {
    selectedText = window.getSelection();
}

if (document.getSelection) {
    selectedText = document.getSelection();
}

if (document.selection) {
    selectedText = document.selection.createRange().text;
}

function textSelector() {
   alert(selectedText);
}
textSelector();
Mowneshachar
  • 11
  • 1
  • 7