Home > Blockchain >  Using Javascript to scroll to an element automatically when the user scrolls
Using Javascript to scroll to an element automatically when the user scrolls

Time:02-06

I made a website that has 2 sections. You have to scroll a bit to come to section 2 so I wanted to make a code which sends you directly to section 2 when you scroll down.

So I made a basic function that works when I use a button to trigger it but I couldnt figure out how can I make this function run when the user scrolls. The function:

     function scroll_to_target(){
        document.getElementById("moreinfo").scrollIntoView();
     }

Basically I need something that when the user scrolls down in the first section of the website it triggers "scroll_to_target()" function which makes the user scroll to "moreinfo" (second section) of the website directly and smoothly.

CodePudding user response:

// Get the element with id "moreinfo"
var element = document.getElementById("moreinfo");

// Listen for the scroll event on the window object
window.addEventListener("scroll", function() {
  // Check if the user has scrolled to the target element
  if (element.getBoundingClientRect().top <= 0) {
    // Scroll to the target element
    element.scrollIntoView();
  }
});

CodePudding user response:

i guess you can use Jquery to do that , for the scroll function to hit you could do something like this after importing jquery to project :

    $(window).on("scroll", function() {
       //call the function here or make any changes
    });

  • Related