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.)