Introduction #
Animations are part of websites nowadays. They’re everywhere, and for a good reason: they enhance the user experience.
With the current state of JavaScript and CSS, it’s very easy to add scrolling animations.
Let’s take a look at how to implement it on your website.
Implementation using JavaScript #
In JavaScript, there are basically two ways to scroll on a webpage:
- Using
scrollTo(x, y)
- which scrolls to the given position. -
Using
scrollBy(x, y)
- which scrolls by the given amount of pixels.
Both methods can be used on a window
or on an HTML element obtained from a
method like document.querySelector()
.
The “trick” to implement a smoothed scrolling is to pass an object instead of the
x
and y
parameters, with the arguments
top
instead of y
, left
instead of x
,
and behavior
with the value smooth
to finally add the effect.
Here is an example:
window.scrollTo({
left: 0,
top: 100,
behavior: "smooth",
})
In this example, the browser will scroll to 100 pixels relative to the top of the page starting from your current position, with a smooth effect.
Implementation using CSS #
CSS has implemented a really useful property: you can add smooth scrolling with a single line of CSS, and you can even decide which element to apply it to - either globally or on individual elements.
This property is called scroll-behavior.
Enough talking - let’s get to the practical part.
Apply the effect to an entire website #
html {
scroll-behavior: smooth;
}
Nothing more, nothing less.
Apply the effect to a specific part of the website #
.my-selector-with-scrolling {
scroll-behavior: smooth;
}
Yeah, I know - only the selector changed 😁
By doing this, the effect is applied only to the specified element.
Does the CSS property affect JavaScript functions? #
Exactly! If you’ve applied the CSS property, then you don’t need to specify the smooth behavior on the JavaScript side.
The choice is yours 😉