How does the position of the scroll affect the height of an element on a webpage

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?

Answer №1

  1. Avoid repeatedly calling getElementById inside the function by storing element references in variables. This will help reduce resource usage since constant DOM search is intensive.
  2. Instead of using .style.height to get an element's height, consider using .clientHeight for a more accurate measurement. However, keep in mind that reading from the DOM frequently can be resource-heavy. You may also try calculating the new height without relying on the actual element height.
  3. When setting the height with .style.height += y, ensure to include the appropriate CSS unit such as 10px rather than just a number like 10.

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

Utilize titles and hrefs for images in an array of objects

In my Canvas, there is a map as the background image with markers placed in different cities. These markers are images duplicated from an Array of Objects and added to the Canvas using drawImage(). Now, I need to include href and title attributes in these ...

Techniques for Shortening Dates in JavaScript

How can I abbreviate a full date in JavaScript? For example, converting 15 September 2020 to 15 SEP 20. I have arrays of dates that need this formatting. ...

Error: Preflight request returned a 405 HTTP status code when querying Ionic + CI backend

I am currently working on my first app using ionic with a codeigniter backend. However, I am encountering the "Response for preflight has invalid HTTP status code 405" issue in ionic + CI backend. Can anyone help me solve this problem? This is my controll ...

Having trouble with a malfunctioning JavaScript function? Need help resolving the issue?

My JavaScript code can be found at the following link: Link The function makewindows does not seem to be functioning properly. While it does create a window, the HTML content either shows as quoted text or if I use: child1.document.write(json_encode($ro ...

No specification has been provided for the delivery

I'm currently working with the Meteor framework and I am attempting to send an uploaded file (HTML input) from the client to the server using the npm package Delivery. Below is my code: Client side : var socket = io.connect('http://0.0.0.0 ...

Attempting to employ $set in conjunction with stringify, unfortunately without success

I am currently trying to utilize this function to edit a specific space in my MongoDB database. However, being new to this, I am struggling to understand what is going wrong. The error message "missing ) after argument list" keeps appearing. Any help and ...

Developing an interactive single-page website

My goal is to develop a PHP web application with an overlay container that features dynamic fields/forms. The idea is for users to fill out the form without being redirected from the main page they are on. Imagine being able to report a page error on a w ...

Leverage jscript and controller actions in MVC ASP.net to effectively insert new data into the database

I am looking to store data in a database from my MVC ASP.net project without the need to refresh the view page. My approach involves creating a string, sending it to the controller, and then pushing it to the database. I have already developed a function f ...

Graphql query using $http.post is unsuccessful

I successfully made a request for the code below, but I am encountering an issue where I am not receiving any data back. The "preview" tab of the request in Chrome simply displays "Error Not Found". Interestingly, when I try the same query in GraphiQL, i ...

"Menu bar showcasing various products and services in the

Is there a way to design a menu similar to the one on this website using bootstrap 4? https://i.sstatic.net/2wkck.jpg The menu layout features categories on the sidebar and collapses in mobile view. How can I achieve this with bootstrap 4? ...

Utilizing JavaScript to enable a Bootstrap 5 dropdown menu to open on hover for desktop users and be clickable for mobile users

I am currently using Bootstrap 5 to design a website and I'm facing an issue with creating a navbar dropdown. On desktop, I want the dropdown to open on hover and redirect the user to a new page when clicked. However, on mobile devices, I only want th ...

Toggling checkboxes using Angular framework

Within my form, there is a table with checkboxes in each column. The table consists of 3 <tr> elements, and each <tr> uses ng-repeate to call the webservice and display clone data (in JSON format). Upon clicking a checkbox, I create a JavaScrip ...

Achieving CSS centering with translate and avoiding content overflow

I have a code snippet for centering content both horizontally and vertically. It functions properly unless there is too much content, in which case it gets cut off. Is there a CSS solution to prevent this overflow issue without involving JavaScript? .b ...

Exploring the World of Audio Playback with R Shiny

For this question, I am incorporating the following libraries: library("shiny") library("tuneR") library("markdown") Although, it seems that only shiny is relevant in this context. According to the Shiny tag glossary, I should be able to utilize tags$a ...

Exploring NextJS with Typescript to utilize the getStaticProps method

I'm currently enrolled in a NextJS course and I am interested in using Typescript. While browsing through a GitHub discussion forum, I came across an issue that I don't quite understand. The first function provided below seems to be throwing an e ...

Create a standard chart with a colored map using Three.js

Recently, I dove into the world of Three.js and found myself on a mission to convert a color map into a normal map. My goal is to create a normal map similar to [image 2], based on the color map shown in [image 1]. Instead of simply uploading files, I wa ...

How to position a dropdown menu to the right of a textbox in a Bootstrap form

Seeking assistance with customizing my accordion. I have a flex-row textbox with icons on the right, and I want to incorporate a menu, as depicted in the image linked below: Accordion Image Below is the code snippet: <html> <head> <s ...

Learn the process of retrieving JSON objects through AJAX using jQuery

When making a jQuery call to an API website, I receive the results in JSON format: { "results":[ { "user":{ "gender":"female", "name":{ "title":"mrs", "first":"linda", "last":"diaz" }, ...

The JSON.stringify() function helps to convert data into a JSON-formatted string, avoiding any potential "c

connection.query( 'SELECT DeskName FROM desks WHERE stat = ?',["Booked"], function(err, rows){ if(err) { throw err; }else{ try{ var dataToParse = new Array(); dataToParse = rows; res.render('workspaces.html',{parsedArray : JS ...

What could be causing the width of a table row (tr) in a table element to not function properly, while the height is functioning as expected?

My code is as follows: .table1 { background-color: gray; display: flex; justify-content: ; align-items: ; height: 400px; margin-left: 40px; padding-left: ; } .table1 tr { background-color: blue; height: 50px; width: 50px; } <tabl ...