palAlaa
palAlaa

Reputation: 9858

jQuery selector for text selection

I need a jquery selector that makes the same as ::selection in CSS3 .

I want an event to be triggered for each time I select a text in the document.

I found a solution but it works only for html tags. I need selector not only for html tags but also for any text .

Upvotes: 3

Views: 91

Answers (1)

BrianH
BrianH

Reputation: 2123

First, the :selection CSS tag has been removed from the W3C CSS3 Specification and is largely unsupported across browsers. But that wasn't your question! Just had to get that out of the way...

What I believe you want is actually a DOM function: window.getSelection()

Note: $(window).getSelection() isn't valid.

To get an event triggered by selection you might bind to related mouse/keyboard/touch events that could result in a selection, then use getSelection() to see if it did in fact result in a selection (by checking its length, for instance). You can then pair it with a timer to make sure you aren't throwing events for every letter selected, but that's obviously up to what specifically you want to do once the event is triggered.

You might also want to peruse this (non-duplicate!) question: Insert selected text on the page into textarea (jQuery)

Upvotes: 1

Related Questions