How to revert a toggle variant back to its base version, when clicked anywhere else on the screen.

As the title says. How to revert a toggle variant, that opens on click event, back to its base variant when the user clicks anywhere else on the screen.

Like a side bar menu that opens onclick event as a toggle variant, but gets back to hidden state when the user clicks on another option or any blank space.

Any idea or advice is much appreciated.

Hi, great question. Because these are usually a little bit tricky to create yourself, you can also consider using one of the built-in components. For instance, inside the anti design system there is a Drawer component that already has all the right behavior built in.

If you want to create this yourself, it sounds like you already have something, but what you also need is a transparent box such as an empty vertical sack that covers the rest of the page that isn’t covered by the drawer. And then you need to add an on-click handler to that box which toggles the variant. This is usually how these are implemented. Let me know if that makes sense!

1 Like

Thanks for the advice. I do understand what that empty vertical stack can do in a situation like this

But i think i should better rephrase my question here.

How to revert a toggle variant, like this
Screenshot (33)
back to its base variant, like this
Screenshot (31)
when the user clicks or touches anywhere else on the screen, rather than the user having to click the red close sign in the toggle variant. I was thinking if there’s a javascript solution to this, but then i couldn’t figure out how to register when the user clicks anywhere else on the screen that will update the state variant of this component.

For something like that you will need to write custom code in order to handle this.

Assuming this was its own component, you can do the following

  1. Insert this component into your page
  2. Define a state variable on the page called open, of type boolean, with default value false
  3. Select the instance of the component you inserted and set the variant to a dynamic value based on the open state.
  4. Add an onclick handler to the page that sets open to false, But only when $‘.container *’)
  5. Make sure your instance is inside of a container with class “container”
1 Like