// First, let's bind the 'scroll' event so that it runs our parallax
window.addEventListener("scroll", function () {
// We'll be using this scrollTop value a lot, so let's bind it
var st = document.body.scrollTop;
// Let's add a little sun
var sun = document.querySelector(".circle");
// and a mysterious box for some reason
var box = document.querySelector(".square");
// Then, simply update the style so that the backgroundPosition is calculated based on it
document.body.style.backgroundPosition =
// Let's make this bottom background fancy, and wave it back and forth as a sine wave
100 + 20 * Math.sin(st / 50) + "px 0," +
// We'll make these next two scroll at slightly different speeds
"0 " + Math.floor(100 + st * 1.5) + "px," +
"250px " + Math.floor(200 + st * 2) + "px";
/* There are much better, more flexible ways you can use this. Don't just update the background positions, but have multiple elements on your page that can move about. You could even change the scrolling pattern if you used something like this:
if(st > document.querySelector(".some_cool_looking_element").offsetTop + 100) {
// Start doing something once your element is 100px on the screen
}
*/
// Let's have the sun slide from the left once it's 200px on the screen
if (st > sun.offsetTop - 200) {
sun.style.marginLeft = st - 500 + "px";
}
// This box is fixed position, so we can make it bounce up and down
box.style.top = 50 + Math.sin(st/40) * 45 + "%";
});
// Even though we're updating it from the 'scroll' event, we can still apply events to it here.
document.querySelector(".circle").addEventListener("mouseenter", function () {
this.classList.add("setting");
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.