Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
jquery based simple nested navigation
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.d-none {
display: none;
}
</style>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
</head>
<body>
<ul id="main">
<li><a data-mid="m1">m1 (sub menu)</a></li>
<li><a data-mid="m2">m2 (sub menu)</a></li>
<li><a data-mid="m3">m3 (sub menu)</a></li>
</ul>
<ul id="m1" class="d-none">
<li><a class="menu-back-link">back</a></li>
<li><a data-mid="m1a">m1a (sub menu)</a></li>
<li><a data-mid="m1b">m1b (sub menu)</a></li>
<li><a data-mid="m1c">m1c (sub menu)</a></li>
</ul>
<ul id="m1a" class="d-none">
<li><a class="menu-back-link">back</a></li>
<li>m1a n/a</li>
<li>m1a n/a</li>
<li>m1a n/a</li>
</ul>
<ul id="m1b" class="d-none">
<li><a class="menu-back-link">back</a></li>
<li>m1b n/a</li>
<li>m1b n/a</li>
<li>m1b n/a</li>
</ul>
<ul id="m1c" class="d-none">
<li><a class="menu-back-link">back</a></li>
<li>m1c n/a</li>
<li>m1c n/a</li>
<li>m1c n/a</li>
</ul>
<ul id="m2" class="d-none">
<li><a class="menu-back-link">back</a></li>
<li><a>m2 a</a></li>
<li><a>m2 b</a></li>
<li><a>m2 c</a></li>
</ul>
<ul id="m3" class="d-none">
<li><a class="menu-back-link">back</a></li>
<li><a>m3 a</a></li>
<li><a>m3 b</a></li>
<li><a>m3 c</a></li>
</ul>
<script>
var target = null;
var nav = ['main'];
$(function () {
$('a[data-mid]').click(function () {
target = $(this).data('mid');
if (target) {
const ele = $(`#${target}`);
if (ele) {
ele.css('display', 'block');
nav.push(target);
if (nav.length > 1) {
$(`#${nav[nav.length - 2]}`).css('display', 'none');
}
}
}
})
$('.menu-back-link').click(function () {
if (nav.length > 1) {
target = nav.pop();
$(`#${target}`).css('display', 'none')
// alert(`#${nav.length - 1}`)
$(`#${nav[nav.length - 1]}`).css('display', 'block')
} else {
target = nav[0]
$(`#${target}`).css('display', 'block')
}
});
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment