Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I decrease and increase height of div on scroll with JavaScript only?

JavaScript

var changeHeight = () => {
    let flag = 0;
    while(flag != 1) {
        size += 1;
        return size;
    }
    if(size == window.innerHeight/2){
        flag == 1;
    }
    
}
var size = 5;
document.body.style.height = "10000px";
const div = document.createElement("div");

div.style.width = "100%";
div.style.position = "fixed";
div.style.left = "0";
div.style.top = "0";
div.style.backgroundColor = "green";
document.body.appendChild(div);

window.addEventListener("scroll", changeHeight);
div.style.height = size + "px";

HTML

It’s empty with only <script src="script1.js"> </script> inside

What do I want to achieve?

I want to create stick to the top of the page object while scrolling which increases height until height == window.innerHeight/2 after this, scrolling should decrease it’s size.

My problem is that I cannot return size variable over the function, or is there something more wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

while is unnecesery in this case and you don’t have any code that will tell this element to decrease its size.

In this example given element will decrease and increase its size back and forth

let size = 5;
let flag = 0;

const step = 1;

const changeHeight = () => {
    if(size >= window.innerHeight / 2 && flag === 0){
        flag = 1;
    } else if (size <= 0 && flag === 1) {
        flag = 0;
    }

    div.style.height = `${flag ? size-=step : size+=step}px`;
}

document.body.style.height = "10000px";
const div = document.createElement("div");

div.style.width = "100%";
div.style.position = "fixed";
div.style.left = "0";
div.style.top = "0";
div.style.backgroundColor = "green";
document.body.appendChild(div);

window.addEventListener("scroll", changeHeight);
<html>
  <body>
  </body>
</html>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading