Last Updated: November 19, 2020
·
33.32K
· barnettjw

Make CSS dropdown menus work on touch devices

CSS dropdown menus are pretty neat, but they usually depend on :hover, touch devices don't support hover states. So this bit of JQuery will allow you to, use clicks instead of hovers.

//Allow clicking instead of hover for dropdown menus
$(document).ready( function(){

    $('#submenu').click( function(event){
        event.stopPropagation();
        $('#drop').toggle();
    });

    $(document).click( function(){
        $('#drop').hide();
    });

});

This script assumes markup similar to this:

<a href="#" id = "submenu">Products</a>
        <ul id = "drop" >
            <li><a href="#">Widgets</a></li>
            <li><a href="#">Thingamabobs</a></li>
            <li><a href="#">Doohickies</a></li>
        </ul>

Related protips:

jQuery: When to use $(document).ready() and when $(window).load()

1 Response
Add your response

Thanks for the useful code. It's great that its in jQuery, and works in IE10 and IE11 touch. Do you have a version that works with menus that have several top-level headings with dropdowns? Perhaps using the jQuery ".this" keyword, and CSS classes would work?
--------- Follow Up ----------- I'm new to jQuery, so see if this will work reliably, or maybe there's a better way?

$(document).ready( function(){

$('.submenu').click( function(event){
    event.stopPropagation();
    $(".drop").hide();
    $(this).children("ul").toggle();
});

$(document).click( function(){        
    $('.drop').hide();
});

});

over 1 year ago ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside