Reputation: 33
I'm trying to make it so that when a user hovers over an input element, it automatically focuses and they can type in it. It doesn't give me any errors in the console, but neither does it work.
Here is my code:
var field1 = document.getElementById("code")
const field1hover = function() {
field1.focus()
}
field1.addEventListener("mouseenter", field1hover)
var field2 = document.getElementById("encoded")
const field2hover = function() {
field2.focus()
}
field2.addEventListener("mouseenter", field2hover)
<input id="code">
<input id="encoded">
--------------update---------
It just started working, I don't know why.
Upvotes: 0
Views: 431
Reputation: 10672
So this creates a different UI experience that's certainly not "normal" but I'll ignore that and pretend you have a good use case here. I would simply do it like this, a small refactor so you can clean your code up a bit:
const inputHovered = function() {
this.focus()
}
var field1 = document.getElementById("code")
field1.addEventListener("mouseenter", inputHovered)
var field2 = document.getElementById("encoded")
field2.addEventListener("mouseenter", inputHovered)
<input type="text" id="code" />
<input type="text" id="encoded" />
We can take it a step further if you want this to happen for all of your inputs by just querying for all of your inputs and looping through them to add this listener to all of them. Don't forget to clean up your event listeners to prevent a memory leak.
Also don't forget to make sure you're keeping this accessible for users who do not use a mouse.
Upvotes: 2