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){

    //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

    //Add the open classes to the container and trigger

    /*  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

            //Remove the added classes

            //Unbind the closePopup function from the document

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?


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.