I’ve been working on a really cool site that requires a lot of custom animations on a one page smooth scrolling site. Being the CSS lover I am, most of these are done via CSS3, however they wanted certain panels to have text fade in or slide over when the user scrolled down to it. Nikita and I sat down together to write a quick little script to do just that. Thought I would share it with you – you can see the demo (for the next week or so) here: https://amberweinberg.com/clients/cominds/
We’ll be taking an h1 and a p element and scrolling the first from the left and the second from the right when the user scrolls down enough for the section to hit the top of their browser. The section has an id of #story.
The HTML:
<section id="story">
<h1>The title here</h1>
<p>The paragraph text here</p>
</section>
The CSS:
#story h1 { bottom: 0; right: -100%; }
#story p { left: -100%; line-height: 1; }
#story h1, #story p { display: block; opacity: 0; position: absolute; -webkit-transition: all 2s ease; -moz-transition: all 2s ease; transition: all 2s ease; }
#story .scrolled { opacity: 1; }
#story h1.scrolled { right: 0; }
#story p.scrolled { left: 0; }
The JS:
$(window).scroll(function() {
var scrollTop = $(window).scrollTop();
var elementTop = $('#story').offset().top;
if(scrollTop >= elementTop) {
$('#story h1').addClass('scrolled');
$('#story p').addClass('scrolled');
}
});
By changing the CSS around, you can effect different animations. Instead of scrolling across the page, if you remove the absolute positioning, you can simply make it fade in or out.
Easy!