JSFiddle - React, Tailwind, and code Playground
by al nmeri
HTML
<div id="main">
<header id="header">Header</header>
<nav id="nav">Nav</nav>
</div>
<div id="flyInDiv">
Flying in!
</div>
CSS
#main {
/* Making sure the div scrolls so that the demo will work */
height: 5000px;
}
#header {
height: 90px;
background: lightgreen;
}
#nav {
width: 100%;
height: 40px;
background: lightblue;
color: purple;
}
#nav.is-sticky {
position: fixed;
top: 0;
border-bottom: 3px solid rgb(157,0,53)
}
#flyInDiv {
width: 100px;
height: 100px;
background: red;
position: fixed;
right: 0;
top: 50%;
margin-top: -50px;
transform: translateX(100px);
}
#flyInDiv.is-sticky {
transition: transform 1s ease;
transform: translateX(0);
}
JavaScript
var navigation = document.getElementById('nav');
var flyingDiv = document.getElementById('flyInDiv');
var borderBottom = navigation.getAttribute('border-bottom');
// The flying div isn't visible until the user has scrolled
var flyingDivIsVisible = false;
function scrollAnimations() {
// Find out what the current scroll position is.
// We need to keep doing this every time we hear a scroll event,
// because every time that happens, it means the scroll position
// has changed!
var currentDistance = document.body.scrollTop;
// If we've scrolled 90px down, add a class containing our 'sticky' styles.
// If not, remove the class.
if (currentDistance > 90) {
navigation.className = 'is-sticky';
} else {
navigation.className = '';
}
// If the flying div isn't visible, let's make it visible!
// However, if it's already visible, the code below won't run.
if (!flyingDivIsVisible) {
flyingDiv.className = 'is-sticky';
flyingDivIsVisible = true;
}
}
// Add an event listener to listen for scrolling on the window.
// Every time a user scrolls, the callback function will fire.
window.addEventListener('scroll', scrollAnimations);