I'm working on a site which requires a parallax effect. Nothing to fancy.
What I want to achieve is something similar to this - middle of the page. Observe the scrolling speed, it's..."buttery smooth". So to speak.
What I have is similar, except the scrolling speed, I can't seem to get it. Fiddle.
CSS:
section.module.parallax {
height: 200px;
background-position: 50% 50%;
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
}
section.module.parallax-1 {
background-image: url("http://wearefetch.com/wp-content/uploads/2014/07/3.jpg");
}
.up{
width: 100%;
height: 400px;
background-color: red;
}
.down{
width: 100%;
height: 400px;
background-color: blue;
}
HTML:
<div class="up"></div>
<section class="module parallax parallax-1">
<div class="container"></div>
</section>
<div class="down"></div>
I tried using the data-speed
in another fiddle. But it doesn't seem to make much of a difference.
The code is exactly the same as the first Fiddle except for some added javascript, and of course the data-speed
, which is set to 10.
$(document).ready(function () {
$('section[data-type="background"]').each(function () {
var $bgobj = $(this);
$(window).scroll(function () {
var yPos = ($(window).scrollTop() / $bgobj.data('speed'));
var coords = '50% ' + yPos + 'px';
$bgobj.css({
backgroundPosition: coords
});
});
});
});
I'm not a front-end guy so, although, I'm sure this is probably something simple, I can't seem to make it work.
Any nudging in the right direction is greatly appreciated.
The Parallax effect visually appears if you set the background to a different (slower) speed than the scrolling.
The vertical Scrollbar as a viewpoint moves up and down, the background image represents a object in the distance and moves more slowly than closer objects like a text above that background.
The Fiddle of this question is a good starting point.
The Fiddle handles scroll events and "parallax" through the setting of the backgroundPosition
property of a fixed background image.
Demo Markup (css inline only for example):
<div id="parallax" style="background-position: 50% 0;background-repeat: no-repeat;background-attachment: fixed;background-image: url('http://lorempixel.com/1400/700');">Text in Front appears closer and moves faster</div>
The Javascript:
(function ($) {
"use strict";
var $el = $('#parallax');
// scroll callback
$(window).scroll(function () {
updateBackground($el);
});
updateBackground($el);
});
}(jQuery));
var speed = 0.4;
function updateBackground($el) {
var diff = $(window).scrollTop() - $el.offset().top;
var yPos = -(diff * speed);
var coords = '50% ' + yPos + 'px';
$el.css({
backgroundPosition: coords
});
}