Marc Marc - 6 months ago 15
Javascript Question

Onepage navigation script needs to troggle / close on click on link

I have an onepage site with a responsive navigation script. Works great.
When you click on the Navigation button the "subnav" links show up. (These are anchors).

I need to toggle/close the subnav when clicking on a link/anchor.

Made an example here:
https://jsfiddle.net/fourroses666/jcj0kph2/

The script:

$(document).ready(function(){

$('nav').prepend('<div class="responsive-nav" style="display:none">Navigation</div>');
$('.responsive-nav').on('click',function(){
$('nav ul').slideToggle()
});

$(window).resize(function(){

if ($(window).innerWidth() < 768) {
$('nav ul li').css('display','block');
$('nav ul').hide()
$('.responsive-nav').show()
} else {
$('nav ul li').css('display','inline-block');
$('nav ul').show()
$('.responsive-nav').hide()
}

});

$(window).resize();

});

Answer

You may tidy up your code a bit by doing the prepend and attaching the click handler all in one statement as below.

var $nav = $('#nav').
    prepend('<div class="responsive-nav" style="display:none">Navigation</div>').
    on('click', '.responsive-nav, ul a', function() {
      $nav.find('ul').slideToggle()
    });

Updated fiddle

Note: I used $nav.find('ul') to target the specific nav in question as opposed to other navs that may exist on the page.