Skip to content

Instantly share code, notes, and snippets.

@petehalverson
Created May 22, 2013 21:03
Show Gist options
  • Save petehalverson/5630894 to your computer and use it in GitHub Desktop.
Save petehalverson/5630894 to your computer and use it in GitHub Desktop.
JS for touch subnav. Requires: Modernizr (expects the touch class) and hover classes in CSS.
$(function() {
if ($('html').hasClass('touch'))
{
$('html').click(function(e) {
$('nav > ul > li').removeClass('hover');
});
$('nav > ul > li').click(function(e) {
if (!$(this).hasClass('hover') && $(this).has('ul.subnav').length > 0)
{
e.preventDefault();
e.stopPropagation();
}
$('nav > ul > li').removeClass('hover');
$(this).toggleClass('hover');
});
}
});
@jeremymouton
Copy link

Alternatively, using Bootstrap's dropdown menus, you may want to disable to the forced click on Desktops when using data-toggle="dropdown".

Still using Modernizr:

// Disable data-toggle on dropdown
if (!$('html').hasClass('touch'))
{
    $('.nav a').click( function(e) {
        $(this).removeAttr('data-toggle');
    });
}

@jeremymouton
Copy link

For Bootstrap:

if ($('html').hasClass('touch'))
{
    $('html').click(function(e) {
        $('.navbar-nav > li').removeClass('hover');
    });

    $('.navbar-nav > li').click(function(e) {

        if (!$(this).hasClass('hover') && $(this).has('ul.dropdown-menu').length > 0)
        {
            e.preventDefault();
            e.stopPropagation();
        }

        $('.navbar-nav > li').removeClass('hover');
        $(this).toggleClass('hover');
    });
}

@jeremymouton
Copy link

Load Fastclick (https://github.com/ftlabs/fastclick) for this script to work in iOS8.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment