Smooth Scroll to Div using jQuery

January 25 - 2024
Smooth Scroll to Div using jQuery

Smooth scrolling using jQuery enhances the user interface of web projects, reducing the effort required to navigate to specific sections of a page. By incorporating smooth scroll functionality, users can effortlessly reach desired portions of the page through anchor links or buttons.

Utilizing the jQuery scrollTop method simplifies the process of scrolling to a specific div element. To add a touch of animation to the page scroll, the jQuery animate() method can be employed. In this tutorial, we'll guide you through implementing smooth scrolling to a div using jQuery, eliminating the need for manual scrolling.

Scrolling to a Div

The Scroll to Div feature proves particularly beneficial for single-page websites, allowing users to navigate to specific sections seamlessly. The example code below demonstrates how to scroll to a div and jump to specific sections of the page by clicking on anchor links, all achieved with jQuery.
 

<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Auto Smooth Scroll by CodeAT21</title>
<meta charset="utf-8">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Script for smooth scrolling -->
<script>
$(function() {
        $('a[href*=\\#]:not([href=\\#])').on('click', function() {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.substr(1) +']');
            if (target.length) {
				$('html,body').animate({
				  scrollTop: target.offset().top
				}, 1000);
				return false;
            }
        });
    });
</script>
<style>
body {
    margin: 0 auto;
    padding: 77px;
}
	h1{font-size: 40px;}
	p{ font-size: 35px;}
	#top a {padding: 10px;font-size: 40px;}
</style>
</head>
<body>
    <div id="top">
        <a href="#section1">Go Section 1</a>|
        <a href="#section2">Go Section 2</a>|
        <a href="#section3">Go Section 3</a>|
        <a href="#section4">Go Section 4</a>
    </div>
    <div id="section1">
        <h1>Section 1</h1>
        <p>In a disorienting world, with obstacle after obstacle, and the landscape of our lives shifting in ways we never expected, we can trust that as we look to our Maker, the WayMaker, our road will lead us to arrive exactly where we always hoped it would, though maybe not at all in the way we imagined. And those dreams for our lives? They can still happen—in ways only He perfectly dreamed of. </p>
        <p>In a disorienting world, with obstacle after obstacle, and the landscape of our lives shifting in ways we never expected, we can trust that as we look to our Maker, the WayMaker, our road will lead us to arrive exactly where we always hoped it would, though maybe not at all in the way we imagined. And those dreams for our lives? They can still happen—in ways only He perfectly dreamed of. </p>
   </div>
    <div id="section2">
        <h1>Section 2</h1>
        <p>It is true: heartache, grief, suffering, obstacles, they all come in waves. There is no controlling life’s storms; there is only learning the way to walk through the waves. In WayMaker, bestselling author Ann Voskamp hands us a map that makes meaning of life, that shows the way through to the places we’ve only dreamed of reaching, by a way we never expected. Voskamp reveals how God is present in the totality of our lives, making a wayfor the marriage that seems impossible,for the woman who longs for a child of her own,for the parents who ache for the return of their prodigal,for the sojourner caught between a rock and a hard place, and for the wayfarer who feels as though there is no way through to her dreams. We can encounter the WayMaker in surprising ways and begin to see Him not only making poetry out of pain but working in every miraculous detail of our lives. Even now, the Way is making the way to walk through waves and into a life more deeply fulfilling than our wildest dreams.</p>
    </div>
    <div id="section3">
        <h1>Section 3</h1>
        <a href="#top">BackToTop</a>
		 <p> When you're a bear who is easily scared, it's hard to have friends. Fortunately, Bear has one: Rabbit, who is very brave. One day, Rabbit urges Bear to face his fears and embark on an adventure together. However, things don't entirely go as planned, and the two friends learn the true meaning of bravery.</p>
    </div>
    <div id="section4">
        <h1>Section 4</h1>
        <a href="#top">BackToTop</a>
		 <p> Equal parts hilarious and touching, this funny tale of adventure, bravery, and daring rescue will both inspire the adventurous spirit in all of us and make us laugh along the way. With the unfailingly witty voice of one of America's favorite comedians, Seth Meyers's debut picture book is bound for hilarity history. </p>
    </div>
</body>
</html>

Smooth Scrolling Script

Uses jQuery to enable smooth scrolling when clicking on navigation links. It targets all anchor (<a>) elements with an href attribute containing # (except for #) and adds a click event listener. When a link is clicked, it scrolls to the target section with a smooth animation.


The smooth scrolling is achieved through the jQuery animate function, scrolling to the target section's top position over 1000 milliseconds (1 second).

  • The CSS styles mainly focus on adjusting font sizes for various elements.
  • The navigation links in the #top div provide a quick way to navigate between sections.
  • Sections 3 and 4 have a "BackToTop" link that uses the smooth scrolling script to scroll back to the top of the page.
  • This code utilizes jQuery for simplicity. Ensure that the jQuery library is available, either by the provided CDN or by downloading and hosting it locally.

 

You may also like…

Related posts

January 25 - 2024

How To Use the .htaccess File

The .htaccess (hypertext access) file is a configuration file used on web servers running the Apache web server software. It allows you to customize various aspects of your website's behavior at the directory level, without altering server configuration files. Here's a basic guide on how to use the .htaccess file:Creating the .htaccess File:The .htaccess file is a plain text file, and you can create it using a text editor like Notepad on Windows or TextEdit on macOS.Save the file with the name ".htaccess" (make sure there is no extension like .txt).File Location:The .htaccess file is typically placed in the root directory of your website. It can also be placed in specific directories to appl...
January 25 - 2024

Back to Top Button using jQuery and CSS

Creating a Back to Top button enhances the user experience of a website, especially for pages with extensive content. This button allows users to effortlessly return to the top of the page with a single click, eliminating the need for manual scrolling.This tutorial demonstrates how to craft a Back to Top button using jQuery and CSS. Positioned at the right-bottom corner of the content area, the button automatically appears after the browser window has been scrolled down. When clicked, the page smoothly scrolls back to the top. This feature streamlines navigation, enabling users to swiftly navigate from the bottom to the top of the webpage.The Back to Top button is a valuable addition for web...
January 29 - 2024

What are penny stocks, and is it wise to invest in them?

Penny stocks, characterized by their low share prices, may seem attractive due to their apparent affordability. However, these stocks can be risky investments, often leading to unexpected losses for investors. In this discussion, we delve into what defines a penny stock, the associated risks, and the myths that can mislead potential investors.What Constitutes a Penny Stock?Penny stocks typically trade at prices below $5 per share, with a common reference being those below a dollar. These stocks are frequently not listed on major exchanges like the NYSE or Nasdaq, instead finding a place on the pink sheets or the over-the-counter (OTC) market. The lack of listing on major exchanges contribute...

Devooti   © All Rights Reserved - 2024