I am trying to show the lists on page load if more than 768px but hide them if less and make them show on clicking the titles.
It works OK but not after resizing the window and I don't get why is this happening? Any advice?
How should I handle the bubbling properly?
HTML:
<nav>
<h3 class="nav__title">first</h3>
<div class="links">
<ul>
<li><a href="#">first one</a></li>
<li><a href="#">first two</a></li>
<li><a href="#">first three</a></li>
</ul>
</div>
</nav>
<nav>
<h3 class="nav__title">second</h3>
<div class="links">
<ul>
<li><a href="#">second one</a></li>
<li><a href="#">second two</a></li>
<li><a href="#">second three</a></li>
</ul>
</div>
</nav>
JS:
(function () {
function footerLinks() {
if ($(window).width() < 768) {
$(".links").hide();
$(".nav__title").on("click", function (e) {
e.preventDefault();
$(this).next(".links").toggle("fast");
});
} else {
$(".links").show();
}
}
footerLinks();
$(window).resize(function () {
footerLinks();
});
}());
I think this is what you want, you were adding up event handlers every time the window was resized:
(function () {
$(".nav__title").on("click", function (e) {
e.preventDefault();
// Drop out of function if window is big enough
if( $(window).width() >= 768 ){ return; }
$(this).next(".links").toggle("fast");
});
function footerLinks() {
if ($(window).width() < 768) {
$(".links").hide();
} else {
$(".links").show();
}
}
footerLinks();
$(window).resize(function () {
footerLinks();
});
}());