Skip to content

Instantly share code, notes, and snippets.

@etoxin
Created June 6, 2016 02:13
Show Gist options
  • Save etoxin/4a594c8f22a302c598ac91f4ced3f411 to your computer and use it in GitHub Desktop.
Save etoxin/4a594c8f22a302c598ac91f4ced3f411 to your computer and use it in GitHub Desktop.
Paralax
.parallax-window {
max-height: 30em;
overflow: hidden;
position: relative;
text-align: center;
width: 100%;
}
.parallax-static-content {
color: #9A9A8A;
padding: 8em 0;
position: relative;
z-index: 9;
}
.parallax-background {
background: url("https://raw.githubusercontent.com/thoughtbot/refills/master/source/images/mountains.png") repeat;
background-position: top;
background-size: cover;
background-color: beige;
height: 60em;
left: 0;
position: absolute;
top: -10em;
width: 100%;
}
<div id="js-parallax-window" class="parallax-window">
<div class="parallax-static-content">
<b>Parallax Window</b>
</div>
<div id="js-parallax-background" class="parallax-background"></div>
</div>
$(document).ready(function() {
if ($("#js-parallax-window").length) {
parallax();
}
});
$(window).scroll(function(e) {
if ($("#js-parallax-window").length) {
parallax();
}
});
function parallax(){
if( $("#js-parallax-window").length > 0 ) {
var plxBackground = $("#js-parallax-background");
var plxWindow = $("#js-parallax-window");
var plxWindowTopToPageTop = $(plxWindow).offset().top;
var windowTopToPageTop = $(window).scrollTop();
var plxWindowTopToWindowTop = plxWindowTopToPageTop - windowTopToPageTop;
var plxBackgroundTopToPageTop = $(plxBackground).offset().top;
var windowInnerHeight = window.innerHeight;
var plxBackgroundTopToWindowTop = plxBackgroundTopToPageTop - windowTopToPageTop;
var plxBackgroundTopToWindowBottom = windowInnerHeight - plxBackgroundTopToWindowTop;
var plxSpeed = 0.35;
plxBackground.css('top', - (plxWindowTopToWindowTop * plxSpeed) + 'px');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment