Is there an event for the end of text selection on iOS?
I know I can run an event when the selection changes through the following:
document.addEventListener("selectionchange", function(event) {
var text = window.getSelection().toString();
$(".output").append("<div>" + text + "</div>");
}, false);
<div class="output"></div>
This will update .output
with the selected text, but runs every time the selection changes. What I would want, is to only capture the text after the selection has finished.
Is there any such event? Is it possible to do something like this?
The selectionchange event of the Selection API is fired when the current Selection of a Document is changed. This event is not cancelable and does not bubble. The event can be handled by adding an event listener for selectionchange or using the onselectionchange event handler.
The OnSelectionChanged method also allows derived classes to handle the event without attaching a delegate. This is the preferred technique for handling the event in a derived class.
getSelection() method returns a Selection object representing the range of text selected by the user or the current position of the caret.
Similar to you i didn't found a good solution for this problem, So i decided to create a workaround. it's not the prettiest but it works.
I created a timeout function and bind it to a "onselectionchange" event. Each time the event fired i check if my timeout is running, and if so i delete it and create a new one.
when the timeout is finished a custom event "selectionEnd" is fired.
// bind selection change event to my function
document.onselectionchange = userSelectionChanged;
function userSelectionChanged() {
// wait 500 ms after the last selection change event
if (selectionEndTimeout) {
clearTimeout(selectionEndTimeout);
}
selectionEndTimeout = setTimeout(function () {
$(window).trigger('selectionEnd');
}, 500);
}
$(window).bind('selectionEnd', function () {
// reset selection timeout
selectionEndTimeout = null;
// TODO: Do your cool stuff here........
// get user selection
var selectedText = getSelectionText();
// if the selection is not empty show it :)
if(selectedText != ''){
// TODO: Do something with the text
}
});
DEMO: http://jsfiddle.net/dimshik/z8Jge/
I wrote a small post about it in my blog: http://www.dimshik.com/end-of-text-selection-event-on-ios-workaround/
How about binding a mouseup
event?
JAVASCRIPT:
document.addEventListener("mouseup", function(event) {
var text = window.getSelection().toString();
$(".output").append("<div>" + text + "</div>");
}, false);
DEMO: http://jsfiddle.net/dirtyd77/yTMwu/66/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With