Internal link problem using pure Javascript

Asked

Viewed 45 times

1

Good morning, late or evening to all. I’m having a hard time trying to make a navigation menu with internal link using pure Javascript.

The problem is that I’m probably trying to is that I’m not being able to capture the user’s data, but I don’t know what’s wrong, the browser developer tool (Chrome) says that the node[0] should be [3]. Links "ids" are added

const menuItems = document.querySelectorAll('.menu a');

menuItems.forEach(item => {
  item.addEventListener('click', scrollToIdOnClick);
})

function getScrollTopByHref(element) {
  const id = element.getAttribute('href');
  return document.querySelector(id).offsetTop;
}

function scrollToIdOnClick(event) {
  event.preventDefault();
  const to = getScrollTopByHref(event.target) - 150;
  scrollToPosition(to);
}

function scrollToPosition(to) {
  window.scroll({
    top: to,
    behavior: "smooth",
  });
}
<header>
  <ul class="menu">
    <li>
      <a href="#menu">Home</a>
    </li>
    <li>
      <a href="#quemSomos">Quem Somos</a>
    </li>
    <li>
      <a href="#produtos">Nossos Produtos</a>
    </li>
    <li>
      <a href="#contato">Contato</a>
    </li>
  </ul>
</header>

2 answers

0

I believe that querySelectorAll would have to be like this:

const menuItems = document.querySelectorAll('a.menu');
  • Good evening Rafael, I tried to change how you guided but the nodeList remains zeroed instead of being like [3]

0

Dude, I don’t understand your real problem. But the code you posted won’t work.

'Cause the error in that code is in those two lines

 const id = element.getAttribute('href');
 return document.querySelector(id).offsetTop;

First line returns to variable the href you clicked, for example "#menu"

Then you are trying to do Document.querySelector("#menu"), but there is no such id in html, so it does not find offsetTop.

You need to add ids to the... id="menu", id="whomeWe" links and so on

  • Good note Julio the Ids are properly glued, I’m suspecting that I’m not able to capture the data because the nodeList is zeroed and should be [3]. But thanks for your help!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.