Using websites and web applications have become a usual technological tool for our daily life. It also happened that in the website, we wanted to scroll automatically to any particular section of the webpage once we click a link or button or heading of the navbar. It is a new feature, and achieving this auto-scrolling technique requires implementing jQuery.In this article, you will learn how to use jQuery to implement this auto-scrolling technique.
Ingredients require in this auto-scrolling:
This auto-scrolling to a specific element is created using HTML scripting and jQuery. jQuery is a small, feature-rich, and fast JavaScript library that is used to give specific mechanisms to a web page. It works with HyperText Markup Language (HTML), which is a standard web page development tool. Apart from all these, two jQuery methods will be used that are discussed separately in the next paragraph.
Scrolling to a specific element
Before achieving the auto-scrolling thing for your web page, you have to have an understanding of the two methods namely scrollTop() and offSet() in jQuery.
- scrollTop() method: This method allows programmers to get to the current vertical position of the first element as per the setting of the matched elements.
- offSet() Method: It is responsible for getting the coordinates of the first element from the set of all matching elements.
Practical Implementation of this technique:
- Programmers and web developers can use this to validate a form. It let the user scroll to the first error and makes the user correct it.
- Another way to utilize this technique is when the programmer wants the users to navigate to different topic headings of a series of content, they can click the links to the navbar.
Program:
<html lang="en">
<head>
<meta charset = "UTF-8">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="crossorigin = "anonymous"></script>
<title>Scrolling automatically to specific element - Example</title>
<style>
div {
color: #800080;
border: 3px solid #A52A2A;
margin: 20px;
width: 200px;
height: 100px;
overflow: auto;
}
p {
width: 300px;
height: 300px;
}
button {
margin: 12px;
}
</style>
</head>
<body>
<div class = "scrolly">
<h2>Heading</h2>
<p id="p1"> First paragraph </p>
<p id="p2">Second paragraph </p>
</div>
<button onclick = "scrollParagraph1()">First paragraph</button>
<button onclick = "scrollParagraph2()">Second paragraph</button>
<script>
var container = $('div');
function scrollParagraph1() {
var scrollTo = $("#p1");
var position = scrollTo.offset().top - container.offset().top + container.scrollTop();
container.animate({
scrollTop: position
});
}
function scrollParagraph2() {
var scrollTo = $("#p2");
var position = scrollTo.offset().top - container.offset().top + container.scrollTop();
container.animate({
scrollTop: position
});
}
</script>
</body>
</html>
Explanation:
First, we started with the HTML tag containing the lang attribute that defines the language in which the entire web page documentation will take place. Then comes the <head> and within that <head>, we have put the <meta> tag and the <script> tag.
The charset of the meta tag defines the character set for the document. The script tag will enable the jquery. Under the <head> is the <title> where we set the title of the web page. Then comes the <style> tag within the div that determines the font color, border color, margin, width, and height of the specific segment, we want to use. Also, within the <style> we define the styling of the paragraph and button. Finally close the </head>.
Next comes the <body> tag. This is the tag from where the actual implementation of the web page will take place. Within it, we have defined the div nesting the <H1> and the <P>. Next, we use the <button> tag with the onclick attribute with the value "scrollParagraph1()”, and same for the second button also. Then comes the main <script></script>.
Within this tag, you have to define a variable ‘container’ initializing it with $('div'). Next, we have created a user-defined function scrollParagraph1() that will perform the scrolling operation of the jQuery. Inside that function, we have to create a local variable position that will calculate the scrolling operation based on the offset() function and the formula: position = scrollTo.offset().top - container.offset().top + container.scrollTop()
Next, we will use the container.animate to make the scrolling smooth. The same technique goes for the scrollParagraph2() function also. Finally, you have to put the closing tag of the <script> and then <body> and then <HTML>.
Changing jQuery Smooth Scroll to Fast Scroll:
We can also make the scrolling smooth to fast by adding an animated effect to the code. To do this the code snippet will be:
jQuery(document).ready(function ($) {
$(".scroll").click(function (event) {
event.preventDefault();
$('html,body').animate({scrollTop:$(this.hash).offset().top},
Math.abs(window.scrollY - $(this.hash).offset().top) * 10);
});
});
Smoothly scroll to an element without a jQuery plugin:
There is another way to perform a smooth scrolling without implementing a jQuery plugin. The technique uses special effect where you click on a link and your browser will smoothly scroll down to the appropriate section of that particular page. Here are some code snippets that can help you achieve the same on your own website.
Code:
$('a[href^="#"]').on('click', function(event) {
var target = $(this.getAttribute ('href') );
if (target.length) {
event.preventDefault();
$('html, body').stop().animate( {
scrollTop: target.offset().top
}, 600);
}
});
Or,
$('.top').click(function (e) {
e.preventDefault();
$('html, body').animate( scrollTop: 0
});
});
Scroll to specific element using jQuery:
A lot of times we want to scroll to a specific section or element of our webpage automatically as we click on a button or a heading in a navbar or a list. We can achieve this auto-scrolling with the help of jQuery.
Program:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="crossorigin = "anonymous"></script>
<title>How to scroll to specific item using jQuery?</title>
<style>
div {
color: #0f9d58;
border: 3px solid #0f9d58;
width: 200px;
height: 100px;
overflow: auto;
}
p {
width: 300px;
height: 300px;
}
</style>
</head>
<body>
<div class="demo">
<h1>Heading</h1>
<p>paragraph</p>
</div>
<script>
var container = $('div');
var scrollTo = $('p');
var position = scrollTo.offset().top
- container.offset().top
+ container.scrollTop();
container.scrollTop(position);
</script>
</body>
</html>
Scroll screen specific number of pixels down:
We can also make our program scroll from the current position to a some specific number of pixels. To do this, the code snippet will be:
Scroll Down 300px
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="crossorigin = "anonymous"></script>
<title>Scroll screen specific number of pixels down</title>
<script>
$(document).ready(function() {
$(".scroll").click(function(event) {
$('html, body').animate({ scrollTop: '+=300px'}, 500);
});
});
</script>
</head>
<body>
<p class="scroll"> Scroll 300px </p>
<p style="height: 1000px;"></p>
</body>
</html>
Scroll Up 300px
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="crossorigin = "anonymous"></script>
<title>Scroll screen specific number of pixels down</title>
<script>
$(document).ready(function() {
$(".scroll").click(function(event) {
$('html, body').animate({ scrollTop: '-=300px'}, 500);
});
});
</script>
</head>
<body>
<p style="height: 1000px;"></p>
<p class="scroll"> Scroll 300px </p>
</body>
</html>
Conclusion:
Scrolling to specific part or element in a webpage has become a common component of web application development. This type of auto-scrolling comes under dynamic scripting. HTML is mostly a static scripting language were putting logic and pre-defined methods is not possible. That is why JavaScript and jQuery plays a critical role in putting logic and conditions to the code to make the web scripting dynamic.