skip to Main Content

I am trying to show a search box when you click the search icon in WordPress. The issue I am having is I want it to hide if you click anyplace else on the site.

Currently this is the code I am using and it works if you click the icon on and off but i want lost focus click also.

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

The other script I was trying to use is this but it doesn’t seem to have any effect.

<script>
    document.addEventListener('click', function handleClickOutsideBox(event) {
        const box = document.getElementById('myDIV');
        if (window.getComputedStyle(x).visibility === "visible") {
            x.style.visibility = "hidden";
        }
    });
</script>

Any help would be great thank you.

The second part of my code

<script>
  document.addEventListener('click', function handleClickOutsideBox(event) {
      const box = document.getElementById('myDIV');

      if (window.getComputedStyle(x).visibility === "visible") {
          x.style.visibility = "hidden";
      }
  });
</script>

I thought this would hide it if it saw it was visible but it isn’t working.

2

Answers


  1. Try Changing ‘visibility’ to ‘display’ in your second and third code pieces.

    because you’re controlling your search inputs’ visibility using ‘display’ attribute in the first piece so the ‘visibility’ is quite meaningless.

    Login or Signup to reply.
  2. You can do it like this:

    function toggle() {
      document.querySelector("input").classList.toggle("hidden");  
    }
    document.querySelector("input").addEventListener("blur", (e) => {
      toggle();
    });
    document.querySelector("button").addEventListener("click", (e) => {
      toggle();
    });
    .hidden {
      display: none;
      visibility: hidden;
    }
    <button id="test">Open
    </button>
    <input name="search" class="hidden" placeholder="Enter search here"/>

    Setting both display and visibility as I’ve shown here is overkill. You only need one of them (they do slightly different things in this context)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search