How to execute closed button when search form is open?

I have a basic Javascript to open and close my search form.

  $('.mysearchbutton').click(function()
   {
    $(this).parent().toggleClass('open');
   }
  );
 }

When users click outside search form (in other words they decide not to search) it should close a button. How to manage this as toggleClass(‘open’); should not be invoked.

I… am having a little trouble understanding what you’re asking, but i THINK what you’re searching for is the .removeClass() function.

Can you post the whole code when clicked outside search button?
I have set an example:

  $('.mysearchbutton').click(function()
   {
    $(this).parent().toggleClass('open');
    $("?").removeClass('open');
   }
  );

Sorry I think I get what you’re saying now.

I’m not sure what elements make up your search box, but basically, what i would do is instead bind a function to the blur event of all elements of your form, such that if none of your elements $("whatevertheelementis").is(":focus"), close the form.

I’m new to this. Please find HTML:

<div class="search">
  <input type="search" class="search-box" />
  <span class="search-button">
    <span class="search-icon"></span>
  </span>
</div>

Well, $('.mysearchbutton') isnt going to work because you dont have anything in your HTML that has the class “mysearchbutton”.

Essentially what you’d be looking to do is to say something like

$('.search-box').on('blur',function() {
   if(!$('.search-button').is(':focus')) {
      //The box has lost focus, but the span doesnt have it; so the focus went somewhere else...
      $(this).parent().removeClass('open');
  }
}

but without knowing which element you’re actually trying to remove classes from, s’gonna be hard to give you an exact answer.

I have done testing and the following code:

  $('.search-button').click(function()
   {
    $(this).parent().toggleClass('open');
   }
  );

  $('.search-button').on('blur', function()
   {
    if(!$('.search-button').is(':focus')) {
     $(this).parent().removeClass('open');
    }
   }
  )

Will this work as I tested and it will be detected parent but blur function will not be active?

Please find the whole source code if I missed focus attribute:
https://codepen.io/kristyjy/pen/zGOXYb

Well i dont know what kind of field search-box is, because type=‘search’ is not a normal html input type.

It’s probably something more like:

  $('.search-button').click(function()
   {
    $(this).parent().toggleClass('open');
   }
  );

  $('.search *').on('blur', function()
   {
    if(!$('.search-button').is(':focus') && !$('.search-box').is(':focus') && !$('.search-icon').is(':focus')) {
     $('.search').removeClass('open');
    }
   }
  )

Thank you for all messages!
I will try to test and enhance as it seem a different issue as I posted.

Can we use this script in our blog type website? My blog is on WordPress and I want to add this feature.