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>
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>
Share
Improve this question
edited May 10, 2015 at 15:18
marsh
1,4411 gold badge13 silver badges19 bronze badges
asked May 10, 2015 at 14:19
TarlenTarlen
3,7958 gold badges35 silver badges60 bronze badges
3
- possible duplicate of Set cursor position on contentEditable <div> – marsh Commented May 10, 2015 at 14:22
- stackoverflow./a/14701053/2025923 Possible Duplicate – Tushar Commented May 10, 2015 at 14:22
- possible duplicate of Set focus on div contenteditable element – WiredPrairie Commented May 10, 2015 at 14:46
1 Answer
Reset to default 3I 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./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="content" contenteditable="true">sample input</div>
(fiddle: http://jsfiddle/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 thewindow.load
. There might be a few exceptions to that rule, read this and this to fully understand the workings of thewindow.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.)