简体   繁体   中英

make dyanmic scroll using "scrollIntoView" if I will using one class no problem but the problem with the dynamic class

// html

<div class="nav-bullets">
      <div class="bullet">
        <div class="tooltip" data-i=".about-us">About Us</div>
      </div>
      <div class="bullet">
        <div class="tooltip" data-i=".skills">Our Skills</div>
      </div>
      <div class="bullet">
        <div class="tooltip" data-i=".gallery">Our Gallery</div>
      </div>
      <div class="bullet">
        <div class="tooltip" data-i=".timeline">TimeLine</div>
      </div>
    </div>

// javascript

using one class no promlem like this

// Select All Bullets
const allBullets = document.querySelectorAll(".nav-bullets .bullet");

allBullets.forEach(bullet => {
bullet.addEventListener("click" , (e) => {
    document.querySelector(".about-us").scrollIntoView({
      behavior: 'smooth'
    });
 
});
});

// the problem

// Uncaught TypeError: Cannot read properties of null (reading 'scrollIntoView')     at HTMLDivElement.<anonymous> 

 

// but if i will make the class dynamic not working like this

 allBullets.forEach(bullet => { bullet.addEventListener("click" , (e) => {     document.querySelector(e.target.dataset.i).scrollIntoView({       behavior: 'smooth'     });   }); });

You're attaching the event listener to the .bullet element, but it has no data-i attribute, you've added that to the child .tooltip :

<div class="bullet"> <-- event listener is here
  <div class="tooltip" data-i=".about-us"> <-- data attribute is here
    About Us
  </div>
</div>

Which is why e.target.dataset.i is undefined and document.querySelector(undefined) doesn't match any element.

Move the data attribute to the .bullet .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM