John Davidson

javascript - Make Search Box closes if user clicks anywhere?

0 comments
Message:


Currently, the search box opens and closes on clicking the font awesome search icon. But I want the search box closed when the user clicks anywhere inside the body...


My Code:




button.search-open {
position: absolute;
z-index: 999;
background-color: transparent;
border: none;
padding: 8px 20px;
font-size: 20px;
color: #fff;
top: 10px;
margin-left: 1225px;
border-radius: 4px;
cursor: pointer;
}


My Answer:
white;_ cursor: pointer;_}_input.search-box {_ display: none;_ position: absolute;_ top: 50%;_ left: 50%;_ transform: translate(-50%, -50%);_ padding: 10px;_ border: 1px solid #ccc;_ border-radius: 5px;_}_document.querySelector('.search-open').addEventListener('click', function() {_ document.querySelector('.search-box').style.display = 'block';_});_document.body.addEventListener('click', function(event) {_ if (!event.target.closest('.search-box') && !event.target.closest('.search-open')) {_ document.querySelector('.search-box').style.display = 'none';_ }_});_

In this code, we first select the search-open button and add an event listener to it. When the button is clicked, we display the search box by setting its display property to 'block'.

Then, we add a click event listener to the body element. In the event handler, we check if the click target is not inside the search box or the search-open button. If it's not, we hide the search box by setting its display property to 'none'. This way, the search box will close when the user clicks anywhere outside of it.

Rate this post

4 of 5 based on 6739 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us