Search code examples
javascriptweb-frontend

A javascript function that scroll down the page when user click's on a element


i wanted to creat a JS function that add's event listener to a link so when user click's on that link, it will scroll down the page to a spicific element but for some reason it didn't work out so I need you'r help

i tried this code but it's not working

function scrollToElement(elementSelector, instance = 0) {
    const elements = document.querySelectorAll(elementSelector);
    if (elements.length > instance) {
      elements[instance].scrollIntoView({ behavior: 'smooth' });
    }
  }
  

const link1 = document.getElementById("link1");
const link2 = document.getElementById("link2");
const link3 = document.getElementById("link3");

link1.addEventListener('click', () => {
  scrollToElement('.features');
});

link2.addEventListener('click', () => {
  scrollToElement('.header', 1);
});

link3.addEventListener('click', () => {
  scrollToElement('.column');
});


Solution

  • Make sure that the element is visible.

    Try to change your function like following:

    function scrollToElement(el, instance=0) {
      const elements = document.querySelectorAll(el);
      
      if (elements.length > 0) {
        if(!elements[instance].checkVisibility()) return;
    
        elements[instance].scrollIntoView({ behavior: 'smooth' });
      }
    }