Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use autofocus on an element with contenteditable?

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?

like image 388
daGUY Avatar asked Jul 13 '12 17:07

daGUY


People also ask

Which element does not support autofocus attribute?

8. Which of the following element does not support autofocus attribute? <base> does not support autofocus attribute.

What is the global attribute Contenteditable used for?

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.

Does autofocus attribute always set focus on first input field in html5?

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.

How does input element gets automatically focused when the page loads?

The autofocus attribute is a boolean attribute. When present, it specifies that an <input> element should automatically get focus when the page loads.


1 Answers

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>
like image 196
Tim Down Avatar answered Sep 19 '22 19:09

Tim Down