Search code examples
javascriptselectmousebolditalic

Knowing the text selected using mouse in javascript


I my application i want to make the text seleected selected using mouse bold..How to do this using javascript? Also how to know the cursor position using javascript...For example ,i may need to insert a text using my function just before the text where cursor is placed


Solution

  • You can do this in a textarea:

    <html>
    <head>
    
    <title>onselect test</title>
    
    <script type="text/javascript">
    
    window.onselect = selectText;
    
    function selectText(e)
    {
        start = e.target.selectionStart;
        end = e.target.selectionEnd;
        alert(e.target.value.substring(start, end));
    }
    </script>
    </head>
    
    <body>
    <textarea>
    Highlight some of this text
    with the mouse pointer
    to fire the onselect event.
    </textarea>
    </body>
    </html>