Trying to create an expanding search bar that expands upon button click and collapses when clicking elsewhere on the page. The issue I'm facing is that everything works well initially, but after the second script hides the input field on a click outside it, the first script fails to trigger when I click the button again. I've tried various code variations without success, and I feel like I don't fully grasp how JavaScript functions in this case. Any help would be greatly appreciated. Check out the codepen link below for the code.
document.getElementById("searchButton").addEventListener("click", function(){
document.getElementById("userInputWindow").classList.toggle("userInputAnimationToggle");
});
document.addEventListener("click", function(event){
let i = document.getElementById("userInputWindow");
let k = document.getElementById("searchButton");
if(event.target !== i && event.target !== k)
{
document.getElementById("userInputWindow").classList.add("userInputAnimationToggle1");
}
if(event.target !== i){
document.getElementById("userInputWindow").value = "";
}
});
.searchBoxWrapper{
position: absolute;
margin: 40px auto;
text-align: center;
left: 50%;
}
button{
position:absolute;
width: 100px;
height: 100px;
margin-bottom: 5rem;
padding: 10px;
background-color: grey;
border: 2px solid orange;
border-radius: 100px;
font-size: 1rem;
transform: translate(-50%, 0);
z-index: 2;
}
.userInput{
position: absolute;
display: block;
width: 0;
padding: 15px;
border-radius: 40px;
background-color: grey;
border: 2px solid orange;
transform: translateY(50%);
left: 20px;
z-index: 1;
text-align:center;
transition: all 1s ease;
}
.userInput::placeholder{
font-size: 2rem;
}
.userInputAnimationToggle{
width: 150px;
display: block;
}
.userInputAnimationToggle1{
display: none;
}
<div class = "searchBoxWrapper">
<button class = "openSearchButton" id = "searchButton" type = "button" title = "Open Search window">Search</button>
<input class = "userInput" value="" type = "text" id = "userInputWindow" placeholder = " for item"/>
</div>
Link to Codepen: https://codepen.io/Mynickname/pen/jepzzX