determining the amount by which a div extends beyond the window's height

My challenge is to have a fixed div appear on top of various background images. The problem arises when this fixed div exceeds the height of the window, causing it not to scroll and resulting in lost content. I've attempted using max-height: 100% and y-overflow:scroll;, but to no avail.

To address this issue, I devised a workaround using the following JavaScript:

<script>
  $(window).scroll(function(){
    var css = {};
    if  ($(window).scrollTop() > 120){
         css = { top:'0'};
    } 
    else {
            css = {top:'120'};
    }
    $('#writtenContent').animate(css,{duration:200,queue:false});
  });
</script>

This solution lifts the div up, although it is not ideal for several reasons. I am seeking a way to determine how much of the div is hidden and move up that amount accordingly or make the fixed div scrollable. Ideally, these adjustments should only occur as needed, meaning if the div fits within the window, no action would be required.

I welcome any suggestions!

===============UPDATE=================

Hello everyone - I created a quick jsfiddle showcasing the issue I'm facing. It's a simplified version, demonstrating how we lose content when the window is resized smaller than the content-holding div.

Answer №1

Initially, you mentioned it's a fixed div, suggesting position:fixed, but then you refer to position:relative. Can you clarify the discrepancy? The desired functionality should involve scrolling. While attempting y-overflow is understandable, it should actually be overflow-y. Give that another try and evaluate the outcome. If issues persist, consider sharing all relevant code and styles for further assistance.

As an additional approach, consider using max-height: with different percentages below 100% to assess any improvements in behavior.

Answer №2

It seems like this solution will meet your needs.

let windowElement = window,
    $writtenContent = $('#writtenContent'),
    $writtenContentPosition;

function scrollMagic(){

    $writtenContentPosition = $writtenContent.offset().top; // find distance from top

    // if scrolled beyond the element:

    if (window.scrollY > $writtenContentPosition) {

        // perform action, like animating $writtenContent to match win.scrollY position
    }
}

$(document).ready(function(){

    $(windowElement).scroll(){

        scrollMagic();
    });
});

Adjustment based on the jsfiddle example:

let $win            = $(window),
    $winHeight,
    $writtenContent = $('#writtenContent'),
    $writtenContentPosition,
    $writtenContentHeight,
    $writtenContentBottomEdgePosition,
    heightDifference;

function calculateHeights() {

    $winHeight                        = $win.height();
    $writtenContentPosition           = $writtenContent.offset().top;
    $writtenContentHeight             = $writtenContent.height();
    $writtenContentBottomEdgePosition = $writtenContentPosition + $writtenContentHeight;

    heightDifference                  = $winHeight - $writtenContentBottomEdgePosition;
}

function resizeMagic() {

    calculateHeights();

    if (heightDifference < 0) {

        $('#alert').html('Written Content is off screen by ' + heightDifference + 'px');
    } else {
        $('#alert').html('Written Content is not off screen');
    }
}

$(document).ready(function(){

    calculateHeights();

    $win.resize(function(){

        resizeMagic();
    });
});

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

Modifying the position of a component in the UI tree to reset its state in ReactJs

According to React, the state will be maintained as long as the same component is rendered at the same position. In this scenario, I have two Counter components rendering. By toggling a checkbox, I am able to control the visibility of the first Counter co ...

How to pass event data when clicking on a div using React

I'm curious about how the onClick event flows in React when clicking on a div. In my application, there's a ParentComponent that renders a ChildComponent which generates a div for each item in the props.options array. I have a couple of questio ...

The functionality of the JavaScript animated placeholder seems to be malfunctioning

I am currently working on a code that updates the placeholder text every 2 seconds. The idea is to have it type out the letters one by one, and then erase them in the same manner. Unfortunately, the code is not functioning as expected. As a newcomer to J ...

When the value of a Formcontrol is changed using valueAccessor.writeValue(), it remains unchanged

Encountering a similar issue as seen in this stack overflow post, but the solution provided isn't resolving the issue. Perhaps you can offer assistance on that thread. In my scenario, I have created a directive for formatting phone numbers: import { ...

