JSFiddle - React, Tailwind, and code Playground
by codecowboy
HTML
<div class="debug" id="direction"></div>
<div class="viewport" id="view">
<div class="parallax from-bottom" style="background-color: red; width: 99%; height: 99%;">
From Bottom
</div>
<div class="parallax from-left" style="background-color: blue; width: 33%; height: 33%;">
From Left
</div>
<div class="parallax from-right" style="background-color: green; width: 40%; height: 50%;">
From Right
</div>
<div class="parallax from-top" style="background-color: yellow; width: 99%; height: 99%;">
From Top
</div>
<div class="parallax from-bottom" style="background-color: purple; width: 99%; height: 99%;">
From Bottom
</div>
</div>
CSS
.debug {
z-index: 999999;
position: absolute;
top: 0px;
left: 0px;
width: auto;
height: auto;
background-color: white;
}
.viewport {
position: absolute;
top: 10%;
left: 10%;
width: 80%;
height: 80%;
overflow: hidden;
background-color: aqua;
margin: 0px;
padding: 0px;
}
.parallax {
z-index:-1;
position: absolute;
margin: 0px;
padding: 0px;
}
JavaScript
/*
initialize
*/
var scrollDown = false;
var scrollUp = false;
var scroll = 0;
var $view = $('#view');
var l = 0;
var t = 0;
var w = $view.width();
var h = $view.height();
$view.find('.parallax').each(function() {
var $moving = $(this);
// position the next moving correctly
if($moving.hasClass('from-left')) {
$moving.css('left', l - $moving.width());
} else if($moving.hasClass('from-right')) {
$moving.css('left', w);
} else if($moving.hasClass('from-top')) {
$moving.css('top', t - $moving.height());
} else if($moving.hasClass('from-bottom')) {
$moving.css('top', h);
}
// make sure moving is visible
$moving.css('z-index', 0);
});
var $moving = $view.find('.parallax:first');
$moving.css('z-index', 0);
/*
event handlers
*/
$(window).keydown(function(e) {
if(e.which == 37 || e.which == 38) {
// left or up
scrollDown = false;
scrollUp = true;;
} else if(e.which == 39 || e.which == 40) {
// right or down
scrollUp = false;
scrollDown = true;
}
});
$(window).keyup(function(e) {
if(e.which >= 37 && e.which <= 40) {
// left, up, right, down
scrollDown = false;
scrollUp = false;
}
});
var mousew = function(e) {
var d = 0;
if(!e) e = window.event;
if (e.wheelDelta) {
d = -e.wheelDelta/120;
} else if (e.detail) {
d = e.detail/3;
}
parallaxScroll(d);
}
if (window.addEventListener) {
window.addEventListener('DOMMouseScroll', mousew, false);
}
window.onmousewheel = document.onmousewheel = mousew;
/*
parallax loop display loop
*/
window.setInterval(function() {
if(scrollDown)
parallaxScroll(4);
else if(scrollUp)
parallaxScroll(-4);
}, 50);
function parallaxScroll(scroll) {
// current moving object
var ml = $moving.position().left;
var mt = $moving.position().top;
var mw = $moving.width();
var mh = $moving.height();
// calc velocity
...