JSFiddle - React, Tailwind, and code Playground
by Alma Grace
HTML
<div data-my-stuff="foobar" style="height:700px">
</div>
<div class="circle"></div>
<div class="square"></div>
<div data-my-stuff="foobar" style="height:700px">
</div>
CSS
body {
background-color:#000;
background-image:url(http://testcollectivator.com/images/stars.png), url(http://testcollectivator.com/images/stars.png), url(http://testcollectivator.com/images/stars.png);
background-position:100px 0, 0 100px, 250px 200px;
}
.circle {
width:100px;
height:100px;
display:block;
position:relative;;
top:0;left:0;
background-color:gold;
border-radius:100%;
-webkit-transition-duration:2s;
}
.circle.setting {
background-color:#f00;
}
.square {
width:50px;
height:50px;
border:5px solid #333;
position:fixed;
top:50%;
right:50px;
background-color:#f0f;
}
JavaScript
//josh jsfiddle-pasted by alma
// 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 + Math.sin(st / 50) * 20 + "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 - 300) {
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) * 55 + "%";
});
// 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");
});