I'm using the contenteditable
attribute on a <div>
in order to make it act as a text field on demand (for users to rename something). But I want to enable autofocus
on it as well, so users can begin typing immediately (the <div>
always has contenteditable
enabled initially).
Is this valid and/or possible? Or will I have to switch to a standard text input?
You'll have to do it with JavaScript in most browsers, I think. And it won't work on iOS, which only allows programmatic use of focus()
in an event handler of a genuine user interaction (such as a click
or touch-related event).
Also, be aware that if there other inputs on the page, it's possible the user may focus on one of those before the document has completely loaded, in which case it is then very annoying for the user to find that the focus has been moved from under them when the load
event does fire, so you should use the inputs' focus
events to track this.
<div contenteditable="true" id="editable"></div>
<script type="text/javascript">
window.onload = function() {
document.getElementById("editable").focus();
};
</script>