JSFiddle - React, Tailwind, and code Playground
by klarstil
HTML
<link rel="stylesheet" href="http://necolas.github.io/normalize.css/2.1.2/normalize.css">
<ul class="parallax-container">
<li class="parallax-entry" data-align="left"></li>
<li class="parallax-entry" data-align="right" data-speed="0.2"></li>
</ul>
CSS
body, html {
color: #3c3c3c;
}
.parallax-container {
width: 400px;
height: 600px;
border: 1px solid #000;
position: relative;
overflow: hidden;
padding: 0; margin: 20px;
}
.parallax-container > li {
list-style: none;
}
.parallax-entry {
position: absolute;
width: 350px;
height: 200px;
}
.parallax-entry:first-child {
background: #f00;
left: 0px;
top: 0px;
}
.parallax-entry:last-child {
background: #00f;
top: 220px;
right: 10px;
width: 30px;
height: 30px;
}
JavaScript
;(function($, window, undefined) {
var pluginName = 'parallax',
defaults = {
};
function Plugin( element, options ) {
this.element = element;
this.$el = $(element);
this.width = this.$el.outerWidth();
this.entries = this.$el.find('li');
this.options = $.extend( {}, defaults, options);
this.zIndexStack = 0;
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype.init = function() {
var me = this, alignment = 'marginLeft';
$.each(me.entries, function(i, el) {
el = $(el);
el.css('zIndex', ++me.zIndexStack);
if(el.attr('data-align') && el.attr('data-align') === 'right') {
alignment = 'marginRight';
}
el.css(alignment, el.css((alignment === 'marginLeft') ? 'left' : 'right'));
});
me.$el.on('mousemove', $.proxy(me.onMouseMove, me));
};
Plugin.prototype.onMouseMove = function(event) {
var me = this,
offset = me.$el.offset(),
left = event.pageX - offset.left,
alignment = 'left';
if(me._timer) {
window.clearTimeout(me._timer);
}
me._timer = window.setTimeout(function() {
$.each(me.entries, function(i, el) {
el = $(el);
var movement = (left / me.width) * 100,
elWidth = (el.outerWidth() / me.width) * 100,
max = 100 - elWidth, speed = parseFloat(el.attr('data-speed')) || 1;
if(el.attr('data-align') && el.attr('data-align') === 'right') {
alignment = 'right';
movement = (left / (me.width - el.outerWidth())) * 100;
}
movement = movement * speed;
if(max < movement) {
...