Currently, I'm exploring the 'scroll' eventlistener in web development to incorporate some motion design elements into my projects. For this particular experiment, I am making a div element react to the user's scrolling actions on the page.
Here is a snippet of my HTML code containing the element and script:
<div id="top_div" class="normal_height"></div>
<script src="js/scroll_top_element.js"></script>
In my CSS, I switch between two classes to adjust the height of the div element based on a specific 'click' point.
.adapt_height{
height: 10vh;
}
.normal_height{
height: 25vh;
}
The Javascript code I've written involves using a debounce function to optimize performance by filtering excessive input to the UI Thread.
function debounce(func, wait=10, immediate = true){
var timeout;
return function run_code() {
var context = this;
var args = arguments;
var later = function(){
timeout = null;
if(!immediate) func.apply(context, args);
};
var Callnow = immediate &&!timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if(Callnow) func.apply(context, args);
}
}
The subsequent function tracks the scrolling behavior on the screen with the goal of achieving two outcomes. The first task successfully adjusts the element height immediately when the user scrolls beyond the defined y mark of 50. However, the second objective, which aims to dynamically adapt the element's height linearly in relation to the window's scrollY property, presents a challenge. I attempted to manipulate "element.style.height" and add the "scrollY" property to achieve the desired effect but encountered difficulties in combining them effectively.
window.addEventListener('scroll', debounce(function(){
var y = window.scrollY;
console.log(y);
if (y < 50){
document.getElementById("top_div").className = "adapt_height";
console.log(document.getElementById("top_div").className);
}
else {
document.getElementById("top_div").className = "normal_height";
document.getElementById("top_div").style.height += y;
console.log(document.getElementById("top_div").clientHeight);
}
}));
Any insights or suggestions on how to address this issue?