Sometimes, we want to make a HTML5 datalist visible when focus event fires on input with JavaScript.
In this article, we’ll look at how to make a HTML5 datalist visible when focus event fires on input with JavaScript.
How to make a HTML5 datalist visible when focus event fires on input with JavaScript?
To make a HTML5 datalist visible when focus event fires on input with JavaScript, we can save the old input value on mouse move. On mouse down, we can empty the input value. And on mouse up, we set the input value to the saved input value.
For instance, we write:
<input name="input" list="input" />
<datalist id="input">
<option value="apple" selected></option>
<option value="orange"></option>
<option value="grape"></option>
</datalist>
to add an input and datalist associated with the input.
Then we write:
const input = document.querySelector('input')
let old;
input.onmousemove = (e) => {
e.target.focus()
old = e.target.value
}
input.onmousedown = (e) => {
e.target.value = ''
}
input.onmouseup = (e) => {
e.target.value = old
}
to select the input and define the old
variable to store the old value.
The we focus on the input and save the old value on mouse move with:
input.onmousemove = (e) => {
e.target.focus()
old = e.target.value
}
Then on mouse down, we empty the input value with:
input.onmousedown = (e) => {
e.target.value = ''
}
Then on mouse up, we set the input value to the saved old
value with:
input.onmouseup = (e) => {
e.target.value = old
}
Conclusion
To make a HTML5 datalist visible when focus event fires on input with JavaScript, we can save the old input value on mouse move. On mouse down, we can empty the input value. And on mouse up, we set the input value to the saved input value.