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()">
The thing i want to do is;
When I click to search input it works as I want, but when I click search input again it goes back to normal.
I don’t want it like this. I want it to go normal when I click outside not to search input.
I don't have much knowledge of javascript. Also don't know which code I should write. Can u guys help me?
CodePudding user response:
What you can do is:
<input type="search" name="" id="inpt" onfocus="active()" onblur="deactivate()">
CodePudding user response:
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()">
CodePudding user response:
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')">
CodePudding user response:
<input type="search" name="" id="inpt" onblur="blurF()" onfocus="focusF()">
// Lose focus
function blurF() {
let body = document.body;
let inp = document.getElementById("inpt")
body.classList.remove("bg")
inp.classList.remove("iwidth")
}
// Get focus
function focusF() {
let body = document.body;
let inp = document.getElementById("inpt")
body.classList.add("bg")
inp.classList.add("iwidth")
}