The orientation of the rating stars has transformed into a vertical layout

I'm having trouble creating a rating interface that prompts the user to rate the website (by clicking the stars) and leave a comment. The stars are displaying vertically instead of horizontally, as shown in the image provided in the link. I've tr ...

Using JQuery and PHP to handle a click event on a webpage

To monitor and handle the click of a button on my page, I am looking to trigger a POST request to delete a specific course from the database by sending its course ID to PHP. Here's what I have implemented: Within a table displaying course details, th ...

Pictures failing to load on both Chrome and Safari browsers

For some reason, the images on my app are not appearing in Chrome and Safari but show up fine in Firefox. If you try to open the image URL in a browser, it works perfectly. However, when embedded in the HTML document, the image appears broken. I also test ...

Moving elements upwards and downwards using CSS transitions

I am currently designing a metro tiles menu for my website, without using JavaScript and only relying on HTML and CSS. The issue I am facing involves the sliding tiles and the direction in which they slide. Additionally, there seems to be a problem where ...

My node.js and express application is encountering an issue where it is failing with an error indicating that a variable has not been

Currently in the process of understanding how node.js and express operate. I've successfully extracted data from my mongo database... and now I'm experimenting with transferring data between my router code and views. The locations.js file within ...

How can I use JavaScript to display every line individually in a textarea?

I am trying to display the content of a textarea in my div with the ID #result. I want to maintain the line breaks from the textarea and append 1 at the end of each line. Here's my current attempt, but it only adds 1 to the last line. <!DOCTY ...

When the page is zoomed in, the image exceeds the boundaries of the parent div

I attempted to position the div elements but did not achieve the desired outcome. .tab-vertical { border: 1px solid black; } <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" dat ...

In JavaScript, I would like to be able to input an end date and have the program calculate and display the number of days remaining until the deadline

I'm working on a school project that involves JavaScript code. I'm struggling with converting a date prompt from string to number format. As a beginner in JavaScript, I could really use some guidance. <script> enddate = prompt('Wh ...

Updating the design attributes of a div by utilizing ReactJS hooks upon clicking

Among my collection of elements with distinct IDs and a common className, I aim to modify the background, text color, and font when a user interacts with them. To achieve this, I defined two variables (Style1 and Style2) to represent the styles for normal ...

Guide on inserting text input value into the href attribute of a hyperlink

Lately, I've been facing an issue that has been troubling me for the past few hours. I have a search input field where users can enter text and click send. The entered text should then be added to the href attribute and sent to the results page for qu ...

Storing data in a text or HTML file using server-side JavaScript

Currently, I am working on a JavaScript form that involves saving user-entered variables to either a .txt file or a new webpage with the variables pre-filled in the inputs. I know that JavaScript cannot directly manipulate the user's machine, but I am ...

Looking to handle a .csv file containing both quotes and commas within the quotes in Node.js - how can I achieve this

My code solution successfully parses a CSV file, but it doesn't handle cases where data has commas within quoted fields. For example, "not, accounted","normal". let filePath = Path.resolve(__dirname, `./MyData.csv`); let data = fs.readFileSyn ...

The for loop unexpectedly interrupts a different array

Hey there, I've been working with puppeteer and came across an issue with the following code snippet: console.log(dealsId[i]); for (var i = 0; i < sizes.length; i++) { var refIdClasses = await sizes[i].$eval('input', a => a.getAtt ...

What's the best way to center Align Bootstrap 5 Card component?

https://i.sstatic.net/y86aU.jpg I would like to centrally align the screenshot above. The main parent division class is called "main-div". ...

Can you explain the purpose of prevState within the setState method of a functional component?

When returning the updated previous state within a setState method retrieved from the useState hook, it appears that the state remains unchanged. To demonstrate this behavior, consider running the following code snippet: function App(){ const [state, ...

Steps for creating a resizable and automatically hiding side menu

I am working on a side menu that can be resized, and I want it to collapse (set to zero width) when it is empty. I have considered implementing one of these features individually, but I'm not sure how to make both work together. Is there a way to ad ...