2
\$\begingroup\$

I looked around for a script for popup menus in jQuery, but all i found were complex and largely-coded plugins.

I decided to write a small script myself:

$(document).on("click",".js_popup-trigger", function(e){
    e.preventDefault();

    //Set variables
    var element     = $(e.currentTarget).closest('.js_popup-trigger'),
        container   = element.parent('.js_popup-container'),
        menu        = element.next('.js_popup-menu');

    //Toggle the menu
    menu.fadeToggle(100);

    //Add the open classes to the container and trigger
    container.toggleClass('js_popup-container--open');
    element.toggleClass('js_popup-trigger--open');

    /*  Create a click listener for the document
    *   This is to close the menu if clicked outside of it */
    $(document).click(function closePopup(e){

        //If the clicked item is not in the popup, close it
        if(!$(e.target).closest(container[0]).length && element.is(":visible")){

            //Close the popup
            menu.fadeOut(100);

            //Remove the added classes
            container.removeClass('js_popup-container--open');
            element.removeClass('js_popup-trigger--open');

            //Unbind the closePopup function from the document
            $(document).unbind('click',closePopup);
        }
    });
});

This is working as it should at the moment, it simply allows you to create popup menus using the three classes in the script, one for the overall popup menu container, one for the trigger, and one for the menu items container.

When you click on the trigger, it opens the popup, and sets an event listener for a click event to the document which checks if the user clicked outside of the popup, which will close it if so.

Is this something that is efficient, if so then why the need for the large plugins? I assume those plugins have other functionalities and come with more styling options, effects, etc. But would a script like this be considered efficient?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.