22

I want to get the selected text position using javascript. For example,
I have a simple textarea.

#input-text {
  resize: none;
  width: 50%;
  height: 50px;
  margin: 1rem auto;
}
<textarea id="input-text">I am a student and I want to become a good person</textarea>

In my textarea, I have some text such as:

"I am a student and I want to become a good person"

From this string, if I select "become a good person" from the textarea,
Then How can I get the selected text/ string position in javascript?


Here the selected string character starts from 29 and ends in 49. So the start position is 29 & the end position is 49

Tahazzot
  • 1,060
  • 2
  • 21
  • 1
    By position you mean what is the index of character "b" of "become" in the string? – palaѕн Feb 23 '20 at 07:08
  • I feel like the question is just asking for [HTMLInputElement.selectionStart](https://webplatform.github.io/docs/dom/HTMLInputElement/selectionStart/) and [selectionEnd](https://webplatform.github.io/docs/dom/HTMLInputElement/selectionEnd/) while the answers mostly talk about the selection event. No point in writing an answer that's included in all the other answers, though. – JollyJoker Feb 24 '20 at 10:16
  • 1
    Does this answer your question? [How to get selected text from textbox control with javascript](https://stackoverflow.com/questions/275761/how-to-get-selected-text-from-textbox-control-with-javascript) – Matsemann Feb 24 '20 at 11:41

5 Answers5

31

This will work for text selection with the mouse and keyboard for all <textarea> elements on the page. Change the selector (be more specific) if you don't want all <textarea> elements to have this text selection.

Read the comments, you will find out there how to disable keyboard selection, if you don't want/need keyboard selection.

var mySelection = function (element) {
    let startPos = element.selectionStart;
    let endPos = element.selectionEnd;
    let selectedText = element.value.substring(startPos, endPos);

    if(selectedText.length <= 0) {
      return; // stop here if selection length is <= 0
    }
    
    // log the selection
    console.log("startPos: " + startPos, " | endPos: " + endPos );
    console.log("selectedText: " +  selectedText);

  };

var textAreaElements = document.querySelectorAll('textarea');
[...textAreaElements].forEach(function(element) {
    // register "mouseup" event for the mouse
    element.addEventListener('mouseup', function(){
        mySelection(element)
    });
    
    // register "keyup" event for the keyboard
    element.addEventListener('keyup', function( event ) {
        // assuming we need CTRL, SHIFT or CMD key to select text
        // only listen for those keyup events
        if(event.keyCode == 16 || event.keyCode == 17 || event.metaKey) {
            mySelection(element)
        }
    });
});
textarea {
   resize: none; 
   width: 50%;
   height: 50px; 
   margin: 1rem auto;
}
<textarea>I am a student and I want to become a good person</textarea>
caramba
  • 19,727
  • 15
  • 78
  • 118
5

I would make use of of onselect event to get the same.

<textarea id="input-text" onselect="myFunction(event)">I am a student and I want to become a good person</textarea>


<script>
    function myFunction(event) {
      const start  = event.currentTarget.selectionStart;
      const end= event.currentTarget.selectionEnd;
    }
</script>
Dreamweaver
  • 1,175
  • 8
  • 21
2

Caramba answer worked pretty great, however I had the issue that if you selected some text and released the mouse outside of the textarea, the event didn't fire.

To solve this i changed the initial event to mousedown, this event registers a mouseup event on the document to ensure it fires after the cursor is released. The mouseup event then removes itself after it has fired.

This can be achieved with adding the once option to addEventListener, but sadly isn't supported in IE11 which is why i used the solution in the snippet.

var mySelection = function (element) {
    let startPos = element.selectionStart;
    let endPos = element.selectionEnd;
    let selectedText = element.value.substring(startPos, endPos);

    if(selectedText.length <= 0) {
      return; // stop here if selection length is <= 0
    }
    
    // log the selection
    console.log("startPos: " + startPos, " | endPos: " + endPos );
    console.log("selectedText: " +  selectedText);
};

function addSelfDestructiveEventListener (element, eventType, callback) {
    let handler = () => {
        callback();
        element.removeEventListener(eventType, handler);
    };
    element.addEventListener(eventType, handler);
};

var textAreaElements = document.querySelectorAll('textarea');
[...textAreaElements].forEach(function(element) {
    // register "mouseup" event for those
    element.addEventListener('mousedown', function(){
      // This will only run the event once and then remove itself
      addSelfDestructiveEventListener(document, 'mouseup', function() {
        mySelection(element)
      })
    });
    
    // register "keyup" event for the keyboard
    element.addEventListener('keyup', function( event ) {
        // assuming we need CTRL, SHIFT or CMD key to select text
        // only listen for those keyup events
        if(event.keyCode == 16 || event.keyCode == 17 || event.metaKey) {
            mySelection(element)
        }
    });
});
textarea {
   resize: none; 
   width: 50%;
   height: 50px; 
   margin: 1rem auto;
}
<textarea>I am a student and I want to become a good person</textarea>
Hiws
  • 5,391
  • 1
  • 9
  • 27
1
    var idoftextarea='answer';
    function getSelectedText(idoftextarea){
        var textArea = document.getElementById(idoftextarea);
        var text =textArea.value;
        var indexStart=textArea.selectionStart;
        var indexEnd=textArea.selectionEnd;
        alert(text.substring(indexStart, indexEnd));

    }


    getSelectedText(idoftextarea);


Nourhan Ahmed
  • 184
  • 1
  • 10
0
var mySelection = function (element) {
let startPos = element.selectionStart;
let endPos = element.selectionEnd;
let selectedText = element.value.substring(startPos, endPos);

if(selectedText.length <= 0) {
  return; // stop here if selection length is <= 0
}

// log the selection
console.log("startPos: " + startPos, " | endPos: " + endPos );
console.log("selectedText: " +  selectedText); };var textAreaElements = document.querySelectorAll('textarea'); 
[...textAreaElements].forEach(function(element) {
// register "mouseup" event for the mouse
element.addEventListener('mouseup', function(){
    mySelection(element)
});
// register "keyup" event for the keyboard
element.addEventListener('keyup', function( event ) {
    // assuming we need CTRL, SHIFT or CMD key to select text
    // only listen for those keyup events
    if(event.keyCode == 16 || event.keyCode == 17 || event.metaKey) {
        mySelection(element)
    }
});});