95

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.

0

10 Answers 10

92

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/

9
  • 6
    You should also consider selection via the keyboard.
    – Tim Down
    Commented Aug 23, 2010 at 8:26
  • 6
    There is a "Text was selected" (DOM) event: w3schools.com/jsref/event_onselect.asp
    – user681814
    Commented Mar 28, 2013 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
    Commented May 30, 2013 at 22:03
  • 4
    The selectionchange event is preferable because window.getSelection() might return old selection objects on mouseup events.
    – Cani
    Commented Jan 30, 2019 at 11:01
  • 2
    @user681814 - Only for form controls, not other elements. Commented Sep 13, 2021 at 8:25
71

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/

6
  • 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
    Commented Aug 23, 2010 at 8: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." :) developer.mozilla.org/en/window.getSelection
    – karim79
    Commented Aug 23, 2010 at 8: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
    Commented Aug 23, 2010 at 9:22
  • 4
    @Tim Down - You weren't winging, you were in fact correct and did the right thing in pointing that out.
    – karim79
    Commented Aug 23, 2010 at 9:44
  • 1
    MDN link above is not working anymore. The new might be developer.mozilla.org/en-US/docs/Web/API/Window/getSelection
    – DerMike
    Commented Jun 9, 2022 at 11:39
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.

4
  • 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
    – eisbehr
    Commented Sep 27, 2016 at 6:24
  • I have modified the answer
    – Ricky Han
    Commented Sep 27, 2016 at 6: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: help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/…
    – Triynko
    Commented Jan 30, 2017 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. caniuse.com/?search=selectionchange
    – talljosh
    Commented Dec 6, 2021 at 10:23
8

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', () => {

});
1
  • This worked on chrome Commented Apr 11, 2022 at 8:27
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.

2
  • 1
    Thanks ShiVik, it is really helpful. Does this emulation has browser dependence?
    – user178841
    Commented Aug 23, 2010 at 6:23
  • @abhishiktiwari - AFAIU the blog - none Commented Aug 23, 2010 at 6:53
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>
0

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

event.currentTarget[event.currentTarget.selectedIndex].text
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
  • 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.
    – Community Bot
    Commented Sep 25, 2021 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();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.