Have you ever noticed how a scroll works on a webpage? What if you are not allowed to touch the mouse or the arrow keys on the keyboard. How would you scroll then? If you happen to have pressed the space key while navigating a page, you’d have noticed that it scrolls down a page, welcome to the club! But in addition to that, there is another way to scroll the page of the website using a dedicated key on the keyboard. Yes, the PgDn (Page Down) key. Now, before reading the post and what we are about to discuss, scroll this page using the page down key and notice if there’s an abrupt pattern (sudden jump).
Scrolling is a commonly used feature on computers. Even without the mouse, there are still a lot of users who rely on the keyboard for scrolling. These users include the readers, editors, and other people who tend to read a lot. As a web developer, you must have coded or noticed a link on the webpage that takes you to another section on the web page by giving the id of that element as href in the anchor tag. It is so instant that the “scrolling” part is quite abrupt.
I have written this article on how to create a smooth scroll with CSS, JavaScript & Jquery to help your users’ scroll smoothly over the pages or the section on the same page.
Run your Automation Selenium Testing scripts on the LambdaTest cloud grid. Test on 3000+ desktop & mobile environments. Try it for free.
What Is Smooth Scrolling?
Smooth scrolling is a user-friendly web feature that enables seamless navigation through web pages. It is a cool feature on websites that lets you scroll smoothly, unlike choppy and distracting scrolling. It’s great for reading long pages because it’s not annoying like normal scrolling.
Let’s see a small demo difference between normal scrolling and smooth scrolling:
The above image uses id as the navigation link for the same page to demonstrate how the page moves when clicked on the link.
If I change the scrolling to smooth, the image would look like this:
Doesn’t it look more graceful and a good choice that a user might prefer?
Smooth scrolling is a very important, useful, and common feature used in web development today. The best thing about creating a smooth scroll is that we get options according to our convenience for creating a smooth-scroll web page. You can achieve Smooth scroll with CSS, JavaScript, and Jquery. We will explore all of the three Smooth scrolls in detail.
It’s crucial to debug websites for Safari before pushing them live. In this article, we look at how to debug websites using Developer tools for Safari.
How To Create Smooth Scroll With CSS?
CSS provides us a standard property to make a page that scrolls smoothly. This property is called “smooth-behavior”.
The smooth-behavior property for Smooth Scroll in CSS takes four values:
auto
smooth
initial
inherit
Auto:
The auto value of smooth-behavior in CSS is the default value of the scroll-behavior which is the direct jump from one element to another.
Smooth:
The smooth value of smooth-behavior for Smooth Scroll in CSS changes the element’s scroll behavior from a direct jump to a smooth transition from one element to another. This was shown in the above image.
Initial:
The initial is the reserved keyword for Smooth Scroll in CSS and not a value specific to scroll-behavior. The initial value sets the default behavior of a property like color, align, etc. In this case, initial and auto will behave in the same way as the auto is the default behavior.
Inherit:
The inherent value inherits the value from the parent element.
To apply smooth scroll with CSS, you need to mention one single line on the element you are trying to scroll smoothly.
scroll-behavior: smooth;
The following piece of code will help:
<!DOCTYPE HTML>
<head>
<title>Sticky Element </title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<style>
.navbar {
position : sticky;
top : 0;
background-color: #32839c;
}
html {
scroll-behavior: smooth;
}
.active a {
color : black;
}
p {
font-size: 20px;
}
#description {
/* background-color: #6ccde6; */
text-align: justify;
width : 75%
}
</style>
</head>
<body style = "background-color: #3991bd; text-align: "justify"">
<!-- <div id = "sticky-div">
<br>
Introduction To Sticky Elements In CSS
<br>
</div> -->
<center>
<h1>Welcome To Info Wiki</h1>
<br><br>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">Info-Wiki</a>
</div>
<ul class="nav navbar-nav">
<li class="active"><a href="#" style="color: black">Home</a></li>
<li><a href="#what" style="color: black">What</a></li>
<li><a href="#distance" style="color: black" >Distance</a></li>
<li><a href="#author" style="color: black">Author</a></li>
</ul>
</div>
</nav>
<br>
<br>
<h1>Comet Swan</h1>
<br>
<img src="Comet_Swan.jpg" width="300px" height="300px" />
<br><br><br>
<h1 id="what">What Is Comet Swan??</h1>
<br>
<p id="description">
“Your Text”
</p>
<br><br>
<h1 id="distance">
How Far Is Comet Swan?
</h1>
<br>
<p id = "description">
“Your Text”
</p>
<br><br>
<h1>
How To See Comet Swan?
</h1>
<br><br>
<p id = "description">
“Your Text”
</p>
<br><br>
<h3 id="author">Written By Harish Rajora</h3>
</center>
</body>
</html>
This corresponds to the following effect:
Although incorporating the smooth scroll in CSS will do the job, it is not perfect and neither the best way. For me, as a web developer, I need more control over my web page and definitely the elements I am using on it. In addition to that, as discussed in the next section, the browser support for a smooth scroll in CSS is poor. Since this control is not provided by CSS and, you can rely on JavaScript for the same effects rather than CSS.
Do you need to gather more knowledge on testing web? LambdaTest is here to explain further.
Browser Support For Scroll-Behavior
The browser support for the CSS scroll-behavior property is as follows on CanIUse.
As you can see that this property is not browser compatible with all the major browsers, Surprisingly, the scroll-behavior property is poorly supported with Apple still not ready to incorporate this in their browsers. Scroll-behavior being an important property needs a turnaround method to implement in the browsers where it is not supported and help to build a website that works better across different browsers.
To ensure the compatibility of this property with any major browsers, you can perform browser compatibility testing with LambdaTest and ensure that the property works on the browser as intended. LambdaTest offers 3000+ real browsers and devices, you can perform live testing on these browsers to ensure compatibility of the scroll-behavior feature on the browsers you want to target. In case you want to read up more on browser compatibility testing of CSS writing mode, you can refer to our article on the topic.
In order to get better control over the smooth scroll and better cross browser support, you can opt for a smooth scroll with JS or Jquery method to come to the rescue.
Inspect web elements to help developers and testers to debug UI flaws or make modifications in HTML or CSS files. Learn how to inspect on MacBook
How To Create Smooth Scroll With JS?
Smooth scrolling can also be done through JavaScript and it gives better control over the functionalities. For example, through a smooth scroll with CSS, I can apply the scroll behavior only where the scroll event is built in to be triggered like while clicking the web links. But with JavaScript, I can decide when to scroll and how much to scroll i.e. the offset of the element. In this section, I have modified the same code which I wrote above but here I use a smooth scroll with JS for scrolling to the links. For this, the following built-in JavaScript function is used:
window.scrollTo();
This function can be declared for smooth scroll in JS in two ways:
window.scrollTo(x-coord, y-coord);
window.scrollTo(options)
The x-coord parameter defines the pixel value in the horizontal direction to which the page needs to be scrolled.
The y-coord parameter defines the pixel value in the vertical direction to which the page needs to be scrolled.
The options field depends on the developer. This field is a dictionary parameter that contains a set of options or parameters defining the characteristics of the smooth scroll with JS. To remember this as a stepwise process, we perform the following process to achieve smooth scrolling with JS:
Detect the element you want to connect scrolling to.
Define how much you want to scroll the page.
Trigger the scrolling property within the function.
If you remember these three steps, scrolling smoothly is a very easy part when it comes to the code. But, before taking reference from this code, ensure that you have deleted the following CSS line from the webpage given in the previous section code:
html {
scroll-behavior : smooth;
}
In the code given in the previous section, add the following code for smooth scroll in JS inside the page at any place:
<script>
const navlink = document.querySelectorAll(".navbar a");
navlink.forEach(elem => elem.addEventListener("click", smoothscroll));
function smoothscroll(event){
event.preventDefault();
const targetId = event.currentTarget.getAttribute("href");
window.scrollTo({
top: document.querySelector(targetId).offsetTop,
behavior: "smooth"
})
}
</script>
Now we can relate the code with the steps that I wrote above:
Detecting The Element:
const navlink = document.querySelectorAll(".navbar a");
navlink.forEach(elem => elem.addEventListener("click", smoothscroll));
In this code for smooth scroll with JS, I am selecting the elements with the class navbar and anchor tags that are within that class. Whenever you click such elements, a function will be triggered with the name smoothscroll.
This article explains the emulator vs simulator vs real device differences, the learning of which can help you select the right mobile testing solution for your business
Define How Much To Scroll:
top: document.querySelector(targetId).offsetTop,
In the function smoothscroll, I am defining the pixel value that needs to be scrolled. Since, this cannot be an absolute value, you can make use of the offsetTop function. So, this line returns the offset value for the element being referred to.
Trigger The Scrolling Property Within The function:
behavior: "smooth"
With this code, you can trigger the property behavior and set it’s value to “smooth”. This means that you want to scroll smoothly.
This code will generate the same results as from JavaScript.
So with this, are we done with our options of creating a smooth scroll in the page? Well, no! Apart from CSS and JavaScript, we still have another method, smooth scroll with JQuery.
Guide For Fixing Javascript Cross Browser Compatibility.
How To Create Smooth Scroll With JQuery?
Jquery is yet another method that gives us the liberty to implement smooth scrolling with even more control than JavaScript. Implementing a smooth scroll with Jquery allows us to control the time it should take to scroll to the target element. In other words, you can manage the speed of scrolling.
Before referring to the following code for a smooth scroll in Jquery, make sure you have no other code that influences the scrolling behavior of the web page.
Now perform live interactive jQuery mobile testing of your jQuery Mobile websites on LambdaTest.
<script>
$(document).ready(function(){
$(".navbar a").on('click', function(event) {
if (this.hash !== "") {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 1300, function(){
window.location.hash = hash;
});
}
});
});
</script>
Taking this snippet and connecting back to the steps I mentioned above, we get the following:
Detect The Element
$(".navbar a").on('click', function(event)
In this code, I am selecting all the anchor tags located within the class named navbar. For all such elements, a function will be triggered when they are clicked.
Define How Much To Scroll
scrollTop: $(hash).offset().top
}, 1300
The above code for smooth scroll in Jquery calculates the offset of the attribute with “hash” and returns the pixel value back.
The value 1300 refers to the time in milliseconds that I want the web page to take before reaching the target location i.e. window.location.hash
.
This code for smooth scroll in Jquery generates the following output:
Test your native, hybrid, and web apps across all legacy and latest mobile operating systems on the most powerful online Android emulator
Wrapping It Up!
Scroll-behavior is the property of the CSS that allows a page to scroll smoothly or abruptly when a link is clicked (although this can be extended to any element via JS). This can be achieved through three methods that are through direct styling in the CSS, through JavaScript, and through JQuery. Although there are tons of plugins that are available in JavaScript which can also be used for similar results. Deciding which way to go depends totally on the web developer and the requirements.
If Opera and Safari are not in your browser matrix and you don’t need more control over the scroll event, you can use the smooth scroll with the CSS method. But that is hardly the case. Every web developer wants to target a maximum audience and therefore I recommend using a smooth scroll with JS method, as it is simple and gives more control although smooth scroll with JQuery offers some more features on the plate.
You can use any of them as per your comfort level. Whatever the developer decides, it is always better to have a smooth scroll on your website. I have never seen a dissatisfied customer using the smooth-scroll property. So, it is better to learn than skip this property on your web page. Also, make sure that you perform cross browser testing over your browser matrix to ensure browser compatibility support of the feature.
If you have used something unique with scroll property, do comment below to help all the fellow developers learn and experiment more. I hope you liked this article on a smooth scroll with Jquery, JS, and CSS. Feel free to share this article with your peers on Twitter, LinkedIn, or any other social media of your choice. That’s all for now. Happy Testing!!!?