/    Sign up×
Community /Pin to ProfileBookmark

Need help with JavaScript

Hi , This is a long one . But I have a nav bar that slide and I want to make it close after I click on a links that takes me to a section of the page.
so far I had this code that someone actually give it to me

[code]
// Handle close bar
const closeNavbar = () => {
$(‘.nav-links’).removeClass(‘nav-activ’)
}

// Toggle hamburger animation
const toggleHamburgerBtn = () => {
$(“.burger”).toggleClass(‘animation’)
}

// Handle change link
const changeLink = () => {
$(‘.nav-links a’).on(‘click’, () => {
closeNavbar()
toggleHamburgerBtn()
})
}[/code]

But I this uses jQuery so I tried to write the same thing in javaScript. And as I am new to coding it took me a while and some variations of the code to make it work. At least kinda make it work.
The code that I managed to make it work with this this on

[code]const closeNav = () => {
const navLinks = document.querySelector(‘.nav-links’);
navLinks.classList.remove(‘nav-active’);
}
const closeBurger = () => {
const burger = document.querySelector(‘.burger’);
burger.classList.remove(‘animation’);
}

const closeSlide = () => {
const links = document.querySelector(‘.nav-links a’);

links.addEventListener(‘click’, () => {
closeNav();
closeBurger();
})
}

closeSlide();[/code]

The problem with this on is that only work for the first a tag, no for all . I think I need to an an .forEach I dont exactly know how but I have an idea.
I think it shoud be something along the lines

[code]links.forEatch(a => {
a.addEventListener(‘click’, () => (
closeNav();
closeBurger();
))})[/code]

But the main question is why this code doesn’t work ? I tried to reduce the code as much as I could.

[code]const navSlide = () => {
const burger = document.querySelector(‘.burger’);
const navLinks = document.querySelector(‘.nav-links’);
const links = document.querySelector(‘nav-links a’);

burger.addEventListener(‘click’, () => {
navLinks.classList.toggle(‘nav-active’);
burger.classList.toggle(‘animation’);

links.addEventListener(‘click’, () => {
navLinks.classList.remove(‘nav-active’);
burger.classList.remove(‘animation’);

})
});

}

navSlide();[/code]

This function is the function that makes the nav slide.

to post a comment
JavaScript

9 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumJun 15.2019 — With forEach you were on the right track already. Note that document.querySelector will return only the first element that matches. You need to use document.querySelector[b]All[/b] in order to get all. Then you can loop through the elements by use of forEach.
Copy linkTweet thisAlerts:
@codyhillauthorJun 15.2019 — @Sempervivum#1604786 Aha ! That makes sens . But why the last code does not work at all ? Isn't a shorter version of the code that I used ?
Copy linkTweet thisAlerts:
@SempervivumJun 15.2019 — Indenting your code in a meaningful way helps a lot:
<i>
</i> const navSlide = () =&gt; {
const burger = document.querySelector('.burger');
const navLinks = document.querySelector('.nav-links');
const links = document.querySelector('nav-links a');

<i> </i> burger.addEventListener('click', () =&gt; {
<i> </i> navLinks.classList.toggle('nav-active');
<i> </i> burger.classList.toggle('animation');

<i> </i> links.addEventListener('click', () =&gt; {
<i> </i> navLinks.classList.remove('nav-active');
<i> </i> burger.classList.remove('animation');

<i> </i> })
<i> </i> });
<i> </i> }

<i> </i> navSlide();

  • 1. You add the event listener for links inside the click handler for burger. This will result in:

    1.1 The listener is added only when the burger is clicked.

    1.2 The listener is added multiplely: Every time the burger is clicked.

  • 2. As written above querySelector will return the first matching element only. You need to use querySelectorAll and a forEach loop in order to add an event listener to all links.
  • Copy linkTweet thisAlerts:
    @SempervivumJun 15.2019 — PS: Unfortunately the forum software breaks my indents partly .-(
    Copy linkTweet thisAlerts:
    @codyhillauthorJun 15.2019 — @Sempervivum#1604792 So this should worki >
    <i>
    </i>links.forEach(a =&gt; {
    a.addEventLsitenerAll('click', () =&gt; {
    navLinks.classList.remove('nav-active');
    burger.classList.remove('burger');
    })
    })

    Copy linkTweet thisAlerts:
    @SempervivumJun 15.2019 — There is no function addEventListenerAll, instead you need to use querySelectorAll:
    const links = document.querySelectorAll('nav-links a');
    links.forEach(a =&gt; {
    a.addEventListener('click', () =&gt; {
    navLinks.classList.remove('nav-active');
    burger.classList.remove('burger');
    })
    })
    (untested)
    Copy linkTweet thisAlerts:
    @daveyerwinJun 15.2019 — arrow functions do not work in IE(in the edge they work)

    querySelectorAll returns a nodeList

    nodeList s do not have the forEach method in IE

    so if you do it more like this it works in most browsers
    ``<i>
    </i>&lt;style&gt;

    .subs{
    display: none;
    }
    &lt;/style&gt;
    &lt;ul&gt;
    &lt;li class="cats"&gt;Car
    &lt;ul class="subs"&gt;
    &lt;li&gt;New car&lt;/li&gt;
    &lt;li&gt;Rent car&lt;/li&gt;
    &lt;li&gt;Car parts&lt;/li&gt;
    &lt;/ul&gt;
    &lt;/li&gt;
    &lt;li class="cats"&gt;Digital
    &lt;ul class="subs"&gt;
    &lt;li&gt;Notebooks&lt;/li&gt;
    &lt;li&gt;Tablets&lt;/li&gt;
    &lt;li&gt;Phones&lt;/li&gt;
    &lt;/ul&gt;
    &lt;/li&gt;
    &lt;/ul&gt;
    &lt;script&gt;
    (function(){
    var active;
    var catsNodeList = document.querySelectorAll('.cats');
    [].forEach.call(catsNodeList,function (item, index, array) {
    item.addEventListener('click',function(){
    if(typeof active != 'undefined') active.style.display = '';
    active=this.getElementsByTagName('UL')[0];
    active.style.display = 'block';
    });
    });
    }());
    &lt;/script&gt;<i>
    </i>
    ``
    Copy linkTweet thisAlerts:
    @codyhillauthorJun 15.2019 — @Sempervivum#1604800 that's what I meant in the first place. sorry. I wanted to type addEventListener idk why I typed

    addEventListenerAll
    Copy linkTweet thisAlerts:
    @LennonJohn1Jun 17.2019 — Our programming experts provide assignment help to students across UK, USA and Australia for multiple programming languages i.e. Java,java script, Python, HTML, PHP, Assembly language, C++ help online ,Linux ,Unix etc. visit:https://www.myhomeworkhelponline.com/c-plus-plus-programming-homework-help/
    ×

    Success!

    Help @codyhill spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 4.25,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,

    tipper: @Samric24,
    tipped: article
    amount: 1000 SATS,
    )...