How to trigger an event when there is selection inside a contentEditable div?
I want to trigger an event when the user selects some text/element in a contentEditable div. Accordingly I want to inactivate certain buttons in a Rich Text Editor.
There are some events which can be triggered based upon change of content. I only want an event when the user selects some content.
Solution 1:
A relatively simplified version could look like this, depending on your needs you might need to handle browsers like old IE's etc. that do not support window.getSelection()
!
const handleSelection = function() {
const btn = document.querySelector('#btn');
let selection = window.getSelection().anchorNode.textContent
.substring(
window.getSelection().extentOffset,
window.getSelection().anchorOffset
);
if (selection.length !== 0) {
btn.setAttribute('disabled', true);
} else {
btn.removeAttribute('disabled');
}
};
['mouseup', 'keyup', 'selectionchange'].forEach((e) => {
document.querySelector('#editable').addEventListener(e, handleSelection);
});
#btn[disabled] {
cursor: default;
opacity: 0.3;
}
<button type="button" id="btn">Button (disabled when something is selected)</button>
<div id="editable" contenteditable>
<p>I'm some content that is editable!</p>
</div>
Solution 2:
You can add event listener to the element for mouseup
event and get the selection from window
after that:
<div contenteditable="true" id="editableDiv">Some content</div>
And the js:
document.getElementById("editableDiv").addEventListener("mouseup", function() {
var s = window.getSelection();
if(s == "something"){
//do your thing
}
}, false);