Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set focus on div contenteditable element

I have a <div contenteditable=true> where I define by a WYSIWYG some elements. For example <p>,<h1>, etc. I would like to put directly the focus on one of this elements.

For example on <p id="p_test">. But it seems that focus() function doesn't work on <div> elements, <p> elements...

Is there a another means to define the focus in my case?

like image 289
sanceray3 Avatar asked Mar 05 '10 16:03

sanceray3


People also ask

How do you make a div Contenteditable?

Answer: Use the HTML5 contenteditable Attribute You can set the HTML5 contenteditable attribute with the value true (i.e. contentEditable="true" ) to make an element editable in HTML, such as <div> or <p> element.

What is false about Contenteditable attribute?

The contentEditable property of the HTMLElement interface specifies whether or not the element is editable. This enumerated attribute can have the following values: ' true ' indicates that the element is contenteditable . ' false ' indicates that the element cannot be edited.

How do you move the cursor to the end of Contenteditable entity?

moveToElementText(contentEditableElement);//Select the entire contents of the element with the range range. collapse(false);//collapse the range to the end point. false means collapse to end rather than the start range.

How do I get rid of Contenteditable border?

It is a default behavior of any element which have content-editable attributes set to true whenever, the element gets a focus it will get a border around them. The task can be done by using the [attribute] selector to select all elements that are contenteditable, and remove the border with the outline property.


1 Answers

Old post but none of the solutions worked for me. I figured it out eventually though:

var div = document.getElementById('contenteditablediv'); setTimeout(function() {     div.focus(); }, 0); 
like image 54
chris97ong Avatar answered Sep 18 '22 00:09

chris97ong