Wednesday 11 December 2013

Bootstrap Dropdown Mega Menu

Update: Just use this plugin https://github.com/CWSpear/bootstrap-hover-dropdown. It's most likely better tested than this hastily put together script.

I would just like to point out that I agree with the Twitter Bootstrap dev's, in that you should not be having the megamenu display on hover. That's paraphrasing their words but seems to be their general intent.

Now that that's out of the way, if you do want a Mega Menu that works on desktop and tablets, here is some code that may be of assistance. I'm pretty curious about it's behaviour on touch screen PCs, but as we don't have any to test with I can't check it :(

var topLevelLinks = jQuery('.dropdown-toggle');  // We're using bootstrap for the dropdown, but we need it to display on hover
    if (!Modernizr.touch) {
        // pseudo hover stuff
        topLevelLinks.on('mouseover', function(event) {
            topLevelLinks.removeClass('disabled');
            jQuery(this).dropdown('toggle').addClass('disabled');
        });
        // pseduo off hover
        jQuery('#menu-main-menu').on('mouseout', function() {
            jQuery('.dropdown-toggle.disabled').removeClass('disabled').dropdown('toggle');
        });
    }
    topLevelLinks.on('click', function(event) {
        if (jQuery(this).parent().hasClass('open')) {
            // stop the dropdown stuff and let the normal link stuff happen
            event.stopPropagation();
        }
    });