JSFiddle - React, Tailwind, and code Playground
by Allendar
HTML
<div class="menu">
<ul>
<li>
<span>Menu 1</span>
<ul>
<li>Submenu 1.1</li>
<li>
<span>Submenu 2.1</span>
<ul>
<li>Submenu 2.1.1</li>
<li>Submenu 2.1.2</li>
</ul>
</li>
</ul>
</li>
<li>
<span>Menu 2</span>
<ul>
<li>Submenu 2.1</li>
</ul>
</li>
</ul>
</div>
CSS
.menu {
border: 1px dotted blue;
}
.menu li {
width: 150px;
padding: 10px 5px;
display: inline;
}
.menu ul:hover {
cursor: pointer;
}
.menu ul ul {
display: none;
position: absolute;
}
JavaScript
$(document).ready(function() {
// Find each UL inside a `.menu` class
$('.menu').children('ul').each(function() {
// Find each LI child on this level
var items = $(this).children('li');
// If there are items in there
if (items.length > 0) {
for (var i = 0; i < items.length; i++) {
// Bind a working hover to show the submenu
$(items[i]).mouseover(function() {
// Change color
$(this).css('color', 'orange');
// Show first submenu's items if they exist
var sub_items = $(this).children('ul').children('li');
if (sub_items.length > 0) {
$(this).children('ul').each(function() {
$(this).css('display', 'block');
});
}
});
$(items[i]).mouseout(function() {
// Change color
$(this).css('color', 'black');
// Hide first submenu's items if they exist
var sub_items = $(this).children('ul').children('li');
if (sub_items.length > 0) {
$(this).children('ul').each(function() {
$(this).css('display', 'none');
});
}
});
}
}
});
});