Reputation: 11
I am trying to hide a container when the search bar is clicked but the page reloads and the container is shown again.
the code is below
<div class="search">
<form action="" method="GET">
<input type="text" name="search" value="" placeholder="search member..">
<button class="search_btn">
<i class="fas fa-search" style="font-size: 18px;"></i>
</button>
</form>
</div>
the javascript for adding the class of hide
const search_btn=document.querySelector(".search_btn");
const content=document.querySelector(".content");
search_btn.addEventListener("click", search);
let se=false;
function search(){
if(!se){
content.classList.add("hide");
se=true;
}else{
content.classList.remove("hide");
se=false;
}
}
and the css part of itis as below
.container .content.hide{
display:none;
}
.container .content{
display: block;
margin: 20px;
background: #f2f5f9;
}
Upvotes: 0
Views: 583
Reputation: 972
The page is reloading becase your code contains form and when you are clicking on the search you are actually submit the form. You can use event.preventDefault() for prevent it.
function search(event){
if(!se){
content.classList.add("hide");
se=true;
}else{
content.classList.remove("hide");
se=false;
}
event.preventDefault()
}
Upvotes: 1