JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>
<a href="stackoverflow.com">maincat1</a>
<ul>
<li>
<a href="stackoverflow.com">subcat1.1</a>
<ul>
<li>
subcat1.1.1
</li>
<li>
subcat1.1.2
</li>
</ul>
</li>
</ul>
</li>
<li>
<a href="stackoverflow.com"> maincat2</a>
<ul>
<li>
subcat2.1
</li>
<li>
subcat2.2
</li>
<li>
subcat2.3
<ul>
<li>
subcat2.3.1
</li>
<li>
subcat2.3.2
</li>
</ul>
</li>
</ul>
</li>
</ul>
CSS
li > ul {
display:none;
}
li:hover > ul {
display:block;
}
.active > ul >li{
display:block;
}
JavaScript
$(document).ready(function(){
window.USER_IS_TOUCHING = false;
window.addEventListener('touchstart', function onFirstTouch() {
window.USER_IS_TOUCHING = true;
// we only need to know once that a human touched the screen, so we can stop listening now
window.removeEventListener('touchstart', onFirstTouch, false);
}, false);
function is_touch_device() {
return 'ontouchstart' in window // works on most browsers
|| navigator.maxTouchPoints; // works on IE10/11 and Surface
};
$('ul > li > a').click(function(e){
var target = $(e.target);
var parent = target.parent(); // the li
if(is_touch_device() || window.USER_IS_TOUCHING){
if(target.hasClass("active")){
//run default action of the link
}
else{
e.preventDefault();
//remove class active from all links
$('ul > li > a.active').removeClass('active');
//set class active to current link
target.addClass("active");
parent.addClass("active");
}
}
});
$('ul > li').click(function(e){
//remove class active from all links if li was clicked
if (e.target == this){
$(".active").removeClass('active');
}
});
});