Onselect event doesn't fire on div
Asked Answered
A

3

6

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?

Annmaria answered 28/12, 2008 at 10:19 Comment(0)
R
10

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.

Reedy answered 28/12, 2008 at 10:46 Comment(0)
R
5

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>
Rhodesia answered 15/2, 2012 at 15:9 Comment(1)
This is more or less what I'm looking for but it doesn't consider the possibility that the user will use the keyboard to extend or move the selection. But then, binding the same logic to onKeyUp will probably work.Phail
L
2

Use OnClick.

:select only applies to some form elements.

Labana answered 28/12, 2008 at 11:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.