I'm using Rangy in conjunction with AngularJS. Angular replaces href with ng-click, so calling a function becomes:
<a ng-click='theFunctionThatCallsRangy()'>Get Range</a>
Unfortunately,
range.commonAncestorContainer
is returning the node of the anchor instead of the selection:
<a ng-click='theFunctionThatCallsRangy()'>Get Range</a>
and
range.collapsed
returns true. This leads me to believe clicking the anchor responsible for generating the range is destroying the selection before the range can be created from the selection.
As soon as I modify the anchor to:
<a href='#' ng-click='theFunctionThatCallsRangy()'>Get Range</a>
the range is created as expected. However, adding href='#' causes Angular to redirect to the root domain ('/'). Swapping out <a>
for <button>
also works, however this breaks existing CSS.
Why is this happening? Does Rangy expect href
to be present in anchor tags? Workarounds?
Rangy is only reporting what the browser tells it about the selection and has no opinion about whether the href
attribute is present. As you correctly diagnosed, the problem is that when you click on an <a>
element, the existing selection is destroyed by the time the click event fires. Assuming you continue using these <a>
elements, your options are:
mousedown
event instead<a>
element unselectable, which will obviously have its own consequences