Home > Software design >  How can i add a smoothscroll effect to the next page on my website
How can i add a smoothscroll effect to the next page on my website

Time:12-24

I want my website to have a smoothscroll to the next page, i have a button wich i would like to use as smoothscroll. Using <div id=""></div> and this is the button <a href="Link here"><button type="button"><span></span>More info</button></a> and then i tried adding this in the css file: scroll-behavior: smooth; (in html, body)

CodePudding user response:

You can use the HTML anchor element and the scrollIntoView() method to add a smooth scroll effect to the next page on your website.

For example, if you have a link with the id of "myLink", you can add a smooth scroll effect when the link is clicked by adding the following code to your JavaScript file:

document.getElementById("myLink").addEventListener("click", function() { document.querySelector('#nextPage').scrollIntoView({ behavior: 'smooth' }); });

CodePudding user response:

To create a smooth scroll effect using the button you provided, you can use JavaScript to listen for a click on the button and then smoothly scroll to the desired location on the page.

Example:

<a href="#section-to-scroll-to" id="scroll-button">
  <button type="button">
    <span></span>More info
  </button>
</a>

<div id="section-to-scroll-to">
  <!-- content goes here -->
</div>

<style>
  html, body {
    scroll-behavior: smooth;
  }
</style>

<script>
  const scrollButton = document.getElementById('scroll-button');
  const sectionToScrollTo = document.getElementById('section-to-scroll-to');

  scrollButton.addEventListener('click', (event) => {
    event.preventDefault();
    sectionToScrollTo.scrollIntoView({ behavior: 'smooth' });
  });
</script>

This code listens for a click on the button and then smoothly scrolls to the element with the section-to-scroll-to ID. The scrollIntoView() method can be used to smoothly scroll an element into view. The behavior: 'smooth' option specifies that the scroll should be smooth.

Note that this code assumes that the section-to-scroll-to element is on the same page as the button. If you want to smooth scroll to a different page, you can use the window.scrollTo() method instead.

  • Related