Determine the vertical distance that a div element is currently visible while scrolling

To better understand this concept, please refer to the following fiddle: http://jsfiddle.net/abhicodes/LasxP/

The main goal here is to calculate the visible height of the element with the ID #content-wrapper as the user scrolls. The height of the header (#header) remains constant and fixed, but the footer height varies across different pages, making it impossible to use the current footer height as a standard measurement.

Even when scrolling to the end of the page where the footer occupies most of the area, we still need to determine the visible portion of #content-wrapper. In cases where the footer is not visible, subtracting the header height from the viewport height gives us the visible part of the content.

For example, if the viewport height at the bottom of the page is 600px, with the footer taking up 100px and the header 80px, the visible height of #content-wrapper would be 420px. Conversely, at the top of the page where only the header is present, the visible area of #content-wrapper would be 520px.

In essence, what we aim to achieve is dynamically determining the visible height of #content-wrapper for the user during any given scroll based on the scenario presented in the aforementioned fiddle.

Answer №1

Give it a shot

var $win = $(window);
var $footer = $("#footer");
$(window).scroll(function(){
    var windowHeight = $win.height();
    var footerTop = $footer.offset().top - $win.scrollTop();
    var visibleHeight = Math.min(windowHeight, footerTop) - 80;
    console.log(windowHeight +", " + footerTop + ", " + visibleHeight);
});

Check out the updated jsfiddle here.


The concept is straightforward.

  1. Determine window's height before the footer appears.
  2. Calculate footer's top position after it becomes visible.
  3. [1] or [2] - subtract header's height to find your solution.

Answer №2

Utilizing this code will determine the visible height on a webpage and organizes the variables for easier calculation:

$(document).on('scroll', function() {
    //Container
    var cont = $("#content-container");

    //Scroll Position (changes with scrolling)
    var pageTop = $(document).scrollTop();
    //Visible Page Size (constant)
    var pageSize = $(window).height();

    //Header Height (constant)
    var headerHeight = $('#header').height();

    //Content top (constant)
    var contTop = cont.offset().top;
    //Content top position (changes with scrolling)
    var contTopPos = contTop - pageTop;
    //Content bottom (constant)
    var contBottom =  cont.height() + contTop;
    //Content position in relation to screen top (changes with scrolling)
    var contBottomPos = contBottom - pageTop;

    /*
        VISIBLE AREA
        Take the size of screen/page, unless the bottom of the content further up
            and subtract from it
        The header height, unless the top of the content is below the header
    */
    var visibleArea = Math.min(pageSize, contBottomPos) - Math.max( headerHeight, contTopPos);
});

For an example, visit: http://jsfiddle.net/asifrc/LasxP/8/

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

Transfer a GET parameter from the URL to a .js file, then pass it from the .js file to a

Hey there, I'm currently using a JavaScript file to populate my HTML page with dynamic data. The JS file makes a call to a PHP file, which then fetches information from my SQL database and echoes it as json_encode to populate the HTML page. The issue ...

Error: The function pathRegexp is not defined

