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?
A lot of the time if you can't call
.focus()
on an element, it's because the tabIndex is -1, which means the tab key can't focus on it when you're pressing tab to navigate.Changing your tabIndex to >= 0 will let you focus on the elements. If you need to do it dynamically, you can just add a tabindex >= 0 to your element in the event listener.
You can try this code, it can auto focus in your last insert location.
Bind a "click" event handler to all elements within the contenteditable div, and change the class/style on click (i.e. add class "focused" to the element);
You can identify, to the user, which element has focus by adding style such as a colorful border or an inner box-shadow. Then when you want to access the focused element in your jQuery script, just do something like this:
var focused = $('.focused');
In case someone, who uses MediumEditor that manages
contenteditable
element, stumbles upon this issue, the following has worked for me:editor
is an instance ofMediumEditor
.editorDOMNode
is a reference to the actualcontenteditable
DOM node.It is also possible to focus on a specific child node within the editor as follows:
I noticed that jQuery focus() did not work for my contenteditable DIV with width and height of 0. I replaced it with .get(0).focus() - the native javascript focus method - and it works.
Old post but none of the solutions worked for me. I figured it out eventually though: