简体   繁体   中英

jQuery on textarea selectionchange

How can I handle the selectionchange event of a textarea ?

I tried:

$('#editor').on('selectionchange', function () {
   console.log(arguments);               
});

Not working. Am I wrong?

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> 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM