What is the best way to change the height of a div element as the user scrolls using JavaScript exclusively?

Coding with 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 Learning

There is little content, only

<script src="script1.js"> </script>
inside it.

What am I aiming for?

The objective is to make an element stick to the top of the page as the user scrolls, expanding in height until it reaches window.innerHeight/2. Once this limit is reached, the scrolling should reduce its size.

I'm encountering issues with returning the 'size' variable within the function. Could there be another error in my code?

Answer №1

Using a while loop is unnecessary in this scenario since there is no code to control the element's size decrease.

In this specific case, the element will continuously adjust its size, alternating between decreasing and increasing.

let size = 5;
let flag = 0;

const step = 1;

const changeSize = () => {
    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", changeSize);
<html>
  <body>
  </body>
</html>

Answer №2

let boxSize = 5;
let halfwayReached = false;

const adjustBoxHeight = () => {
    console.log("Current size of the box:", boxSize);
    
    if (boxSize <= window.innerHeight / 2 && !halfwayReached) halfwayReached = false;
    else halfwayReached = true;

    if (!halfwayReached) {
        // Increase the height of the box if it's less than or equal to half of the window inner height
        boxSize += 1;
        return boxSize;
    } else if (halfwayReached && boxSize > 5) {
        // Decrease the height of the box when it reaches the halfway point 
        boxSize -= 1;
        return boxSize;
    } else {
        // Reset back to original values
        halfwayReached = false;
        boxSize = 5;
        return boxSize;
    }
}

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

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

console.log("Window innerHeight:", window.innerHeight);

window.addEventListener("scroll", () => {
    box.style.height = adjustBoxHeight() + "px";
    console.log("Box size in event listener:", boxSize);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble getting data to send to node.js server using $.ajax post

Trying to convert a table date into an array and send it to the server side using Ajax post for the first time. Despite following all the suggestions in previous posts, I am still struggling. Utilizing body-parser to extract data on the server side. Any he ...

Spinning an SVG path with CSS3 in a circular motion from its central axis

I have a collection of SVG paths, and one of them is displayed below: <path id="GOL" class="st0" d="M37.5,430.5l-12.4-12.4v-13.3h-4.2c-7.2,0-13.9,2.5-18.7,7.5c-4.7,4.9-7.3,11.3-7.3,18.3 c0,7,2.6,13.5,7.3,18.3c4.8,5,11.4,7.6,18.6,7.6l4.2,0v-13.7L36. ...

Issue: 'node' is not being recognized when attempting to execute the file using the package.json script

Currently diving into the world of Node.js, I encountered an issue stating "node is not recognized as an internal or external command" whenever I attempt to start my project using either npm start or npm run start. Strangely enough, running node index.js ...

Does not work in Electron's Chrome environment, although it does work in Node's console

I've incorporated the npm package foreach-batch into my electron project. The package is properly installed and there are no issues related to a Cannot find module. var forEachBatch = require('foreach-batch') var stuff = [0,1,2,3,4,5,6,7,8, ...

Utilizing JQuery to Modify XML File Content

Looking to retrieve data from an XML file using jQuery and display it in a textbox? If you want changes made in the textbox to reflect back in the original XML file, there are ways to achieve this. Here is some code that can help: <html><head&g ...

"Bootstrap4 - Troubleshooting the Issue of Multiple Carousels Not Function

I attempted to incorporate 2 Bootstrap 4 carousels onto a single page, but encountered issues with the functionality. I utilized this code on my page, however, the last element in the carousel does not cycle correctly. There is a delay of 3 transactions be ...

What separates $(document).ready() from embedding a script at the end of the body tag?

Can you explain the distinction between running a JavaScript function during jQuery's $(document).ready() and embedding it in the HTML within script tags at the bottom of the body? Appreciate your insights, DLiKS ...

Ways to add extra dots to your listing style

Is there a CSS property or list style that can display an expanding list? For example: Order now for a discount! <ol style="list-style: none"> <li>* Available only for the first 12 months</li> <li>** Only for new customers ...

What is the proper method for setting up handlers in functional React components?

My knowledge of JavaScript tells me that there are three different ways to define functions. Let's take a look at them: 1. Declaration function handleEvent(e) {} 2. Assignment var handleEvent = function(e) {} 3. Arrow var handleEvent = (e) => ...

Ways to connect css file to ejs views in nodejs

Currently, I am tackling a beginner node.js server project. While I have successfully managed to render dynamic HTML using ejs templates, I seem to be facing difficulties when it comes to linking CSS styling to these templates. In an effort to address thi ...

The Node JS API remains unresponsive when the request parameters are increased, continuing to send multiple requests to the server without receiving

Using the API below returns nothing: http://localhost:6150/api/v1/simpleSurveyData/abc/:projectId/:startDate/:endDate/:visitMonth However, if I remove any of the four parameters or provide less than four parameters, and adjust the API route in Node.js acc ...

Stopping the interval in Vue before the component is destroyed

I am currently facing an issue with a countdown timer implemented on a component. The timer functions properly, however, I want it to stop counting down once the user navigates away from the page where the component is located. I have attempted to use cl ...

Storing each item in its own document within a Firebase collection

I have a feature where users input their sitemap and it generates all the links in the sitemap. How can I then store each of those links in separate documents within a specific collection on Firebase? Below is the current function used to set data in Fir ...

Tips for populating an HTML input with the value of a link element using JQuery

I have a form input that I want to populate with autocomplete suggestions from my database using Ajax. To style the list, I am using bootstrap 4, and I have opted to use the <a></a> tag instead of the <li></li> tag. This is because ...

Initiate playing HTML video upon user click

My current situation is quite straightforward. I have an HTML video that plays when I click a div with the class ".play". $('.play').click(function() { $('.video').get(0).paused ? $('.video').get(0).play() : $('.vide ...

Having trouble with jQuery.cookie saving my JSON data

Being new to jQuery and JSON, I find this situation quite frustrating as it seems pretty straightforward but still doesn't work for me. My ASP.NET MVC website is using AJAX (via jQuery) to load data. Everything works fine until this point. I'm ...

Issues with vertical repeating in CSS Sprites

Hey there, I'm currently working on implementing css sprites in my web application. The challenge I'm facing is that I have organized the background of my website vertically within a sprite image. Now, one specific portion of the sprite needs to ...

Leveraging Angular's capability to import files directly from the assets

I recently installed a library via npm and made some modifications to one of the modules. python.js If I delete the node_modules folder and run npm install, I am concerned that I will lose my changes. Is there a way to preserve these modifications by mov ...

Dropzone ceased functioning following the transition from version "4.2.0" to "5.7.0" while utilizing jquery version "3.3.1"

Currently, I am loading my libraries in the following way: <link href="~/lib/dropzone/dropzone.min.css" rel="stylesheet" /> <script src="~/lib/dropzone/dropzone.min.js"></script> <script src="~/Scripts/jquery-3.3.1.min.js"></sc ...

Optimal approach for handling large JSON files

I am in possession of a JSON file containing approximately 500 lines. I am hesitant to simply dump this JSON data into the end of my Node.JS file as it doesn't seem like the most efficient approach. What alternatives or best practices can be recommend ...