Tutorial: Implementing Close-on-Background-Click for Custom Menus

Hey all! @greg on the Rarely Decaf team wrote up a tutorial for a functionality we’ve been using recently with our clients. I thought I’d share with the rest of the community here. (original post here)

I’m sure @greg would be happy to answer any questions.


This how-to guide aims to addresses a gap in WeWeb’s native features, providing a simple way to integrate close-on-background-click functionality to a conditionally displayed custom menu or modal-like element. By following the steps below, builders can add background click functionality quickly, simply and without JavaScript.

Use case
This trick will come in useful when you want to position a menu relative to a click event or a parent element instead of relative to the top and left side of the page.

Add the important elements
Begin by creating a container, that will hold three things. The button that will trigger the display of the menu, a div that we will call background and a final div to hold the menu elements. It’s important that the element are placed in the right order.

image

Styling and positioning
At this point it’s a good idea to add background colours to the background div and the menu so that you can see if they are displayed correctly in the following steps. You can update the styling later to suit your application.

Now for the important part, the positioning. We will start with the background. Set its position to fixed and set top, bottom, left and right to 0px. This will make the background cover the whole screen. Next find the menu container and set its position to Absolute. This will position the menu relative to the top left hand corner of it’s parent container. You’ll need to play around with the top, bottom, left and right positions to get the menu right where you want it.

image

Conditional display and Workflows
Next we need a boolean variable that will control the display of the background and menu. We will call it displayMenu and it will default to false. Once created, add an on-click workflow to the button that sets displayMenu to true when clicked. We can then set the conditional rendering properties of the background and the menu to the value of displayMenu.

With that, we are at the final step. We just need to add an on-click workflow to the background element. When clicked we will reset the showMenu variable which will hide the background and the menu. At this point everything should be working!

image

Testing and Troubleshooting:
If you are using z index on your page you might have a few elements peaking through the background. To solve this, increase the z index of the background until all the elements disappear. Then set the z index of the menu one step higher than the background.


3 Likes

Ooooh this is awesome! Thanks so much for taking the time to put this together and sharing it on here :hugs:

1 Like