0
<div id="container" style="border: 1px solid #333" contentEditable="true">Type text    here</div>

Is there a function to be triggered when I select text? (Type text here)

user1211599
  • 1
  • 1
  • 1
  • 1
    possible duplicate of [Can I get a Javascript event from the selection of text outside of text or textarea?](http://stackoverflow.com/questions/1791526/can-i-get-a-javascript-event-from-the-selection-of-text-outside-of-text-or-texta) – Shadow The GPT Wizard Feb 15 '12 at 14:53
  • check my solution... your problem is solved.... – Fahim Parkar Feb 15 '12 at 15:08
  • @FahimParkar: Not really. Selection can also be triggered by the keyboard or by the edit and context menus. – Tim Down Feb 17 '12 at 11:03
  • possible duplicate of [How to bind a handler to a selection change on window?](http://stackoverflow.com/questions/8991511/how-to-bind-a-handler-to-a-selection-change-on-window) – Tim Down Feb 17 '12 at 11:06

3 Answers3

3

You can achieve what you want by using onMouseUp event. See below...

<html>
    <body>
        <div id="container" style="border: 1px solid #333" contentEditable="true" onMouseUp="checkMe()">Type text    here</div>

    </body>
    <script language="javascript">
    function checkMe() {
        var txt = "";

        if (window.getSelection) {
            txt = window.getSelection();
        } else if (document.getSelection) {
            txt = document.getSelection();
        } else if (document.selection) {
            txt = document.selection.createRange().text;
        }

        alert("Selected text is " + txt);
    }
    </script>
</html>
Fahim Parkar
  • 30,974
  • 45
  • 160
  • 276
1

You can use onMouseUp event and check if there is a selection as in this example:
http://jsfiddle.net/2gLLp/

see also: http://www.codetoad.com/javascript_get_selected_text.asp

A.B.Cade
  • 16,735
  • 1
  • 37
  • 53
0

I have used selection changed event you can try that

    document.addEventListener('selectionchange', (e)=>{
        console.log("Archor node - ",window.getSelection().anchorNode.parentElement);
    });
MD SHAYON
  • 7,001
  • 45
  • 38