Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focus ContentEditable div

I want to focus the contenteditable div, so that I can automatically start typing when it is inserted into the DOM

I have tried $('.content').focus(), but this does not work

Example html:

<div class="content" contenteditable="true">sample input</div>
like image 371
Tarlen Avatar asked May 10 '15 14:05

Tarlen


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 does Contenteditable mean?

The contenteditable global attribute is an enumerated attribute indicating if the element should be editable by the user. If so, the browser modifies its widget to allow editing.

What is Contenteditable in CSS?

The contenteditable attribute specifies whether the content of an element is editable or not. Note: When the contenteditable attribute is not set on an element, the element will inherit it from its parent.

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

I think you probably just need to wrap your code in a window.load function:

$(window).on("load",function(){
  $('.content').focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="content" contenteditable="true">sample input</div>
(fiddle: http://jsfiddle.net/hxeqm541/)

What this does is, it waits until the page is fully loaded, before it executes the code inside the window.load.
If you don't do this, the code to focus on the div will be executed before the div even exists on the page, which is impossible. By the time the div finally does exist on the page, the code has already run, so nothing will happen anymore.


Side notes:

  • Because you reference the div by its class ($('.content')), if you have more than one of these divs with the same class-name, only the last one will receive focus. See example.
  • You DO NOT NEED to wrap every individual code block in an window.load.
    Usually, you can wrap your ENTIRE JavaScript code in the window.load. There might be a few exceptions to that rule, read this and this to fully understand the workings of the window.load mechanism so you'll know exactly how to use it.
    (Notice in the second link that .load can also be used on other elements.)
like image 194
myfunkyside Avatar answered Oct 04 '22 07:10

myfunkyside