I have the following code that hides a div when there is anything typed in a textbox.
<script type="text/javascript" charset="utf-8">
$('#email').change(function () {
var len = $('#email').val().length;
if (len > 0) {
$("#user_accounts").fadeOut(1)
} else {
$("#user_accounts").fadeIn(1)
}
});
</script>
This is working but it only works after you click away from the textbox and not when you start typing. I wanted to see if there is a way to execute this code when you start typing and not just when there is text in the field and you click away.
It's quite easy, here's the code:
document.getElementById('myInput').addEventListener('keyup', () => {
if (document.getElementById('myInput').value.length > 0) {
document.getElementById('myDiv').style.display = 'none';
} else {
document.getElementById('myDiv').style.display = 'block';
}
})
#myInput {
width: 200px;
height: 35px;
padding: 0 10px;
background: #333;
color: #fff;
border: 0;
outline: 0;
font-family: arial;
}
#myInput::placeholder {
color: #ccc;
}
#myDiv {
width: 220px;
height: 70px;
margin-top: 20px;
line-height: 70px;
text-align: center;
font-family: arial;
background: red;
color: #fff;
}
<html>
<body>
<input id='myInput' type="text" placeholder="Type here!">
<div id='myDiv'>Can you see me?</div>
</body>
</html>
Basically using
document.getElementById('myInput').addEventListener('keyup', () => { // your function }
you're calling a function everytime someone types inside the input (actually the function is called only when you realese a key) and then you just check for the input's value length inside of the function and hide or not the div based on the length.
Hope It's what you're looking for, if you have any question let me know.
According to the documentation, for <input type="text">, the change event only triggers after the element loses its focus (e.g. clicking away).
Unlike change event, input event is fired every time the value of the element changes. Therefore, it fits better to your usecase.
Your code will look like this:
$('#email').on('input', function() {
var len = $('#email').val().length;
if (len > 0) {
$("#user_accounts").fadeOut(1)
} else {
$("#user_accounts").fadeIn(1)
}
});
for cleaner code, I would recommend using inline HTML and instead of onchange, I would actually use onkeyup (as other commentators noted) this event would call a named function which would be binded to the event.
as follows:
<element onkeyup="handleInputKeyup">...</element>
const handleInputKeyup = (event) => {//do something with the event here};