Home > Mobile >  tag a not working on pure javascript on onClick event
tag a not working on pure javascript on onClick event

Time:01-15

I've run into the following problem. I made a landing page, made links to page sections through pure javascript, everything seems to be working, super. But, I wanted to add a regular <а></а> link and it turns out it doesn't work, I understand that the reason lies in event.preventDefault(); but if this is removed, then the main script breaks

document.querySelector('.nav').addEventListener("click", (event) => {
    event.preventDefault();
    let elementOffset = 0;

    let parent = document.querySelector('.nav');
    let menuItem = parent.querySelectorAll('.nav__link');

    if(event.target.classList.contains('nav__link')) {
        for (let i = 0; i < menuItem.length; i  ) {
            menuItem[i].classList.remove('active');
        }
    }

    let elementId = event.target.getAttribute('data-scroll');
    let element = event.target;

    if(elementId && element){
        elementOffset = getElementScrollOffset(elementId);

        scrollToTop(elementOffset);

        element.classList.add('active');
    }
});
<div >
                <div  data-scroll="#intro"></div>
                <nav  id="nav">
                    <a  href="#" data-scroll="#about">about</a>
                    <a  href="#" data-scroll="#services">services</a>
                    <a  href="#" data-scroll="#mods">Сmods</a>
                    <a  href="#" data-scroll="#updates">updates</a>
                    <a  href="#" data-scroll="#footer">Кfooter</a>
                    <a  href="https://www.google.com/" target="_blank">Discord</a>
                </nav>
            </div>

If you remove event.preventDefault(); instead of going to it, it takes me to the top page. Yes, I understand that you can insert a link outside the .nav element, but I need it there. Help pls :)

CodePudding user response:

What you need to do in you click handler is to prevent the execution of the code if the clicked link is not an in-page anchor. You could do this by checking that the href of the clicked <a> element is not equal to #. You could do this by modifying your handler as follows:

document.querySelector('.nav').addEventListener("click", (event) => {
  if (event.target.getAttribute('href') !== '#') { return; }

  /* rest of handler logic remains the same */
});

I have created a fiddle for reference.

  • Related