My goal is to display a div whenever the input contains at least 1 character and hide it when the input is empty. Despite my efforts, I can't seem to make it work no matter what I try.
Here is my initial attempt:
var input = document.getElementById('search');
input.addEventListener('keypress', function(e) {
var searchHits = document.getElementById('search-hits');
if (e.keyCode >= 48 && e.keyCode <= 90) {
searchHits.style.display = 'block';
}
else if (e.keyCode === 8 && input.value === '') {
searchHits.style.display = 'none';
}
});
This approach fails because a backspace key press (keyCode 8) doesn't trigger as an actual keypress since it doesn't add a character to the input value.
Thinking logically, I came up with this solution:
var input = document.getElementById('search');
input.addEventListener('keypress', function(e) {
var searchHits = document.getElementById('search-hits');
if (input.value.length >= 0) {
searchHits.style.display = 'block';
}
else {
searchHits.style.display = 'none';
}
});
However, I encountered the same issue again where the backspace wasn't being registered as an actual keypress. I'm stuck on how to fix this for proper functionality. Any suggestions?
UPDATE: I even attempted changing the event from 'keypress' to keydown, keyup, input, and change without success.