ArticleZip > Smooth Scroll To Specific Div On Click

Smooth Scroll To Specific Div On Click

Have you ever visited a webpage with a long scroll and wanted to navigate to a specific section quickly by clicking a button or link? This is where smooth scrolling to a specific div on click comes in handy. In this article, we will guide you on how to implement this functionality using HTML, CSS, and JavaScript on your website.

To achieve smooth scrolling to a specific div on click, the first step is to create the HTML structure of your page. Make sure to give each section you want to scroll to a unique ID. This ID will be used as an anchor point for the smooth scrolling effect. Here's an example:

Html

<div id="section1">
   <!-- Content of section 1 goes here -->
</div>

<div id="section2">
   <!-- Content of section 2 goes here -->
</div>

<button>Go to Section 1</button>
<button>Go to Section 2</button>

In the above code snippet, we have two sections with IDs `section1` and `section2`. We also have two buttons that will trigger the smooth scroll effect when clicked.

Next, let's add some CSS to style our sections and buttons. You can customize the styles according to your design preferences. Here is a basic example:

Css

#section1,
#section2 {
   height: 100vh;
   padding: 20px;
   border: 1px solid #ccc;
   margin: 10px;
}

button {
   background-color: #007bff;
   color: #fff;
   padding: 10px 20px;
   border: none;
   cursor: pointer;
}

Now comes the exciting part – adding the JavaScript code to enable smooth scrolling to a specific div on click. We will create a function called `scrollToSection` that takes the ID of the section as a parameter and scrolls to that section smoothly. Here's the JavaScript code:

Javascript

function scrollToSection(sectionId) {
   const section = document.getElementById(sectionId);
   window.scrollTo({
      top: section.offsetTop,
      behavior: 'smooth'
   });
}

In the `scrollToSection` function, we first get the element with the specified ID using `document.getElementById`. Then, we use `window.scrollTo` to smoothly scroll to the top position of that element when the corresponding button is clicked.

Finally, don't forget to link your CSS and JavaScript files to your HTML document and test your smooth scroll functionality. You should now have a website where visitors can navigate to specific sections smoothly by clicking buttons or links.

Smooth scrolling to a specific div on click can greatly enhance the user experience of your website, making navigation more user-friendly and engaging. We hope this article has been helpful in guiding you through implementing this feature on your website. Happy coding!

×