Reputation: 1
<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
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
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
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