Reputation: 11
I'm creating my first one-page project, so I want to be able to scroll around easily.
HTML:
<nav>
<ul>
<li><a href="#top">Top</a></li>
<li><a href="#middle">Middle</a></li>
<li><a href="#bottom">Bottom</a></li>
</ul>
<span id="hamburger">Hamburger Icon</span>
</nav>
JQuery:
$("#hamburger").on("click", function() {
$("nav ul li").toggleSlide("normal");
});
//Snipet code from CSS-Tricks
$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
//Added code
if($('nav ul').is(':visible')) {
$('nav').slideToggle("fast");
}
//End added code
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top
}, 700);
return false;
}
}
});
});
I'm stuck at mobile-first template. Basically, when I click on the Hamburger Icon, the menu appears as "blocks". When I choose an anchor point, it should close the menu and scroll to the anchor. Things seem simple, yet it doesn't work well as I thought. When I click the anchor point, the menu disappears and scrolls to my destined point very well. However, now the menu can't be opened again, no matter how I click on the "Hamburger icon".
Btw, I'm just start using JQuery, so I hope to see a clear instruction. Thanks.
Upvotes: 0
Views: 66
Reputation: 9055
Use slideToggle for both of your animations. I would also just animate the nav ul
Instead of the nav ul li
that way your are just animating one item instead of multiple items for no reason. So in your css change the nav ul
to display:none
instead of the nav ul li
. Also there is probably no reason to check if nav ul
is visible because no matter what you are going to be scrolling to a section if a link in your menu is clicked. So that being said you could just use the following code:
Here is a working Fiddle Fiddle Demo
$("#hamburger").on("click", function() {
$("nav ul").slideToggle("normal");
});
//Snipet code from CSS-Tricks
$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
//Added code
$('nav ul').slideToggle("fast");
//End added code
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top
}, 700);
return false;
}
}
});
});
Upvotes: 1