user1211599
user1211599

Reputation: 1

How to select event in div?

<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)

Upvotes: 0

Views: 4661

Answers (3)

MD SHAYON
MD SHAYON

Reputation: 8055

I have used selection changed event you can try that

    document.addEventListener('selectionchange', (e)=>{
        console.log("Archor node - ",window.getSelection().anchorNode.parentElement);
    });

Upvotes: 0

Fahim Parkar
Fahim Parkar

Reputation: 31633

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>

Upvotes: 3

A.B.Cade
A.B.Cade

Reputation: 16905

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

Upvotes: 1

Related Questions