How to find out if a custom range is within the HTML range

I am working on a Firefox add-on that converts the screen temperatures that are used when the user selects. After its conversion, the user selection is replaced with an HTML span element with the identifier alreadyconverted , which contains the initial temperature and the converted temperature in brackets. An obvious malfunction in the code is that the user can go through and select the converted temperature and transform it endlessly.

I want my Javascript code to detect when a custom selection is contained in a span element, overriding the span element or containing the entire span element. How can I detect Javascript when a user selects this span whole or in part?

I saw a similar question in StackOverflow, but he wanted to know when the user selection was contained entirely within a specific element. This is not exactly what I want, but I'm not sure what I will need to change in the code to fit my needs.

Check out JS Fiddle for this thread: http://jsfiddle.net/eT8NQ/

+5
source share
1 answer

After looking at the MDN documentation for Select, it seems that this feature is already supported directly. See Selection.containsNode() .

I updated your script and now it correctly returns the boolean value if any part of the element is in your selection.

 function elementContainsSelection(el) { if (window.getSelection) { var sel = window.getSelection(); if (sel.rangeCount > 0) { return sel.containsNode(el, true); } } return false; } 

This function returns false by default if the aPartlyContained flag is not set. Then partial containment will also return true.

aPartlyContained

When true, containsNode () returns true when the node part is part of the selection.

When false, containsNode () only returns true when the entire node is part of the selection.

+3
source

All Articles