I'm trying to make a div appear whenever the input contains at least 1 character and hide it whenever the input is empty. However, I just can't get it to work no matter what I do.
Here is my first 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 doesn't work because a backspace (keyCode 8) key press doesn't actually count as a keypress since it doesn't add a character to the input value.
So then I figured that this solution should work:
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';
}
});
But yet again I get the same problem with the backspace not being registred as an actual keypress.. I have no idea how to fix this so that it's working properly. Any ideas?
EDIT: I have also tried changing the 'keypress' to keydown, keyup, input and change. None of them work.