Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Retrieving the selected text using JavaScript

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 269
    Comment on it

    In the example below, we have a textarea containing some text. When the user selects something using a mouse, we will check what user has selected. For that, we use selectionStart and selectionEnd properties of textarea, and we can get the selected text using formElement.value.substring().

    <textarea id="sample_quote" rows="4"  cols="30">
    Please select the text of your choice and you will see the selected text below.
    </textarea>
     
    <div id="selected_output"></div>
     
    <script>
     
    var sample_quote = document.getElementById('sample_quote')
    var selected_output = document.getElementById('selected_output')
    sample_quote.addEventListener('mouseup', function(){
        if (this.selectionStart != this.selectionEnd){ // check the user has selected some text inside field
            var selectedtext = this.value.substring(this.selectionStart,this.selectionEnd)
            selected_output.innerHTML = selectedtext
        }
    }, false)
     
    </script>

    There are some other methods that we can use. One of them is window.getSelection() for retrieving what the user has selected on the page. This method is supported by all modern browsers and IE9+.
    For example:

    var userSelectedText = window.getSelection().toString()

    Here, the text which is selected currently on that page is returned by window.getSelection() and it will returns a Selection object containing that data. To retrieve the actual text from the object we have used toString().

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: