Ways to automatically close the search box when the user clicks anywhere within the body

What I desire At the moment, the search box opens and closes when the font awesome search icon is clicked. However, I also want the option for the search box to close if the user clicks anywhere within the body.

Screenshot

[

My Custom Code

<div id="searchbox">
    <form action="">
        <input type="text" name="q">
        <button type="submit"><i class="fa fa-search"></i></button>
    </form>
</div>
<i class="fa fa-search" onclick="closeSearch()"; ></i>

<script>
function closeSearch() {
  var x = document.getElementById("searchbox");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
</script>

Answer №1

In order to address the mentioned click event instead of focus, the implementation utilized a click event rather than a blur event.

var isSearchBoxVisible = false;
var searchBox = document.getElementById("searchbox");
var skipClose;

function toggleSearchBox() {
  showSearchBox(!isSearchBoxVisible);
  skipCloseFn();
}

function showSearchBox(show=true){
   searchBox.style.display = show ? '' : 'none'; 
   isSearchBoxVisible = show;
}

function skipCloseFn(){
  skipClose = true;
}

showSearchBox(false);

// This can be directly placed in HTML or for the outer search icon.
searchBox.querySelector('input').addEventListener('click', skipCloseFn);
// Add if necessary
searchBox.querySelector('button').addEventListener('click', function(e){
  e.preventDefault();
  skipCloseFn();
});


document.addEventListener('click', function(){
  if(!skipClose){
    showSearchBox(false);
  }
  skipClose = false;
});
<button><i class="fa fa-search" onclick="toggleSearchBox()">icon</i></button>
<br>
<br>
<div id="searchbox">
    <form action="">
        <input type="text" name="q">
        <button type="submit"><i class="fa fa-search">icon</i></button>
    </form>
</div>

Answer №2

Implement the onblur event on an input field.

<div id="searchbox">
        <form action="">
            <input type="text" onblur="closeSearch()" name="q">
            <button type="submit"><i class="fa fa-search"></i></button>
        </form>
    </div>
    <i class="fa fa-search" onclick="closeSearch()"; ></i>

Answer №3

If you're looking for a way to ensure that a click elsewhere on the page is required before closing, there's a simple solution.

<div id="searchbox">
    <form action="">
        <input type="text" name="q">
        <button type="submit><i class="fa fa-search"></i></button>
    </form>
</div>
<i class="fa fa-search" onclick="closeSearch()"; ></i>

<script>
function closeSearch() {
  var x = document.getElementById("searchbox");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

document.onclick = function closeSearch(e) {
  const searchbox = document.getElementById('searchbox');
  if (!searchbox.contains(e.target) {
    searchbox.style.display = 'none';
  }
}
</script>

Answer №4

function toggleSearch() {
  var searchBox = document.getElementById("searchbox");
  if (searchBox.style.display === "none") {
    searchBox.style.display = "block";
  } else {
    searchBox.style.display = "none";
  }
}
window.addEventListener('load',function(){
var searchInput = document.querySelector('input[name="q"]');
searchInput.addEventListener('blur',function(event){
document.getElementById("searchbox").style.display="none";
})

});
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet"/>
<div id="searchbox">
    <form action="">
        <input type="text" name="q">
        <button type="submit"><i class="fa fa-search"></i></button>
    </form>
</div>
<i class="fa fa-search" onclick="toggleSearch()" ></i>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

To open a popup menu with a text box, simply click on the text box

Whenever the text box text is clicked, a popup menu should open with a text box. Similarly, when the filter icon in the right side corner is clicked, a menu should open with a list of checkboxes. However, currently both menus are opening when clicking on b ...

Modifying Font Style in Angular 4 Material

Is there a way to change the font in Angular 4 Material material.angular.io using the styles file in .CSS format instead of SASS? While the documentation offers an example for SASS at: https://github.com/angular/material2/blob/master/guides/typography.md ...

Highlighting of Vue directives in HTML within WebStorm

Can the Vue attributes and directives be highlighted? Including those in quotes. https://i.sstatic.net/NOGn7.jpg ...

invoke a function through a form in Angular

I am encountering an issue with invoking a function from Angular. This particular function has a dual purpose - it uploads an image to S3 and saves the form data along with the URL of the image in the MongoDB database. Below is the HTML snippet where I cal ...

Deactivate a specific button within a row on a Primeng table by clicking on it

I'm trying to modify my primeng table so that each row has a button, and when I click on a button, only that specific button should be disabled. However, in my current code, all buttons are getting disabled with a single click. Can someone please help ...

Load images in advance using this script

Using a script to load images on two websites, the image is placed inside a div with the ID div-to-load-external-image Encountering an issue where PageSpeed Insights advises to preload these images, seeking guidance... Any assistance will be appreciated. ...

Is the H1 tag styled differently when located within an article element? Additionally, what is the best way to style multiple paragraphs within a

What is the best and most effective way to style multiple paragraphs within a div or semantic tag, each with different styles? Also, I have noticed that when I include an h1 tag inside the article, it does not display at the expected size. Does anyone know ...

Having trouble executing the yarn command for clasp login

Issue with running yarn clasp login I am not very proficient in English, so please bear with me. 8> yarn clasp login yarn run v1.22.22 $ C:\Users\myname\Desktop\個人開発プロジェクト\clasp-240418\node_modu ...

Vue.JS - Dynamically Displaying Property Values Based on Other Property and Concatenating with

I have a reusable component in Vue.js called DonutChart. <donut-chart :chartName="graphPrefix + 'PerformanceDay'" /> The value of the property graphPrefix is currently set to site1. It is used as part of the identifier for the div id ...

Guide to updating a database using ajax and javascript in asp.net mvc without the need to refresh the page

Is there a way to update the value of an enumdropdownlist from "active" to "inactive" in my database through an ajax call without having to refresh the page? I am unsure whether to use a javascript method or ajax.beginform for this task. I attempted to us ...

Discrepancy in functionality between Android and JavaScript Parse API

Using the open source version of Parse Server as a back end, my Android application saves objects to the server's DB in the form of key-value pairs encoded as JSON. However, when trying to retrieve the same object from an Ionic 2 app using the JS Pars ...

Anticipated a JavaScript module script, but the server returned a MIME type of text/html as well as text/css. No frameworks used, just pure JavaScript

I have been attempting to implement the color-calendar plugin by following their tutorial closely. I have replicated the code from both the DEMO and documentation, shown below: // js/calendar.js import Calendar from '../node_modules/color-calendar&ap ...

"Dilemma with Displaying a 3-Digit Number in DaisyUI Using Next.Js Countdown Component

Hey there, I'm encountering an issue with the countdown component on my Next.js website using daisyUI. When the number of days exceeds 99, it's not rendering correctly as shown below: https://i.sstatic.net/cWR2tSEg.png https://i.sstatic.net/V0Iv ...

"Creating a navigational bar using Bootstrap in a one-page application

I am facing an issue with Bootstrap's navbar in my single-page application. The dropdown navigation menu for mobile is not collapsing properly after clicking. Although I tried to fix it by adding data-toggle="collapse" data-target="#navbar" attributes ...

How can I incorporate checkboxes and crosses for validation in AngularJS?

I've been searching through the documentation for angularjs and online resources, but I can't seem to find any information regarding a specific aspect of form validation. You know when you input something in a form field (like a name, phone numbe ...

Can you locate the hiding spot of the express-session cookie?

After setting a very short cookie max-age (10 secs) in my express-session, I confirmed that it is working as expected: app.use(session({ secret: 'xxx', resave: false, saveUninitialized: true, cookie: { secure: true, maxAge: 10000 } })); ...

Steps for adding a favicon to Content-Type: application/json

In my implementation using node.js, I have an API that returns a response with Content-Type: application/json. Here is an example: module.exports={ api: (req, res) => { let data = {"data": [1, 2, 3]}; res.status(200).json(d ...

Steps for creating a fade effect between two different elements when the mouse is interacting with one of them

I want to create a unique effect with an image in the background and a button above it. When the mouse hovers over the button, I want its opacity to decrease while the image's opacity increases simultaneously. I have experience applying fade effects ...

The iPad Overlay fails to fully extend across the screen

I have implemented a modal div as an overlay to disable the background page while the overlay DIV is open. Below is the code I am using: #TB_overlay { height: 100%; left: 0; position: fixed; top: 0; width: 100%; z-index: 100; } Al ...

"Mastering the art of running a successful Dojo

As I delve into learning dojo, I encountered some peculiar syntax in a project on GitHub. dojo.declare('app.services.Favorites', [ dojo.store.Memory ], { constructor : function() { this.inherited(arguments); dojo.subscribe(& ...