skip to Main Content

I am trying to add a function to all of the links in my nav that will delay the link to the next page while the menu shuts using javascript.

This is my javascript, I know the querySelector part is wrong but I am unsure how to fix it;

document.querySelector(".nav-link-close").addEventListener("click", function (e) {
        e.preventDefault();
        console.log(e.target.href)
        toggleNav(false);
        setTimeout(() => {
            const nextPage = e.target.href;
            window.location.href = nextPage;
        }, 1000)
    });

Thank you in advance to anyone willing to help.

2

Answers


  1. querySelector will get the first element with nav-link-close class, so you need to use querySelectorAll and loop through the elements and add the event.

    const elements = document.querySelectorAll(".nav-link-close")
    elements.forEach(element => {
      element.addEventListener("click", function (e) {
            e.preventDefault();
            console.log(e.target.href)
            toggleNav(false);
            setTimeout(() => {
                const nextPage = e.target.href;
                window.location.href = nextPage;
            }, 1000)
        });
    })
    
    
    Login or Signup to reply.
  2. When you want to select all elements of a class, use querySelectorAll. You also have to loop through every single element to add the event listener to each element.

    document.querySelectorAll(".nav-link-close").forEach( el => {
        el.addEventListener("click", function (e) {
            e.preventDefault();
            console.log(e.target.href)
            toggleNav(false);
            setTimeout(() => {
                const nextPage = e.target.href;
                window.location.href = nextPage;
            }, 1000)
        });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search