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

The background color of the active tab is updated upon loading the page

I have attempted to modify this code to change the background color of li tag on click. It successfully changes the background color when hovering or clicking, but unfortunately reverts back to the default color upon page refresh. I am looking for a soluti ...

Error Alert - Troubleshooting AJAX JSON Parsing Issue

I've encountered a problem with AJAX that involves parsing a JSON Array from a webservice I am developing. The front-end of my project uses a simple combination of ajax and jQuery to showcase the results retrieved from the webservice. Despite being c ...

Prevent the ability to drag and drop within specific div elements

Having trouble disabling the sortable function when the ui ID is set to "comp". Can't figure out what's going wrong, hoping for some assistance here. $(".sort").sortable({ // start sortable connectWith: ".sort", receive: function ...

Fetch additional data from a table by utilizing Ajax and PHP

I have 7 data entries in my database When attempting to load the data from a table using ajax and php, I encountered an issue. After clicking the "load more" button, the data displays successfully but the "load more" button disappears. Here is my index. ...

Mishandling of string interpretation

I'm having trouble converting ANSI color codes from console output into HTML. While I discovered a script that can handle this task, I am struggling to make it parse the strings within node js properly. Even when I attempted to JSON.stringify it to in ...

How can you toggle the visibility of a text based on the selection of a jQuery radio button?

Is it possible to dynamically enable or disable a field based on the selection of a radio button? Here are the rules: The field should only be active when the "Inactive" radio button is selected Check out the code snippet below for reference: Radio B ...

Troubleshooting: When Angular Fade In Out Animation Won't Work

Looking to create a simple animation with the angular animation package The goal is to smoothly transition from opacity 0 to opacity 1 for a fade effect. I've had success with other properties like height and display, but struggling with opacity. H ...

Crop and resize a portion of an image using CSS

Is there a way to display just part of an image on a webpage and scale that specific area either larger or smaller using CSS? A common method is by using the following code: $("#myDiv").css({ width: 100, height: 100, background: "url('myurl.jpg ...

The GitHub Pages website is not displaying exactly like it does when running locally with a live server

Currently in the process of creating a compact website where users can input an anagram and receive all potential words that can be formed from it. Additionally, upon receiving these words, there is an option to click on one for its definitions. The site ...

Working with time durations in JavaScript

Is there a way to calculate the duration between a start time and an end time including both hours and minutes? Currently, I have code that only provides me with the hours. Is there any modification I can make to include minutes as well? If so, what chan ...

Using a PHP variable as the input for the img src attribute in HTML

I am currently working on a project that involves creating a gallery to showcase all the .jpg files from a specific local directory. However, I seem to be encountering some issues with it. <?php $directory = "img/"; $images = glob ...

Bidirectional binding of attributes in an Angular directive

I have developed a custom Angular Directive known as evoEventMirror. Its main purpose is to attach a jQuery event to an inserted element and apply a specified CSS style to the "root" element. Refer to the example below: <div id="#mydiv" evo-event-mirro ...

Creating an Elastic Beanstalk instance from an s3 bucket using the aws-sdk tutorial

I am currently facing some difficulties in deploying an elastic beanstalk instance using the AWS JavaScript SDK. My goal is to have the source code come from an S3 bucket. While I know this can be done through the web interface, I am struggling to figure o ...

Definition of Angular 2 File

I have developed a custom Gantt chart library using D3 in vanilla JavaScript. Now, I am trying to integrate it into my Angular 2 application. After installing D3 via npm and adding the necessary type files and the Gantt chart module to node_modules, I enco ...

Guide to making a button in jQuery that triggers a function with arguments

I've been working on creating a button in jQuery with an onClick event that calls a function and passes some parameters. Here's what I have tried so far: let userArray = []; userArray['recipient_name'] = recipient_name.value; userArray[ ...

Issue with tile size or alignment in Safari

Recently, while creating my portfolio on CodePen, everything was running smoothly except for one little hiccup - Safari. http://codepen.io/tpalmer75/pen/FijEh (SASS for just one .item element) .item width: calc(100% / 3) display: inline-block height ...

Triggering a re-render in React

There are times when I find myself needing to trigger a re-render while still in the middle of executing a function. As a solution, I've developed a method using the state variable my_force_update. Basically, I change it to a random value when I want ...

Switch the display of a div within a ng-template loop using PrimeNg

Working with the PrimeNg picklist, I have encountered a challenge. Here's what's going on: The main focus is on the first row, while the other rows do not have radio buttons (as they are part of incomplete test data). The goal is to show a drop ...

"Encountering a problem with posting API requests using Express

I've encountered a problem where I keep receiving a 404 error when trying to post to a specific route. Here's the code snippet: app.js (code snippet for app.js) .... module.exports = app; api.js (code snippet for api.js) .... module.export ...

Problem encountered with PDFKit plugin regarding Arabic text rendering

When it comes to generating dynamic PDF files, I rely on the PDFKit library. The generation process is smooth, but I'm encountering difficulties with displaying Arabic characters even after installing an Arabic font. Additionally, although the Arabic ...