How to close navigation bar in JS by clicking away?

I know this is a frequently asked question but I am not really familiar with web development and this is the only thing I need to get done.

This is how the navigation javascript snippet currently looks like:

const hamburger = document.querySelector('.hamburger');
const navItem = document.querySelector('.nav__items');

hamburger.addEventListener('click', () => {
    hamburger.classList.toggle('active');
    navItem.classList.toggle('active');
})

And this is how what I have tried to make it work (doesn’t work):

document.addEventListener = ('click', () => {
    if(hamburger.target.querySelector !== ".hamburger" &&
    navItem.target.querySelector !== ".hamburger") {
        hamburger.classList.remove('active');
        navItem.classList.remove('active');
    }
})

Please, if you can help me with this, I’d be really appreciated!
Have a great day :slight_smile:

Well, the syntax highlighting should be telling you that you’ve goofed somewhere…

Compare:

So that’s the first part.

The next part you’re going to run into is that hamburger and navItem dont have a “target”. That’s a property of the event, not of an element.

You’re currently not catching the event, so first we need to tell javascript to catch it:

becomes
('click', (event) => {

At this point, you now have access to the event object, and the properties thereto, whereby you could check to see if the event’s target is the element you captured as hamburger or navItem. Note that hamburger and navItem appear to be classes, and that querySelector will only have found the first instance of that class.

1 Like