6

What kind of event do I need to fire to programmatically start or stop actually editing a contenteditable, like when the user focuses or blurs it? I tried .focus(), .click(), setting the selection to its content, but none of them seem to work.

EDIT: .focus() does work, just make sure the contenteditable node is already inserted to the document...

Community
  • 1
  • 1
thSoft
  • 21,755
  • 5
  • 88
  • 103

2 Answers2

5

You can use the trigger() method inside jQuery:

$('div[contenteditable="true"]').trigger('focus');

This will cause the caret to appear on page load, as per this jsFIddle demo.

BenM
  • 52,573
  • 26
  • 113
  • 168
  • Drat! Although I tried this, it didn't work because the contenteditable DOM node wasn't inserted into the DOM tree when I called .focus(). My bad. – thSoft Jan 24 '14 at 23:29
1

Maybe you are looking for disabled and readonly attributes.

HTML:
<input type="text" disabled="disabled" />

Javascript:
document.getElementsByTagName("div")[0].setAttribute("disabled", "disabled");

other option is

HTML:
<input type="text" readonly="readonly" />

Javascript:
document.getElementsByTagName("div")[0].setAttribute("readonly", "readonly");