JSFiddle - React, Tailwind, and code Playground
by Paul Leech
HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Menu Toggle</title>
<style>
.item-list { display: block; }
.show-list { display: none; }
</style>
</head>
<body>
<div class="main">
<header>
<div class="toggle"></div>
<ul class="item-list">
<li id="item-1">Item 1</li>
<li id="item-2">Item 2</li>
<li id="item-3">Item 3</li>
<li id="item-4">Item 4</li>
</ul>
</header>
</div>
</body>
</html>
JavaScript
// $('.toggle').on('click', function() {});
// is equivalent of $('.toggle').click(function() {});
$('.toggle').on('click', function() {
$('.item-list').toggleClass('show-list');
});
// Bind click event listener on the body
// Hide main menu if user clicks anywhere off of the menu itself.
$('body').on('click.hideMenu', function(e) {
// Check to see if the list is currently displayed.
if ($('.item-list').hasClass('show-list')) {
// If element clicked on is NOT one of the menu list items,
// hide the menu list.
if (!$(e.target).parent().hasClass('item-list')) {
$('.item-list').removeClass('show-list');
}
}
});