Parallax Scroll in 5 Lines of jQuery

Posted 3 years ago     10378      jQuery parallax scrolling
15

Simple start to a parallax scrolling jQuery function (feel free to improve and link in the comments!):

jQuery


$.fn.parallax = function(strength) { var scroll_top = $(window).scrollTop(); var move_value = Math.round(scroll_top * strength); this.css('background-position', '0 -'+ move_value +'px'); };

CSS


.one, .two, .three { width: 450px; height: 250px; } .one { background: url('http://lorempixel.com/output/cats-h-c-450-500-6.jpg') no-repeat; } .two { background: url('http://lorempixel.com/output/cats-h-c-450-500-7.jpg') no-repeat; } .three { background: url('http://lorempixel.com/output/cats-h-c-450-500-1.jpg') no-repeat; }

HTML


<div class="one"></div> <div class="two"></div> <div class="three"></div>

How to Use


$(window).on('scroll', function() { $('.one').parallax(0.5); $('.two').parallax(0.6); $('.three').parallax(0.2); });

Comments

adc

I'm totally going to try this @enijar. Thanks for sharing. I wonder if I could tweak this into an angular js flavor...



Background-position-x and background-position-y don't work in Firefox as they are not CSS3 elements. Try using this instead:

this.css('background-position', '0 -'+ move_value +'px');


@jonathan-bird Updated, thanks for your comment.



Thanks.
*Please update jsfiddle bg images.



Seems interesting, but all images on the example are broken.



@jonathan-bird Any suggestion on how could I set the background-position-x to centered (or anything different than 0)?



Images fixed here: http://jsfiddle.net/Tek57/59/



You need to be logged in to post comments.



Welcome to Snippet Repo!

Discover, share and save useful code snippets.

Join our community over over 2,000 members! Currently a 48% acceptance rate. Apply for membership →