1

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

Jinu Joseph Daniel
  • 5,864
  • 15
  • 60
  • 90

3 Answers3

5

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>
Sreenath
  • 106
  • 3
1

Do you mean something like this:


function getSelText()
{
    var txt = '';
     if (window.getSelection)
    {
        txt = window.getSelection();
    }
    else if (document.getSelection)
    {
        txt = document.getSelection();
    }
    else if (document.selection)
    {
        txt = document.selection.createRange().text;
    }
    else  { return; }
}
//txt is the selected text
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
0

Caching selected text, only available when it is editable input, but not in uneditable htm area i.e. when the text in div or span or etc. the above methods dosn't work .

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 11 '23 at 18:18