Scrolling animation practice
On the most recent episode of ShopTalk Show (episode 419), Chris Coyier mentioned a simple piece of JavaScript that can be used to create a custom CSS property that helps animate elements alongside scroll position. The article containing the JS is on CSStricks.com.
In this practice I used some code from this article about Scroll Animation from CSS Tricks.
View the code:
HTML and JS
<p>In this practice I used some code from <a href="https://css-tricks.com/books/greatest-css-tricks/scroll-animation/">this article about Scroll Animation</a> from CSS Tricks.</p>
<svg width="140" height="170" id="cat">
<title>cat</title>
<desc>Stick figure of a cat</desc>
<!-- Drawing start -->
<circle cx="70" cy="95" r="50" style="stroke: black; fill: none;" />
<circle cx="55" cy="80" r="5" stroke="none" fill="black" />
<circle cx="85" cy="80" r="5" stroke="none" fill="black" />
<g id="whiskers">
<line x1="75" y1="95" x2="135" y2="85" style="stroke: black;" />
<line x1="75" y1="95" x2="135" y2="105" style="stroke: black;" />
</g>
<use xlink:href="#whiskers" transform="scale(-1 1) translate(-140 0)" />
<!-- ears -->
<polyline points="108 62, 90 10, 70 45, 50, 10, 32, 62" style="stroke: black; fill: none;" />
<!-- mouth -->
<polyline points="35 110, 45 120, 95 120, 105 ,110" style="stroke: black; fill: none;"/>
<!-- nose -->
<path d="M 75 90 L 65 90 A 5 10 0 0 0 75 90" style="stroke: black; fill: #ffcccc;"/>
<!-- Drawing end-->
</svg>
<script>
window.addEventListener('scroll', () => {
document.body.style.setProperty('--scroll',window.pageYOffset / (document.body.offsetHeight - window.innerHeight));
}, false);
</script>
CSS
@keyframes grow {
from {transform: rotate(0deg); fill: transparent;}
to {transform: rotate(15deg); fill: white;}
}
svg {
position: fixed;
top: 50%;
left: 50%;
animation: grow 1s linear infinite;
animation-play-state: paused;
animation-delay: calc(var(--scroll) * -1s);
animation-iteration-count: 1;
animation-fill-mode: both;
}
#cat {
margin: 1rem auto;
padding: 1rem;
width: 140px;
height: 170px;
max-height: 170px;
max-width: 140px;
font-family: 'Helvetica', Arial, sans-serif;
}
#cat-text {
text-transform: uppercase;
}
:root * {
animation-play-state: paused;
animation-delay: calc(var(--scroll) * -1s);
animation-iteration-count: 1;
animation-fill-mode: both;
}