Reputation: 1090
I'm trying to place a button next to the text that the user has selected like this:
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.
Upvotes: 1
Views: 138
Reputation: 13814
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
Upvotes: 1
Reputation: 6722
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.
Upvotes: 1
Reputation: 2693
get the parent node of the selection in your function and match its class with your matching value i.e. floatbtnable
Upvotes: 0