Scroll into view on click issue vanilla js

My scroll into view only works for the first click event listener function but none of the others. why is this? error shows: cannot read properties of null reading (‘addEventListener’)

note: I am using a linked script file at the bottom of page if that is helpful in any way.

HTML

  <section class="navbarBox">

    <div class="logoTextBox">
      <div>
      </div>
    </div>
    <nav class="anchorBox">
      <div>
        <a id="mission" class="navTag">Our Mission</a>
      </div>
      <div>
        <a id="#services" class="navTag">Services</a>
      </div>
      <div>
        <a id="#team" class="navTag"> Our Team</a>
      </div>
      <div>
        <a class="navTag">New Patients</a>
      </div>
      <div>
        <a id="#contact" class="navTag">Get In Touch</a>
      </div>
    </nav>

  </section> 


  <!-- QUOTE -->
  <section id="scrollToMission" class="quoteBox">

    <p class="quote">"hello this is my quote."</p>
    <p class="source">- SMARTY PANTS</p>
  </section>

  <!-- BUILDING WEBSITES -->
  <section id="scrollToServices" class="buildingWebsitesBox">

</services>

JS

// SCROLL ON CLICK:
// navbar ids
let mission = document.querySelector('#mission')
let services = document.querySelector('#services')
let team = document.querySelector('#team')
let contact = document.querySelector('#contact')

// section ids
let scrollToMission = document.querySelector('#scrollToMission')
let scrollToServices = document.querySelector('#scrollToServices')
let scrollToTeam = document.querySelector('#scrollToTeam')
let scrollToContact = document.querySelector('#scrollToContact')

// scroll to click
mission.addEventListener('click', () => {
  scrollToMission.scrollIntoView({behavior: 'smooth'})
  console.log('clicked');
})

services.addEventListener('click', () => {
  scrollToServices.scrollIntoView({behavior: 'smooth'})
  console.log('clicked');
})

team.addEventListener('click', () => {
  scrollToTeam.scrollIntoView({behavior: 'smooth'})
})

contact.addEventListener('click', () => {
  scrollToContact.scrollIntoView({behavior: 'smooth'})
})


The issue seems to be with the ID values of the anchor tags in your HTML. When you set the id attribute in your anchor tags, you only need to specify the ID value itself, without the ‘#’ symbol

1 Like

AHA! Thank you! I must have doing that when I was copy and pasting from my javascript

1 Like
 <!-- BUILDING WEBSITES -->
  <section id="scrollToServices" class="buildingWebsitesBox">

</services>

error

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.