Reputation: 141
I change the css of a div at the moment of focus in an input. But i would like to cancel the value of the focus when i enter a letter in the input.
So how to render the initial css of my div when i enter a value in the input ?
I created a snippet for ease.
function setFocused() {
var results = document.querySelectorAll('.test');
for (result of results) {
result.classList.add('focused');
}
}
function unsetFocused() {
var results = document.querySelectorAll('.test');
for (result of results) {
result.classList.remove('focused');
}
}
var results = document.querySelectorAll('input[type="text"]');
for (result of results) {
result.addEventListener("focus", setFocused);
result.addEventListener("blur", unsetFocused);
}
.test.focused {
color: red;
}
<form>
<input type="text"/>
</form>
<div class="test">
Hello
</div>
Thanks for your help !
Upvotes: 0
Views: 52
Reputation: 9135
You can add a eventListener for the input (typing). On that function you can remove the classes.
I hope this will solve the issue. Please find the below code.
function setFocused() {
var results = document.querySelectorAll('.test');
for (result of results) {
result.classList.add('focused');
}
}
function unsetFocused() {
var results = document.querySelectorAll('.test');
for (result of results) {
result.classList.remove('focused');
}
}
function onChange(){
var results = document.querySelectorAll('.test');
result.classList.remove('test','focused');
}
var results = document.querySelectorAll('input[type="text"]');
for (result of results) {
result.addEventListener("focus", setFocused);
result.addEventListener("blur", unsetFocused);
result.addEventListener("input", onChange);
}
.test.focused {
color: red;
}
<form>
<input type="text"/>
</form>
<div class="test">
Hello
</div>
Upvotes: 1