Thanks @pptgames ! I looked everywhere on the web, and did not find any real solution, except this. I wouldn’t have solved this problem without the smooth trick of focus() and onBlur() functions you posted here.
To spread the happiness, I am posting here my version of the requirement and its solution (code as it is).
Requirement :-
To create a custom menu in the header (with buttons like “Home”, “About Us”, “Products”, “Services”, “Contact Us”).
If the “Products” button is clicked, then instead of a plain drop down list, a box showing the images of products appears.
And then if I click anywhere outside the box (including the “Products” button), the box disappears.
My adaptation of this solution :-
“Products” button is “#productsMenuButton”.
The box to be displayed is “#productsMenuBox”.
The helper element that supports the focus() / onBlur() functions is “#ghost”.
Global variables required.
let isFreshClick = true; // to differentiate if the button click is meant to show the products box or hide it.
let isOutsideProductsMenu = true; // to determine if the mouse was clicked outside the products box.
let isOutsideProductsMenuButton = true; // to determine if the mouse was clicked outside the products button.
The onClick() function that fires whenever the “Products” button is clicked.
export function productsMenuButton_onClick(event)
{
if(isFreshClick) // a fresh click is one where the box is already hidden before the click is made
{
$w('#productsMenuBox').show();
$w('#ghost').focus(); // arm the onBlur() function.
isFreshClick = false; // the box will not appear again until a fresh click is made.
}
else
isFreshClick = true; // since the button lies outside the box and the click was not a fresh one, the onBlur() function hides the box. Now the next click on the button will be a fresh one.
}
The onBlur() function that allows hiding back the box as per the position where the mouse is clicked.
export function ghost_onBlur(event)
{
if(isOutsideProductsMenu)
{
$w('#productsMenuBox').hide(); // hide the box as the click was outside the box.
if(isOutsideProductsMenuButton)
isFreshClick = true; // the next click can be fresh only when the click is outside the button.
}
else
$w('#ghost').focus(); // rearm the onBlur() function to allow the box to be hidden when an appropriate click is made in the future.
}
These mouse() functions are fired automatically whenever mouse is moved in or out the box
export function productsMenuBox_mouseIn(event)
{
isOutsideProductsMenu = false;
}
export function productsMenuBox_mouseOut(event)
{
isOutsideProductsMenu = true;
}
These mouse() functions are fired automatically whenever mouse is moved in or out the button
export function productsMenuButton_mouseIn(event)
{
isOutsideProductsMenuButton = false;
}
export function productsMenuButton_mouseOut(event)
{
isOutsideProductsMenuButton = true;
}