DEV Community

Make a parallax effect with 10 lines of JavaScript

Ibrahima Ndaw on December 19, 2019

Originally posted on my blog In this post, we're going to make a nice Parallax effect with HTML, CSS and just 10 lines of JavaScript. You can c...
Collapse
 
alexparra profile image
Alex Parra

As a performance improvement, move the document.querySelector calls outside the scroll event listener, assigned to variables. That way, the browser only has to traverse the DOM once instead of on every scroll event which is what’s happening now. And then, look into throttle to limit the handler calls as scroll fires at a very high rate.
Best.

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

You're absolutely right. I always use selectors in that way. For a real apps, i should control the scroll with a debounce function, but for this quick may be it's not mandatory. So thanks again for your very useful comment.

Collapse
 
darkain profile image
Vincent Milum Jr

Just as an FYI for anyone reading. As a reminder, these types of things are basically an anti-pattern for UX and accessibility. They may be fancy and pretty at face value, but suffer issues in different user agents and for screen readers. These tend to suffer even more when transitioning between touch, mouse wheel, mouse drag, scroll bar, arrow keys, and page up/down keys. And that's before even getting into javascriptless browsing.

Collapse
 
miclgael profile image
Michael Gale

Nice one!

See also: this trick with perspective and translateZ properties

alligator.io/css/pure-css-parallax/

Collapse
 
anwar_nairi profile image
Anwar

On fire!

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

Thanks for sharing your resource.

Collapse
 
mahmoudibrahiam profile image
Mahmoud Ibrahiam

Can I share it on my blog?

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

Yes of course you can.

Collapse
 
iquirino profile image
Igor Quirino

What about thousand lines of css? ^
Nice article!

Thread Thread
 
mahmoudibrahiam profile image
Mahmoud Ibrahiam

where ??

Collapse
 
mahmoudibrahiam profile image
Mahmoud Ibrahiam • Edited

Thank you, Mr Ibrahima

Collapse
 
youkero profile image
youkero

If you reduce the height of the window, you can scroll forever 😁

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

It's not that much responsive, i will soon.

Collapse
 
shroom2020 profile image
Shroom2020

This effect doesn't look that good. However, strip away the parts that degrade user experience, and it's an excellent base for a stunning parallax effect.