Simple parallax background image on a header
A work in progress. I'm still not happy with this, but getting there
Using a little CSS and a small snippet of vanilla JavaScript to emulate the header background used on LinkedIn.
This is a demo of a parallax header image, below a navigation block, followed by a local navigation block and content. As used on the Tesco 2016 Mother's Day page.
Core method is an extension of Sticky header. Using CSS transforms and a little script. Not too sure about the debounce method used, will see how it performs.
Mark up
<header id=hero class=hero>
<div id=hero_bg class="hero-bg img-bg" data-src="digital-tunnel.jpg"><div></div></div>
<div id=hero_copy class=hero-copy>
<h1>Heading</h1>
<p>Copy</p>
</div>
</header>
CSS
The image is set as a background on .hero-bg
and placed via position : absolute
so even without JavaScript support the image displays. Once the script kicks in it adds the class .hero_fixed
to change to position : fixed
WIP - See demo source…
JavaScript
Requires detect CSS transform3d
browser support.
Three id's and two class names are hard coded, but may be easily externalised.
var ParallaxHeader = (function () {
"use strict";
var hero = document.getElementById("hero"),
hero_bg = document.getElementById("hero_bg"),
hero_copy = document.getElementById("hero_copy"),
lastScrollTop = -1;
The _redrawLoop function loops continuously, without the more usual setTimeout
or setInterval
. By using requestAnimationFrame
instead much faster, and smoother, animations are possible.
Note: obj.style
is more performant than obj.setAttribute("style", ...)
.
var _redrawLoop = function () {
WIP - See demo source…
};
The _setVars
function is called on initialisation and when the window is resized. It adjusts the height of the background image to suit header dimensions.
A little extra height is required to ensure there's no body background bleed-through when scrolling extremely quickly. With the figures used allow the background to overscan the header by approximately 23%. Set to 10% above and 13% below.
Note: offsetHeight
is more performant than getBoundingClientRect()
.
var _setVars = function () {
WIP - See demo source…
};
A check to ensure transform3d
support before initialisation. Please note the resize event listener would be better served debounced
when used in full production, a little beyond scope here.
WIP - See demo source…
}());
Google compiled parallax header
WIP - See demo source…
Social links and email client: