Scroll Position Determines Element Height - Question for Web

I am experimenting with the 'scroll' eventlistener on web to add some motion design to my projects. In this test project I am having a div element react to the user scrolling through the page.

My html code with element and script:

<div id="top_div" class="normal_height"></div>
<script src="js/scroll_top_element.js"></script>

In css I toggle between two classes to adjust the height of the div element through a certain 'click' point.

height: 10vh;

height: 25vh;

My Javascript code is the following: I am using a debounce function to filter out too much input to the UI Thread and to improve overall performance of the application.

function debounce(func, wait=10, immediate = true){

var timeout; 

//debounce is a higher order function and will return another function 
return function run_code() {
    var context = this;

    //arguments is local variable of a function, refers to all arguments 
    var args = arguments; 

    //variable later is a function
    var later = function(){
        timeout = null;

        //if it is not time zero, apply checkSlide function 
        if(!immediate) func.apply(context, args);

    var Callnow = immediate && !timeout;
    timeout = setTimeout(later, wait);
    if(Callnow) func.apply(context, args);

The next function listens to the scrolling on the screen and is supposed to do two things. First thing is to immediately adapt the element height when the user scrolls past the y mark set to 50. This functions correctly.

The second thing it is supposed to do is, when scrolling past the "click point y", to adapt the height of the element LINEAR TO THE SCROLLY PROPERTY OF THE WINDOW. I tried using "" and then adding up the "scrollY" property to have it expand with the scrolling on screen. But this does not function. I cannot add them up for some reason..

window.addEventListener('scroll', debounce(function(){

var y = window.scrollY;

if (y < 50){

    document.getElementById("top_div").className = "adapt_height";


else {

    document.getElementById("top_div").className = "normal_height";

    document.getElementById("top_div").style.height += y; 



Any suggestions?

1 answer

  • answered 2019-06-11 23:14 Argeento

    1. Move getElementById out of the function. Use variables to store elements references. Searching the DOM in every 10ms is resource intensive.
    2. .style.height doesnt return elements height, use .clientHeight istead. But again, reading from the DOM is resource intensive. Probably You can calc new height without the knowledge of actual element height.
    3. .style.height += y You must set the value with css unit e.g 10px not a 10