While attempting to conduct tests on my project with jest, I encountered an error code that seems unrelated to the actual testing process. It appears to be more of a dependency or Node Express compatibility issue. `● Test suite failed to run TypeError: ...

My jQuery AJAX request is not successfully communicating with my PHP script

I am not well-versed in AJAX (or jQuery), but I believed my task was fairly straightforward. However, when attempting to send an AJAX request using: $.ajax( requestObj ); it seems to fail, and I am seeking assistance. To provide context, here is how the ...

Combining jQuery dataTables and Codeigniter for dynamic rendering using sAjaxSource

I am currently facing an issue while working with dataTables in Codeigniter. I keep encountering the following error message: array_push() expects parameter 1 to be array, null given The resulting output is {"aaData":null} My desired outcome should look ...

Several buttons converging towards a single circle

https://i.sstatic.net/NyHXu.png I attempted to create a circular layout using 6 buttons, but the end result did not form a perfect circle as intended. In the image provided, I highlighted the areas of concern in red. Below, you will find my HTML and CSS c ...

Is it possible to conceal my Sticky Div in MUI5 once I've scrolled to the bottom of the parent div?

Sample link to see the demonstration: https://stackblitz.com/edit/react-5xt9r5?file=demo.tsx I am looking for a way to conceal a fixed div once I reach the bottom of its parent container while scrolling down. Below is a snippet illustrating how I struct ...

How to create a fresh factory instance in Angular Js

I have implemented a factory in my application to retrieve a list of folders and display it on the front end. Additionally, I have a form on the front end where users can add new folders to the existing list. After adding a folder, I need to refresh my fac ...

Tips for concealing a column within a jqgrid subgrid

Is there a way to conceal a column within a subgrid? Many thanks! ...

How can I incorporate a new object into an existing object in ReactJS?

I am facing an issue where I have an object named waA that is required in the final step. However, in ReactJS, the new object is not updating the previous object using a switch statement in a function. Below is the code for the object: waA = { jso ...

IDEA 2021.2 NPM SCRIPTS: Looks like there are no scripts available

Searching through the npm scripts, I am unable to locate any, however package.json does contain: ...

Utilize CountUp.js to generate a dynamic timer for tracking days and hours

I am looking to create a unique counter similar to the one featured on this website https://inorganik.github.io/countUp.js/ that counts up to a specific number representing hours. My goal is to display it in a format such as 3d13h, indicating days and hour ...

Tips for positioning an MUI element inside a container to extend to the edge of the browser window

Currently, I'm working on a project with a Material-UI (MUI) container that contains a Stack element. Within this Stack, there are two Box elements displayed in a row, each set to take up 50% of the width. In my design, I want the second box to break ...

Showcasing the Characteristics of Products in a Table on Prestashop

Dealing with PrestaShop. I have configured attributes for a product and I want to showcase them in a table format similar to this example: The table should display the Paper Size across the top, with each row representing the quantity of paper. In my ad ...

Adaptable Bootstrap Button that Adjusts to Different Screen Sizes

I want this button to adjust its size according to the screen dimensions. The current code keeps the button fixed in place. See below for the code snippet. <button type="button" [className]="'btn btn-block m-0'" kendoButton ...

Guidance on calling a JavaScript function from a dynamically added control

The Master page includes a ScriptManager. Next, I have a Control with a ScriptManagerProxy and an UpdatePanel. Within the UpdatePanel, I dynamically insert another Control (which also has a ScriptManagerProxy) that needs to run some JavaScript code. In ...

How to fill HTML <select> options using the GET Method

I am looking to populate a dropdown list with values from a repository in Qlik Sense using HTML. Are there any suggestions on how to achieve this without using PHP? As a beginner in this field, I would appreciate any guidance or assistance. UPDATE: Here ...

Two challenges I encountered with my CSS dropdown menu bar

I've been working on a CSS top dropdown navigation bar, but I'm encountering two issues that I can't seem to resolve. The first problem is that my nav div either extends too far down or my 1px right border tabs aren't reaching the botto ...

Angular Markdown Styling: A Guide

Currently, I am using Angular and Scully. I would like to add style to the image in a markdown file within Angular, but I am unsure of how to accomplish this task. The image is currently displaying too large. Can anyone provide me with useful advice on how ...

What techniques do platforms like Twitch, YouTube, Twitter, and Reddit use to dynamically load pages and update the URL without triggering a full reload?

Have you ever noticed that on some websites, when you click a link the page goes blank for a second and shows a loading indicator in your browser tab? However, on platforms like YouTube and Twitch, clicking a link smoothly transitions to the new page wit ...

What is the cause behind the failure of this regular expression in JavaScript?

I have been struggling to make this code display "matched!" for the specific string. I've tried various methods but nothing seems to be working. Here's the HTML part: <div id="ssn">123-45-6789</div> And here's the JavaScript p ...