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>
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.
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.
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.
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.
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>
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:
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.window.load
.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..load
can also be used on other elements.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With