Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger 'contenteditable' element into edit state using js?

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/

like image 818
lfree Avatar asked Jan 21 '17 07:01

lfree


2 Answers

You just need to focus the div:

let div = document.querySelector('div');

div.focus();
<div contenteditable="true">Div Content</div>
like image 155
KevBot Avatar answered Oct 03 '22 04:10

KevBot


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
like image 34
grovesNL Avatar answered Oct 03 '22 04:10

grovesNL