PricingBlog

Hide component if clicked outside the component

  • gabosca01-1280642676567572480

    Gabriel Salazar

    1 year ago

    I have created a component that will perform the function of a dropdown, I want it to hide when the user clicks outside of it.
    1280642676861046804-image.png
    1280642677167362079-image.png
  • tomthebigtree-1280764727970234401

    Tom Ireland

    1 year ago

    Hey, Gabriel. You’d need to have a click event on a div behind the component so that when you click outside it hides it. It also means that you’d need to have it sit at a higher z-index and positioned absolute to sit on top of other page elements.

    That might be considered old school now and a bit faffy. You now have browser support for Popover API, which is worth checking out on MDN because you get that kind of stuff for free without adding extra complexity. Also, Andreas from the toddle team did a video on this on their YT channel.
  • tomthebigtree-1280765418759524424

    Tom Ireland

    1 year ago

    Also, I think for inputs, a simple solution might be to see the focus out or blur events. That’s probably the simplest solution.
  • tomthebigtree-1280765832447922258

    Tom Ireland

    1 year ago

    I think @Victor Giron has also done some work with custom dropdowns recently, so might be able to offer some advice on that.
  • gabosca01-1280878928428404758

    Gabriel Salazar

    1 year ago

    Thank you very much @Tom Ireland , @Victor Giron just helped me
    🙌1
  • tomthebigtree-1280880465087303690

    Tom Ireland

    1 year ago

    Do share the solution if you think it will help others. 🙂
    💪1