Jquery dropdowns with touch support

The problem with having a clickable main item on a dropdown is that on touch devices it gets fired when you only want to show the dropdown.

See demo and code
Demo and code on jsfiddle.

Here is a very simple Jquery code that enables to have dropdowns with touch support on Ipad and Iphone and all other devices with touch events.

First add the class touchdropdown to the dropdown menu, with also the links and the unordered list with the submenu 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 just add this code to your Javascript scripts:


if("ontouchstart" in window

    || (navigator.maxTouchPoints > 0)

    || (navigator.msMaxTouchPoints > 0)){

    document.body.className += " touch";

}

$(".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;

    }

});

So now you can build your dropdown with mouseenter and mouseleave events:


$(".touchdropdown").on('mouseenter', function(e){

    $(this).find("ul").css("display", "block");

});

$(".touchdropdown").on('mouseleave', function(e){

    $(this).find("ul").css("display", "none");

});

The code above just counts how many clicks the .touchdropdown items had and fires the click event only if they have been already clicked one time already, implementing this way the dropdown with only touch clicks.

P. Iva +00 000 000 0000 English
Copyright © 2026 Riccardo Caroli