Fixed positioning upon scrolling begins prior to reaching the uppermost point (top div)

Currently, I have implemented a feature where #filter (the white select list in my sidebar) becomes fixed when it reaches the top of the page and stays there while scrolling until it reaches the footer and is released.

However, I encountered an issue with a <div> box at the top that is also positioned as fixed, causing #filter to not become fixed immediately when reaching the top of the page. This results in a sudden jolt before it finally attaches itself in the fixed position. Is there a way to make #filter become fixed 40px before reaching the very top?

Check out the jsfiddle

$(function() {
    var top = $('#filter').offset().top,
        footTop = $('#outside_footer_wrapper').offset().top,
        maxY = footTop - $('#filter').outerHeight();
        console.log(top , footTop, maxY);

    $(window).scroll(function(evt) {
        var y = $(this).scrollTop();
        console.log(y);
        if (y > top) {
            console.log('greater');
            $('#filter').addClass('fixed').removeAttr('style');
            if (y > maxY-130){
                var min = y - maxY + 130;
                console.log('greater and less', min);
                $('#filter').css('top','-'+min+'px');
            }
        } else {
            $('#filter').removeClass('fixed');
        }

    });
});

Answer №1

Revise the if statement as follows:

console.log(y);
if (y >= (top-y)) {

Check out the code on jsfiddle

LATEST UPDATE

Switch back to this code

$('#filter').css('top','-'+min+'px');

updated jsfiddle version

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

Is it true that Javascript's onclick global event handlers fire prior to the page being fully loaded

I'm trying to set a global event handler for an image, but running into issues. When I use the code document.getElementById("post_image").onclick = photoEnlarge;, it returns an error saying Uncaught TypeError: Cannot set property 'onclick' ...

The React application is experiencing difficulties in receiving the response data (JSON) from the Express server, despite the fact that

When making POST or GET requests to our Express server, served through PM2 on EC2, Postman receives the complete response with JSON data. However, our front end React app (both locally and deployed via CF) only gets the response status code and message. Th ...

Monaco Editor: Module 'monaco-editor' is missing despite being successfully installed

During the development of my desktop application with electron, I encountered an issue with installing Monaco Editor. After using npm install monaco-editor, running the application resulted in a message saying Cannot find module 'monaco-editor'. ...

Guide to Updating Store State with API Data

My goal is to update my component state with data retrieved from an API using a getter in the store. Within the mounted() lifecycle hook, I call the getProducts() getter which is defined as: export const getters = { async getProducts() { axios.ge ...

Trigger an alert after a separate function is completed with jQuery

On my page, I have a function that changes the color of an element. I want to trigger an alert once this action is complete using changecolor(). However, I am unable to modify the changecolor() function due to certain restrictions. Is there a way to dete ...

What is the best way to adjust the height of a div based on its child content

I've been experimenting with various methods to extend the white background around the title to cover the rest of the content. I've tried using overflow, clear, min-height, max-height, and even the '*' selector but nothing seems to work ...

Experiencing Issues with File Downloading on Express Server with Axios and Js-File-Download Library

I developed a feature on my express server that allows users to download a file easily. app.post("/download", (req, res) => { let file_name = req.body.name; res.download(path.join(__dirname, `files/${file_name}.mp3`), (err) => { ...

Error: Property cannot be read after page refresh or modification

Upon refreshing or running the project for the first time, I encounter the error: TypeError: Cannot read property 'statements' of undefined This issue is perplexing as the data renders correctly but it appears that the connection is failing. ...

After extended periods of use, the website experiences frequent crashes

Currently, I am developing a website using a free provider (000webhost) and focusing on integrating a chat feature. To achieve this, I have implemented an interval every 500 milliseconds that reads a file to check for new messages. When a new message is de ...

Is it possible to implement dependency injection within a .css document?

I have a C# .NET 6 application. Some of the web pages (Razor Pages) in the app use dependency injection to inject configuration into the Razor Pages (.cshtml files), allowing certain config elements to be displayed in the user interface. My query is, can ...

Adjust the size of col-lg-3

Is there a way to adjust the size of my col-lg based on different screen resolutions? I'm looking for a solution that can change the size of col-lg depending on the screen resolution. For example: .col-lg-3 { /* styles for screens with 1366x768p ...

Is there a way to horizontally center a content container in Flutter similar to a "max-width" container in CSS?

How can I create a centered content box like this in Flutter?: .content-box { margin-left: auto; margin-right: auto; width: 100%; max-width: 600px; background-color: blue; height: 100vh; } <div class="content-box"> Cont ...

Using Ajax.Updater to run JavaScript code

I've tried numerous online tutorials and examples, but haven't had much success... I'm looking to execute JavaScript from an HTML Response in Ajax. Here's my code snippet: <script src="prototype.js" type="text/javascript"></ ...

Accessing Google Analytics with a single OAuth token using the JavaScript API: A step-by-step guide

I'm currently developing a webpage for exclusive users to view shared Google Analytics data. I have managed to obtain an OAuth token for the account housing this data using JavaScript, but sadly it expires in just 1 hour. Is there a way to utilize th ...

Store the numeric value in JavaScript as a PHP integer

My goal is to obtain the width of the browser and then compare it as a PHP variable. However, the issue I am facing is that it is being saved as a string, and my attempts at parsing it to another variable only result in returning 0. $tam='<script& ...

How is it possible for my search results page to retrieve the words I input?

Currently, I am in the process of creating the search result page and I plan to utilize dynamic routing for implementation. Here is a snippet of my search bar code: <Link href={`/productSearchResult/${searchWord}`}> <a className={styles.navbar_s ...

How to retrieve a subobject using AngularJS

From my perspective : <span data-ng-init="fillEditForm['titi']='toto'" ></span> In my Angular controller : console.log($scope.fillEditForm); console.log($scope.fillEditForm['titi']); The outcome : Object { ti ...

Creating a customized SelectField component for Material-UI v1.0.0-alpha.21 with a fix for the Menu anchorEl problem

Currently, Material-UI v1.0.0 does not have a selectField implemented yet so I am attempting to create my own version using TextField, Menu, and MenuItem Components. Below is the code for my custom selectField: export default class SelectField extends Rea ...

The absence of req.body in the app reflects an undefined state

I'm encountering an issue with my app and I believe showing you my code is the best way to explain the problem: var Meetup = require('./models/meetup'); module.exports.create = function (req, res) { var meetup = new Meetup(req.body); c ...

When using the <object> tag, it may not always render at 100% height as intended

Application Inquiry I am seeking assistance with a web page that features a title, and a sticky menu bar at the top, allowing the rest of the space for displaying content. When a menu item is clicked, the objective is to load a page in the content at full ...