When I click into the search input, it works as desired.
But when I click into the search input again, it reverses the effect of the first click.
It should reverse the effect of the first click when I click outside the search input.
Here is my code:
function active() {
let body = document.body;
let inp = document.getElementById("inpt")
body.classList.toggle("bg")
inp.classList.toggle("iwidth")
}
input {
outline: none;
width: 150px;
padding: 2px;
}
.iwidth {
width: 300px;
}
.bg {
background: rgba(0, 0, 0, 0.8);
transition: 300ms;
}
<input type="search" name="" id="inpt" onclick="active()">
Instead of using toggle(), use add() and remove() so that when you click on the input element twice, the focus doesn't go off
Add this to your js code. If you clicked on any element which is not the input element, the classes are removed and it goes back to normal
document.addEventListener("click", function (e) {
if (e.target.id != "inpt") {
inactive();
}
})
Whole code:
function active() {
let body = document.body;
let inp = document.getElementById("inpt")
body.classList.add("bg")
inp.classList.add("iwidth")
}
function inactive() {
let body = document.body;
let inp = document.getElementById("inpt")
body.classList.remove("bg")
inp.classList.remove("iwidth")
}
document.addEventListener("click", function(e) {
if (e.target.id != "inpt") {
inactive();
}
})
input {
outline: none;
width: 150px;
padding: 2px;
}
.iwidth {
width: 300px;
}
.bg {
background: rgba(0, 0, 0, 0.8);
transition: 300ms;
}
<input type="search" name="" id="inpt" onclick="active()">
What you can do is:
<input type="search" name="" id="inpt" onfocus="active()" onblur="deactivate()">
You can use onfocus and on blur
function active() {
let body = document.body;
let inp = document.getElementById("inpt")
body.classList.toggle("bg")
inp.classList.toggle("iwidth")
}
input {
outline: none;
width: 150px;
padding: 2px;
}
.iwidth {
width: 300px;
}
.bg {
background: rgba(0, 0, 0,0.8);
transition: 300ms;
}
<input type="search" name="" id="inpt" onfocus="active()" onblur="alert('deactivate')">