Reputation: 758
How can I handle the selectionchange
event of a textarea
?
I tried:
$('#editor').on('selectionchange', function () {
console.log(arguments);
});
Not working. Am I wrong?
Upvotes: 1
Views: 1474
Reputation: 1360
The selectionchange
event is fired when the current text selection on a document
is changed. This event works only if target object is a document
. This event for HTML Input Element
and HTML Text Area Element
, only supported in Firefox 52 and above. See the Browser compatibility.
So, Do you need to get the selected text in a textarea
? You may be asking for selectionStart
and selectionEnd
(does not exist in Internet Explorer, works with Firefox and Chrome). See the example below:
Example:
$( document ).on( 'mouseup', 'body', function() {
console.clear();
if ( getSelectionText() ) console.log( getSelectionText() )
});
function getSelectionText() {
if ( window.getSelection ) {
try {
var tarea = $( 'textarea' ).get(0);
return ( tarea.selectionStart != tarea.selectionEnd ) ? 'The event triggered. You select "' + tarea.value.substring( tarea.selectionStart, tarea.selectionEnd ) + '"' : '';
} catch ( e ) {
console.log( 'Cant get selection text' )
}
}
// For IE
if ( document.selection && document.selection.type != 'Control' )
return document.selection.createRange().text;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>Salam textarea</textarea>
Upvotes: 2
Reputation: 489
You should be able to do that by using focus HTML:
<form>
<input id="target" type="text" value="Field 1">
<input type="text" value="Field 2">
</form>
<div id="other">
Trigger the handler
</div>
Javascript
$( "#target" ).focus(function() {
alert( "Handler for .focus() called." );
});
By the example above you will find an idea on how you will be able to use focus to solve your problem
Upvotes: 0