Friday, May 31, 2013

Javascript to Auto hide Primefaces Megamenu on mouseout

The other day I had a request from a customer to auto hide the Primefaces Megamenu when the user navigates away from the menu. This is the javascript that I quickly put together to handle that request.

Its not perfect, but it works. Feel free to modify as you wish. I am sure this could be modified to handle the menubar component as well.

setMegaMenuTimeout("#menu-form\\:main-menu",2000); //Call to method with menu component id


function setMegaMenuTimeout(menuId,mSeconds)
{
    var menuTimer = null;
    
    var parentMenuItems = $(menuId).find('.ui-menu-parent');
    
    parentMenuItems.each(function()
    {
        var dropDown = $(this).children("ul").eq(0);

        dropDown.mouseout(function()
        {
            menuTimer = window.setTimeout(function()
            {
                closeMegaMenu(menuId);
            },mSeconds);
        });
        
        dropDown.mouseover(function()
        {
            if(menuTimer !== null){window.clearTimeout(menuTimer);}
        });
    });
    
    $(document).on('mouseover',menuId,function(e){if(menuTimer !== null){window.clearTimeout(menuTimer);}});
}

function closeMegaMenu(menuId)
{
    var parentMenuItem = $(menuId).find(".ui-menu-parent.ui-menuitem-active");
            
    parentMenuItem.each(function()
    {
        $(this).children("ul").eq(0).hide('slow');
        
        $(this).removeClass("ui-menuitem-active");

        $(this).children("a").eq(0).removeClass("ui-state-hover");
    });
}

No comments:

Post a Comment