3

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 .

palAlaa
  • 9,500
  • 33
  • 107
  • 166
  • That fiddle is working for the standalone text for me.. is it a particular browser you're having issues with? – MDEV Mar 15 '13 at 21:13
  • Well, I am working with Google chrome and it is not working. – palAlaa Mar 15 '13 at 21:18
  • The solution in the fiddle won't technically work anyway. Selection does *not* require use of a mouse. There is such a thing as **caret browsing** in which the user can easily navigate a page without a mouse, including text selection. This is an edge case, you say? Then what about the case where, upon making an initial selection with the mouse, the selection is *extended* by holding shift and using the arrow keys. Very common. – BinaryTox1n Mar 15 '13 at 21:25

1 Answers1

1

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)

Community
  • 1
  • 1
BrianH
  • 2,140
  • 14
  • 20