
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Scroll the Page Up or Down Using Anchor Element in jQuery
jQuery is a popular JavaScript library that simplifies the process of manipulating HTML documents, handling events, and creating animations. In this article, we'll see how to scroll the page up or down using the anchor elements in jQuery.
We sometimes encounter large content pages on websites and to go to a specific section, we want to perform the scrolling in the page up or down. To solve this problem, there are several ways to achieve this, but using anchor elements is one of the easiest and most straightforward methods. Apart from this, we'll see the scrollTop and animate to perform this task.
Approach 1: Using Anchor Element
In this approach, we will be using anchor element to scroll the page up or down. An anchor element is an HTML tag that creates a link to another location within the same page or to a different page. It is identified by the 'a' tag and the href attribute is used to specify the URL of the target location. When a user clicks on an anchor link, the browser scrolls the page to the target location.
Steps to Scroll the Page Using the Anchor Element
Step 1: Create the Anchor Links First
<a href="#para2">Go to Para 2</a>
Step 2: Adding id to div Element
<div id="para2"> <p>This is section 2.</p> </div>
Step 3: jQuery Code to Scroll the Page When the Links are Clicked
$(document).ready(function() { $('a[href^="#"]').on('click', function(event) { var target = $(this.getAttribute('href')); if (target.length) { event.preventDefault(); $('html, body').stop().animate({ scrollTop: target.offset().top }, 1000); } }); });
Example
<!DOCTYPE html> <html> <head> <title>Scrolling with Anchor Elements in jQuery</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { $('a[href^="#"]').on('click', function(event) { var target = $($(this).attr('href')); if (target.length) { event.preventDefault(); $('html, body').stop().animate({ scrollTop: target.offset().top }, 500); } }); }); </script> <style> body { height: 1500px; } h1 { margin-top: 50px; } a { display: block; margin-bottom: 10px; } </style> </head> <body> <a href="#para1">Go to Para 1</a> <a href="#para2">Go to Para 2</a> <a href="#para3">Go to Para 3</a> <h1 id="para1">Section 1</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales quam id malesuada finibus. Vestibulum et leo eu nibh feugiat blandit. Suspendisse sollicitudin ipsum vel lacus pretium, a auctor libero feugiat. Proin eleifend commodo ante, sed consectetur ipsum gravida non.</p> <h1 id="para2">Section 2</h1> <p>Phasellus vel commodo sapien, id tristique nibh. Duis mattis metus at orci commodo aliquam. Pellentesque imperdiet, ex non eleifend consequat, purus dolor consequat risus, in interdum nunc lectus eu augue. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p> <h1 id="para3">Section 3</h1> <p>Nam commodo felis ut massa posuere, eu bibendum ex vehicula. Nam pellentesque sem et turpis interdum, vitae consequat mauris imperdiet. Nulla eu pretium purus. Morbi sodales, lorem ut euismod dapibus, quam nisl aliquam enim, vel sodales mauris purus sit amet leo.</p> </body> </html>
Output
Approach 2: Using ScrollTop and Animate
Another approach to scroll the page up or down using jQuery involves using the built-in jQuery methods 'scrollTop' and 'animate'. See the below steps to implement it ?
Steps to scroll the Page Using ScrollTop and Animate
Step 1: Selecting Element to Scroll
First, we'll need to select the element that we want to scroll to. For example, let's say we want to scroll to a div with the id "myDiv". We can select this element using the jQuery selector as follows ?
var target = $('#myDiv');
Step 2: Using scrollTop Method
Next, we can use the 'scrollTop' method to get the current vertical scroll position of the window. This method returns the number of pixels that the document is currently scrolled from the top. We'll store this value in a variable called 'scrollPosition' ?
var scrollPosition = $(window).scrollTop();
Step 3: Using scrollPosition
Now that we have the target element and the current scroll position, we can calculate the distance that needs to be scrolled. We'll subtract the target element's offset from the top of the document from the current scroll position to get the distance that needs to be scrolled ?
var scrollDistance = target.offset().top - scrollPosition;
Step 4: Adding Animate Method
Finally, we can use the 'animate' method to smoothly scroll the page to the target element. We'll pass in an object with the 'scrollTop' property set to the desired scroll distance, along with a duration in milliseconds for the animation ?
$('html, body').animate({ scrollTop: scrollDistance }, 1000);
Step 5: jQuery Code
$(document).ready(function() { $('a[href^="#"]').on('click', function(event) { var target = $($(this).attr('href')); if (target.length) { event.preventDefault(); var scrollPosition = $(window).scrollTop(); var scrollDistance = target.offset().top - scrollPosition; $('html, body').animate({ scrollTop: scrollDistance }, 1000); } }); });
Example
<!DOCTYPE html> <html> <head> <title>Scrolling with Anchor Elements in jQuery</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { $('a[href^="#"]').on('click', function(event) { var target = $($(this).attr('href')); if (target.length) { event.preventDefault(); var scrollPosition = $(window).scrollTop(); var scrollDistance = target.offset().top - scrollPosition; $('html, body').animate({ scrollTop: scrollDistance }, 800); } }); }); </script> <style> body { height: 1500px; } h1 { margin-top: 50px; } a { display: block; margin-bottom: 10px; } </style> </head> <body> <a href="#para1">Go to Para 1</a> <a href="#para2">Go to Para 2</a> <a href="#para3">Go to Para 3</a> <h1 id="para1">Para 1</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales quam id malesuada finibus. Vestibulum et leo eu nibh feugiat blandit. Suspendisse sollicitudin ipsum vel lacus pretium, a auctor libero feugiat. Proin eleifend commodo ante, sed consectetur ipsum gravida non.</p> <h1 id="para2">Para 2</h1> <p>Phasellus vel commodo sapien, id tristique nibh. Duis mattis metus at orci commodo aliquam. Pellentesque imperdiet, ex non eleifend consequat, purus dolor consequat risus, in interdum nunc lectus eu augue. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p> <h1 id="para3">Para 3</h1> <p>Nam commodo felis ut massa posuere, eu bibendum ex vehicula. Nam pellentesque sem et turpis interdum, vitae consequat mauris imperdiet. Nulla eu pretium purus. Morbi sodales, lorem ut euismod dapibus, quam nisl aliquam enim, vel sodales mauris purus sit amet leo.</p> </body> </html>
Output
Conclusion
Scrolling to a specific section of a web page is an essential feature to enhance user experience. jQuery offers a simple and straightforward approach to implement this functionality using anchor elements. Using anchor elements creates links to other locations on the same page and can easily be identified by the 'a' tag and 'href' attribute. By following the simple steps outlined in this article, web developers can easily implement scrolling to specific sections using jQuery. Additionally, the 'scrollTop' and 'animate' built-in jQuery methods can be used to achieve the same functionality. Regardless of the approach, the end result is a seamless and intuitive navigation experience for users.