Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Select and add function to all links in a nav

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
    });
})

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading