Reputation: 300
Hi all I have a div in a project that has display=none
until it reaches a certain scroll position then it changes to display=block
.
This works and is great, whats not so great is the abruptness of the change. I'd like to find a way for it to ease in to view over, say, 50px.
The div I am looking to do this with has this structure
<div class=section id=anchoredCtaWeb>
<div class=container>
<h1>Hello World</h1>
</div>
</div>
This is the style and JS I have applied to it currently
<style>
#anchoredCtaWeb {
display: none;
position: sticky;
top: 0px;
}
</style>
<script>
document.addEventListener("scroll", function() {
if (window.pageYOffset > 817)
document.getElementById('anchoredCtaWeb').style.display = "block";
if (window.pageYOffset < 817)
document.getElementById('anchoredCtaWeb').style.display = "none";
});
</script>
I know the way its acting is exactly what I've written but I have been unsuccessful with transitioning the height from 0px to its full height.
I really appreciate any feedback, thanks!
Upvotes: 2
Views: 3693
Reputation: 3921
You can do so by adding a class
to #anchoredCtaWeb
on scroll.
document.addEventListener("scroll", function() {
const anchoredCtaWeb = document.getElementById("anchoredCtaWeb");
if (window.pageYOffset > 817) {
anchoredCtaWeb.classList.add("show");
}
if (window.pageYOffset < 817) {
anchoredCtaWeb.classList.remove("show");
}
});
body {
height: 600vh;
}
#anchoredCtaWeb {
position: sticky;
transform: translateY(50px);
opacity: 0;
visibility: hidden;
top: 10px;
}
#anchoredCtaWeb.show {
transform: translateY(0px);
opacity: 1;
visibility: visible;
transition: 0.5s ease-in-out;
}
<div class="section" id="anchoredCtaWeb">
<div class="container">
<h1>Hello World</h1>
</div>
</div>
Check it in action on Codepen: https://codepen.io/manaskhandelwal1/pen/yLVOMPE
Upvotes: 2