I want to implement element in-placing edit using 'contenteditable' attribute. Is it possible to go into the edit state with mouse event simulation instead of user click?
function triggerEvent(element, eventType) {
let rect = element.getBoundingClientRect();
console.log(rect);
let event = new MouseEvent(eventType, {
clientX: rect.left + 20,
clientY: rect.top + 10,
view: window,
buttons: 1,
bubbles: true,
});
element.dispatchEvent(event);
}
document.getElementById('btn').addEventListener('click', (event) => {
let editArea = document.getElementById('edit-area');
editArea.setAttribute('contenteditable', true);
triggerEvent(editArea, 'mousedown');
});
DEMO: https://jsfiddle.net/lfree/vkeq9fza/1/
You just need to focus
the div:
let div = document.querySelector('div');
div.focus();
<div contenteditable="true">Div Content</div>
If I understand correctly, all you're trying to do is set focus to the element. Because you've already enabled contenteditable
, the following should be adequate:
editArea.setAttribute('contenteditable', true);
editArea.focus(); // Focus on the input which will activate editing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With