Sometimes, we want to give keyboard focus to a DIV and attach keyboard event handlers to it with JavaScript.
In this article, we’ll look at how to give keyboard focus to a DIV and attach keyboard event handlers to it with JavaScript.
How to give keyboard focus to a DIV and attach keyboard event handlers to it with JavaScript?
To give keyboard focus to a DIV and attach keyboard event handlers to it with JavaScript, we can set the contentEditable
property of the div to true
and call focus
on it.
For instance, we write
const div = document.getElementById("inner");
div.contentEditable = true;
div.focus();
to select the div with getElementById
.
Then we set its contentEditable
property to true
so we can type in the div.
Then we call focus
on it so we put the cursor on the div.
Conclusion
To give keyboard focus to a DIV and attach keyboard event handlers to it with JavaScript, we can set the contentEditable
property of the div to true
and call focus
on it.