Marc Marc - 1 year ago 80
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:

The script:


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


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




Answer Source

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() {

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download