Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Onselect event doesn't fire on div

Tags:

html

onselect

I have been unable to trigger an onselect event handler attached to a <div> element. Is it possible to force a <div> to emit select events?

like image 815
dpq Avatar asked Dec 08 '22 08:12

dpq


2 Answers

According to w3schools, onSelect is only defined on input and textarea objects.

You may however try to catch the MouseUp event and retrieve the selected text in the current window/document.

like image 170
devio Avatar answered Dec 28 '22 02:12

devio


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>
like image 44
Fahim Parkar Avatar answered Dec 28 '22 02:12

Fahim Parkar