'How do I create a button that when clicked scrolls down to a different section on the page?

I have created a button on a landing page, I would like users to be redirected to another section (in my case the contact section) on the same page when they click this button. I have tried doing this but it's not working

       document.querySelector('#btn').
       addEventListener('click',()=>{
       document.querySelector('#contact').
       style.scrollBehavior = 'smooth'
})
  <button id="btn">Discover Now</button>
  <section id = "contact" class="contact"></section>
    

I have also tried this

<button><a href="#contact">Discover Now</a></button>

but did not work, where am I doing it wrong?



Solution 1:[1]

In CSS, set scroll-behavior property like this:

html {
    scroll-behavior: smooth;
}

In HTML, add an a tag with a href attribute refering to certain section:

<a href="#contact">Click</a>
<div id="contact"></div>

Solution 2:[2]

Just

<a href="#contact">Discover Now</a>

You can't put a link inside a button. Use CSS to make the link look like a button.

Solution 3:[3]

You having a ; inside a javascript object { behavior:'smooth' ; } which make an error syntax, you also could press f12 to check the console logs, im sure it yelling at you the same when you click the button, something like unexpected token ;:

<button id="btn">Discover Now</button>
<section id = "contact" class="contact">

<script>
   document.querySelector('#btn').
   addEventListener('click',()=>{
   document.querySelector('#contact').
     scrollIntoView({
     behavior:'smooth'
   });
</script>

Solution 4:[4]

You are missing a closing section tag.

<section id = "contact" class="contact">
   lorem ipsum
</section>

You may want to check on this page for explanations: https://www.w3schools.com/howto/howto_css_smooth_scroll.asp#section1

Solution 5:[5]

Why use javascript? You can do this with just html. All you need is:

<a href="#contact">Discover now</a>
<div id="contact">Contact section</div>

Neither of your examples are valid html btw.

Solution 6:[6]

using scrollit it is easy to customize http://www.bytemuse.com/scrollIt.js/

Solution 7:[7]

<a href="#contact">Discover now</a>

That's what i recommend using. You can use javascript with this

<button id="contact">Discover now</button>

document.getElementById("contact").addEventListener("click", function(){
    location.hash = "contact";
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daweed
Solution 2 RoToRa
Solution 3
Solution 4 Achinga
Solution 5 Seth Warburton
Solution 6 mehul kalena
Solution 7