0

I have included a button on my homepage. I would like, when users click on this button, for the page to scroll down to the appropriate section that the button is referring to (the shop part of my homepage, in my case). How can I insert code for the page to scroll down when a user clicks on a button?

My website is hintdrop.com

Ty B.
  • 13
  • 3

3 Answers3

1

You are looking for a fragment identifier.

Add an id attribute to the section you want to scroll to.

Example: <section id="shop"> ... </section>

Then, use an anchor <a> instead of a button, with an href attribute.

Example: <a href="#shop">Shop</a>

Simple example:

#shop {
  margin-top: 300vh;
  background-color: tomato;
  height: 100vh;
  position: relative;
}

#shop::after {
  content: 'Shop Content';
  position: absolute;
  color: white;
  font-size: 3em;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
<a href="#shop">Shop</a>

<section id="shop"></section>

If smooth scroll is wanted, scrollIntoView can be used like so:

document.querySelector('#shopBtn').addEventListener('click', function() {

  document.querySelector('#shop').scrollIntoView({
    behavior: 'smooth'
  });

});
#shop {
  margin-top: 300vh;
  background-color: tomato;
  height: 100vh;
  position: relative;
}

#shop::after {
  content: 'Shop Content';
  position: absolute;
  color: white;
  font-size: 3em;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
<button id="shopBtn">Shop</button>

<section id="shop"></section>
Ricky Ruiz
  • 25,455
  • 6
  • 44
  • 53
0

you can also try using a ahref and give an id to it so when it is click, it will move to a specific section.

NoobProgrammer
  • 474
  • 4
  • 21
0

Simplest answer: Create an id in your div or other tags, then in your anchor or a href tag, link the name of your id there.

Example:

<!--remember that ID links inside your html tag, should always have a hashtag (#)-->

<a href="#thisismydiv">JUMP TO MY DIVISION</a> 

<!--your codes--->

<div id="thisismydiv">I am div!</div>
Erika
  • 148
  • 3
  • 14