My goal is to create a transition effect when an element becomes sticky on the page. However, I am facing issues with the current code that I have.
const content = document.querySelector('.contents');
const initalPos = content.offsetTop;
window.addEventListener("scroll", () => {
if(content.offsetTop > initalPos) {
content.classList.add('stuck');
} else {
content.classList.remove('stuck');
}
});
body {
height: 300vh;
}
.contents {
margin-top: 50px;
border: 1px solid black;
position: sticky;
top: 0;
transition: height 3s;
}
.stuck {
height: 100px;
background-color: green;
}
<div class="contents">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</div>
I believe there might be something missing in correctly applying the CSS transition, can you help me identify what it is?