AnApprentice
AnApprentice

Reputation: 110960

jQuery Dropdown Plugin - Any supported plugins out there?

I'm looking for a dropdown plugin for jQuery as my app has multiple dropdowns. The functionality required is very similar to that of the StackOverflow profile caret.

I found this: http://davidwalsh.name/twitter-dropdown-jquery

But given that's not a plugin it feels very messy. Anyone know of a plugin that would allow me to DRY dropdowns on my site?

Thanks

Upvotes: 0

Views: 187

Answers (2)

Blender
Blender

Reputation: 298206

I cleaned up the code a bit and made it plugin-ish. Not very elegant (the code wasn't pretty to begin with), but it should work:

jQuery.fn.twitterMenu = function() {
    return this.each(function() {
        var dropdown = $(this);
        var menu = dropdown.next('div.dropdown-menu');
        var parent = dropdown.parent();

        var activeClass = 'dropdown-active';
        var showingDropdown = false;
        var showingDropdown, showingMenu, showingParent;

        dropdown.click(function(e) {
            e.stopPropagation();
            e.preventDefault();

            if (showingDropdown) {
                dropdown.removeClass(activeClass);
                showingMenu.hide();

                showingDropdown = false;
            } else {
                showingDropdown = true;
                showingMenu = menu;
                showingParent = parent;

                menu.show();
                dropdown.addClass(activeClass);
            }
        });

        $('body').click(function(e) {
            if (showingParent) {
                var parentElement = showingParent[0];

                if (!$.contains(parentElement, e.target) || !parentElement == e.target) {
                    hideMenu();
                }
            }
        });
    });
};

You use it like this:

$(document).ready(function() {
    $('.dropdown').twitterMenu();
});

Demo: http://jsfiddle.net/DraY4/9/

Upvotes: 1

Related Questions