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?
8. Which of the following element does not support autofocus attribute? <base> does not support autofocus attribute.
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 first input or textarea in source order that has the autofocus attribute will be focused on page load. In browsers without autofocus support, no fields will be focused on page load, unless otherwise given focus with JavaScript.
The autofocus attribute is a boolean attribute. When present, it specifies that an <input> element should automatically get focus when the page loads.
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>
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