user178841
user178841

Reputation:

Selected text event trigger in Javascript

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.

Upvotes: 96

Views: 112639

Answers (11)

jAndy
jAndy

Reputation: 235962

Update: Starting in 2017, browsers support the selectionchange event for this purpose, part of the Selection API.

For older browsers, a "Text was selected" (DOM) is supported: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select_event but 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/

Upvotes: 93

Jeromearsene
Jeromearsene

Reputation: 176

You have 2 approaches and 1 subtlety if you want to detect selected text in JS.

Approaches

1. By mouse event

As mentioned in other responses, you can use a listener on the mouseup event:

document.addEventListener("mouseup", async () => {
  setTimeout(async () => {
    console.log(window.getSelection().toString())
  }, 10)
})

2. By keyboard event

To detect the select all keyboard shortcut:

document.addEventListener("keydown", async (event) => {
  if ((event.metaKey || event.ctrlKey) && event.key === "a") {
    setTimeout(async () => {
      console.log(window.getSelection().toString())
    }, 10)
  }
})

Here, you need to detect Ctrl + A (Windows)or Cmd + A (Mac).

Subtlety

setTimeout

Why use setTimeout in my examples ? A short delay is used to allow the browser to complete the selection operation. This is to avoid interfering with the default behavior. Sometimes I sometimes encountered detection problems (Chrome extension context). With this delay, the error disappeared.

Upvotes: 0

Chan Nyein Tun
Chan Nyein Tun

Reputation: 1

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

Upvotes: 0

fj.agmedia
fj.agmedia

Reputation: 87

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

event.currentTarget[event.currentTarget.selectedIndex].text

Upvotes: 0

Damian Czapiewski
Damian Czapiewski

Reputation: 881

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);
  }
});

Upvotes: 3

ozd
ozd

Reputation: 1284

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

});

Upvotes: 10

Mowneshachar
Mowneshachar

Reputation: 9

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();

Upvotes: -1

Macist
Macist

Reputation: 11

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>

Upvotes: 1

Ricky Han
Ricky Han

Reputation: 1367

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.

Upvotes: 16

karim79
karim79

Reputation: 342635

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/

Upvotes: 71

vikmalhotra
vikmalhotra

Reputation: 10071

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

Look over here for the code and demo.

Upvotes: 1

Related Questions