I'm trying to dynamically update a text selection in a particular HTML element. To this end, the link function contains
element.on('mouseup', function(event) {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
(Partly taken from https://stackoverflow.com/a/5379408/353337). This works well when clicking around and selecting text within element
.
The problem with this is that the mouseup
event is only intercepted on the particular element
. If I click anywhere else on the page, the text in the element is deselected as well, of course, but the event never fires.
How can I make sure that text
always contains the selected text in element?