Jquery dropdowns with touch support

Dropdowns with main button linkable on touch devices with the second touch

The Problem

If you want a dropdown where the main item open the dropdown and also have a link (to the category for example), clicking it on touch devices it goes to the link on touch, when instead you only want to show the dropdowns.

The Solution

Demo
Demo
Demo and source code

This simple Jquery code enables to have dropdowns with touch support on Ipad and Iphone and all other devices with touch events.

The Setup

In the menu just add the class .touchdropdown to a div that includes the Main Item and the Sub Items.

<div class="touchdropdown">
    <a href="javascript:alert('Main')">Main Item</a>
    <ul>
        <li><a href="javascript:alert('Sub')">Sub Item 0</a></li>
        <li><a href="javascript:alert('Sub')">Sub Item 1</a></li>
        <li><a href="javascript:alert('Sub')">Sub Item 2</a></li>
    </ul>
</div>

Then apply default styles for the menu.

/* menu styles */
ul {
    display:none;
}

The Javascript

You can copy/paste the following Javascript codes, just add custom code to the openMenu and closeMenu functions.

The first part detects touch devices adding the class touch to the html.

// detect touch
if("ontouchstart" in window
   || (navigator.maxTouchPoints > 0)
   || (navigator.msMaxTouchPoints > 0)){
        document.documentElement.className += " touch";
}

Then we have a code that counts the touches, it counts how many times the .touchdropdown has been touched, and stop the event depending on the number of touches.

// touch counters
$(".touch .touchdropdown").on('mouseenter', function(e){
    $(this).data("touch", 0);
});
$(".touch .touchdropdown").on('click', function(e){
    $(this).data("touch", $(this).data("touch") + 1);
    if($(this).data("touch") < 2){
        return false;
    }
});
$("html").on('click', function(e){
    $(".touch .touchdropdown").data("touch", 0);
});

We add the menu events, with also some code that closes the menu when clicking outside the menu.

// menu events
$(".touchdropdown").on('mouseenter', function(e){
    openMenu($(this));
});
$(".touchdropdown").on('mouseleave', function(e){
    closeMenu($(this));
});
$(".touchdropdown").on('click', function(e){
    // prevent html click event that closes menu
    if(e.stopPropagation){
        e.stopPropagation();
    }else{
        e.cancelBubble = true;
    }
});
$("html").on('click', function(e){
    // close menu when clicking outside
    closeMenu($(".touchdropdown"));
});

So now you can build your own behaviour with custom code inside the open and close functions.

// menu open/close
function openMenu(path){
    // replace and add custom behaviour
    path.find("ul").css("display", "block");
}
function closeMenu(path){
    // replace and add custom behaviour
    path.find("ul").css("display", "none");
}