Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript onClick for mobile devices

I am working on a submenu for a nav that I need to be accessible for mobile and tablet devices. I am aware that using onClick="return true" will do the trick, however, I also need my list item to close when the user clicks on the list item. Basically I need it to toggle the submenu. If I add this simple line of Javascript, it will work but the submenu will always remain open. How can I get it to close/toggle the submenu?

HTML:
        <nav>
            <ul>
                <li class="active"><a href="#">Menu 1</a></li>
                <li><a href="#">Menu 2</a></li>
                <li><a href="#">Menu 3</a></li>
                <li class="bg"><a class="dropdown" href="#">Menu 4</a>
                    <ul>
                        <li><a href="#">Sub 1</a></li>
                        <li><a href="#">Sub 2</a></li>
                    </ul>
                </li>
            </ul>
        </nav>

Javascript:
$('nav li.bg').on('click', function(){
  return true;
}
like image 670
dev_levity Avatar asked May 21 '26 15:05

dev_levity


1 Answers

You can use touchstart event which fires on mobile browsers.

$('nav li.bg').on('click touchstart', function(){
    return true;
});

More touch based events

like image 81
Amit Joki Avatar answered May 23 '26 03:05

Amit Joki