1

I'm trying to place a button next to the text that the user has selected like this:

'Embed Quote' button next to user selection on Quora.

But I want to place it only if the selection is on text that is inside divs with class floatbtnable. For example:

<div class='foo'><!--The floating button doesn't show up if user selects text that is in here --></div>
<div class='floatbtnable'><!--If the user selects text that is in here, the floating button shows up next to user selection. --></div>

NOTE: I've figured out how to place a button next to the user selection, I just want to add a filter such that the button shows up only for a particular class of selected text and not all the time.

haky_nash
  • 1,040
  • 1
  • 10
  • 15
  • 3
    I'm the type of user who, when reading large bodies of text, highlights certain words to let me easily see where the next line of text is. With this approach, the "Embed Quote" button would be placed on top of the line of text I'm next wanting to read. As a user, I personally would be very frustrated by this. – James Donnelly Dec 19 '14 at 10:47
  • *I've figured out how to place a button next to the user selection*. It'd be helpful if you put the code that did this into the question then? – Liam Dec 19 '14 at 10:51
  • May be the way you are placing the button, has the answer of your question. So please put the code or make fiddle sample. – Shyam Dec 19 '14 at 10:53

3 Answers3

1

how about finding like this.

$(window.getSelection().focusNode.parentNode).closest('.floatbtnable').length

window.getSelection() has a property called focusNode which has a property called parentNode. I think you can make use of that property.

NOTE: Not sure about the browser compatibility.

Cerlin
  • 6,622
  • 1
  • 20
  • 28
1

You can use window.getSelection to get the selected text. This works in all modern browsers, but not for Internet Explorer 8 or less [1]. You can use this to find the common ancestor to all selected text elements. If you create a jQuery object from this you can use the $.closest method to see if there is an ancestor with the class floatbtnable.

var selection = window.getSelection()
var commonAncestor = selection.getRangeAt(0).commonAncestorContainer
var isSelectable = $(commonAncestor).closest('floatbtnable').length !== 0;

See http://codepen.io/ckuijjer/pen/bNeMWr for a implementation. If you select text in the yellow background (it shouldn't also select text out it will appear in the selected text <textarea>, other text selections won't. I've used a mouseup event on the body as a trigger.

[1] See Get the Highlighted/Selected text for a solution if you need to support older browsers

Community
  • 1
  • 1
ckuijjer
  • 13,293
  • 3
  • 40
  • 45
0

get the parent node of the selection in your function and match its class with your matching value i.e. floatbtnable

Rahul Munjal
  • 2,551
  • 2
  • 15
  • 35