Skip to content

Instantly share code, notes, and snippets.

@arnog
Created January 22, 2015 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arnog/202fe44b3da2c8f86dca to your computer and use it in GitHub Desktop.
Save arnog/202fe44b3da2c8f86dca to your computer and use it in GitHub Desktop.
Animate on scroll
#scroll-me
p SCROLL TO REVEAL…
p ⬇︎
img src="https://placeimg.com/1000/1000/nature" class="reveal-on-scroll" data-scrolled-out-class="slide-left"
// Return an array of elements matching a CSS selector
function $$(sel) {
return Array.prototype.slice.call(document.querySelectorAll(sel));
}
// Add an event handler to an element
function on(elt, event, handler) {
if (elt.addEventListener) {
// W3C DOM
elt.addEventListener(event, handler, false);
} else if (elt.attachEvent) {
// IE DOM
return elt.attachEvent(event === "load" ? "DOMContentLoaded" : ("on" + event), handler);
}
}
// Once the document is loaded, add the specified class to all elements that are to be revealed so they can be set in their initial (non-revealed) state
on(window, "load", function() {
$$(".reveal-on-scroll").forEach( function(e) {
e.classList.add(e.getAttribute("data-scrolled-out-class"));
});
});
// When the document is scrolled, if an element with the reveal-on-scroll class comes into view, removes its "scrolled-out-class", and add it back if it becomes out of view again.
on(document, "scroll", function() {
// window.pageYOffset works in all browsers >IE8
// document.body.scrollTop works in WebKit
// document.documentElement.scrollTop works in Firefox
var scrollTop = window.pageYOffset + window.innerHeight;
$$(".reveal-on-scroll").forEach( function(e) {
if ((e.offsetTop + e.offsetHeight / 2) < scrollTop) {
e.classList.remove(e.getAttribute("data-scrolled-out-class"));
} else {
e.classList.add(e.getAttribute("data-scrolled-out-class"));
}
});
});
// Specify a transition for when elements are brought into view
.reveal-on-scroll { transition: all .5s ease-in-out; }
//
// Set the data-scrolled-out-class attribute on the element to be revealed to "slide-left" or "transparent" depending on the "out of view" state you want the element to have.
//
// Class to "hide" an element by moving it offscreen on the left-hand side
.slide-left { transform: translate(-100vw, 0); }
// Class to "hide" an element by changing its opacity
.transparent { opacity: 0; }
#scroll-me {
margin: 0;
width: 1000px;
height: 1000px;
background: url(https://placeimg.com/1000/1000/nature/grayscale) no-repeat;
background-position: cover;
color: white;
font-size: 5em;
font-weight: 900;
text-shadow: 3px 3px 8px black;
text-align: center;
padding-top: 20%;
}
img { margin: 0; padding: 0; }
body { max-width: 1100px; margin: 0 auto; background: #333;}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment