Change Class Depending on Vertical Scroll Position

Take a look at the Fiddle provided below:

https://jsfiddle.net/y0mj6v2d/5/

I'm currently trying to figure out the most effective approach for determining when to apply or remove a class based on the vertical scroll position.

My goal is to incorporate side panels (potentially containing banners) into my website that will be displayed:

  • between the Header and Footer
  • to the left and right of the main container

The height of both my header and footer remains consistent across all pages, allowing me to assign a class depending on the ScrollTop position. However, I need the 'Side Panels' to remain within the boundaries of the footer's starting point. In the current example, the fixed class is removed once the Scroll Position combined with the Window height surpasses the Document height. What I aim for is for these panels to reach the top of the Footer and then start scrolling up the page as the user continues scrolling down the footer. This means switching from fixed positioning to absolute and setting bottom: 0.

The challenge I face now lies in calculating this due to:

  • The varying height of the main panel throughout the site
  • Potential fluctuations in the banner's height
$(function() {
var panels = $(".side-panels");
var pos = panels.offset().top;  

$(window).scroll(function() {
    var windowpos = $(window).scrollTop() ;

    if(windowpos + $(window).height() >= $(document).height()){
        panels.removeClass('fixed').addClass('absolute');
    }else if(windowpos >= pos){
        panels.addClass('fixed');
    }else{
        panels.removeClass('fixed');
    }
});
});

Would you say this method is the most efficient way to achieve this effect, or can you suggest a better and simpler solution?

Any assistance you can provide would be highly appreciated!

Thanks!

Answer №1

In the case where both of your side panels are meant to be the same height, it is assumed they should align for consistency. To achieve this, a simple on scroll function can be created with 2 instances of add and remove classes based on the positions of your div elements. Here's a functional fiddle link: Fiddle

Below is an example code snippet:

<div class="header">Header</div>
<div class="content-wrapper">
  <div class="side-panel left"></div>
    <div class="main-content"></div>
  <div class="side-panel right"></div>
</div>
<div class="footer">Footer</div>

Here is the jQuery script used:

$(window).on( "scroll", function() {
  if ( $(window).scrollTop() >= $(".content-wrapper").offset().top ) {
    $( '.side-panel' ).addClass("fixed");
  }else{
    $( '.side-panel' ).removeClass("fixed");
  }
  if ( $(window).scrollTop() >= $(".footer").offset().top - $('.side-panel').height()) {
     $( '.side-panel' ).addClass("absolute-bottom");
  }else{
    $( '.side-panel' ).removeClass("absolute-bottom");
  }
});

And the accompanying CSS styles:

.content-wrapper{
  position: relative;
  height: 100%;
  width: 100%;
}
.main-content{
  width: 60%;
  height: 1000px;
  position: relative;
  margin: 0 auto;
  background: #8a8a8a;
}
.side-panel {
  position:absolute;
  background-color:#532b90;
  width:10%;
  height:125px;
  top: 0;
}
.side-panel.left{
  left: 10%;
}
.side-panel.right{
  right: 10%;
}
.fixed{
  position: fixed;
}
.absolute-bottom{
  position: absolute;
  bottom: 0;
  top:auto;
}

Answer №2

While your approach is solid, consider utilizing .height() more frequently. This will ensure that the heights are constantly adjusted for optimal dynamic functionality.

let headerHeight = $('.header').height();
let footerHeight = $('.footer').height();
let contentHeight = $('.page-contents').height();

Answer №3

To find the starting point of the footer, you can calculate it by subtracting the height of the footer from the top offset of the footer. This would look like:

$(".footer").offset().top - $(".footer").height()
.

Once you determine when the scroll position reaches the calculated value above, you can remove the .fixed class as demonstrated in your existing code.

Here is an illustration of this concept.

Code:

$(function() {
var panels = $(".side-panels");
var pos = panels.offset().top;  
var footerTop = $(".footer").offset().top;

    $(window).scroll(function() {
        var windowpos = $(window).scrollTop() ;

        if(windowpos >= (footerTop - $(".footer").height())){
            panels.removeClass('fixed');
        }else if(windowpos >= pos){
            panels.addClass('fixed');
        }else{
            panels.removeClass('fixed');
        }
    });
});

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

Properties of objects changing dynamically

<div id="bach">Bach</div> <div id="show">about composer</div> $(window).load(function(){ bach = {"bdate": 1685, "bplace": "Eisenach, Germany"} $("div").click(function(){ $("#show").text(this.id['bdate']); // ...

Implement a dropdown menu for filtering, but it is currently not functioning as expected

When I select a city_name, my goal is for the graph to only display information pertaining to that particular city. In the params section of my code, I have included filtering options using a selection menu in Vega-Lite. However, despite selecting Brisba ...

Divide a single string into segments using JavaScript

When working with a string like the following 1-2-3 1-2 What is the JavaScript method to split them so that I can extract the numbers individually like this 1 2 3 ...

When applying json_encode to the PHP $_GET array, it returns a singular string instead of an array containing strings

I am attempting to utilize the PHP GET method in order to generate an array of keywords from a keywordBox field on a different page. For instance, here is how the keywords are added to the page URL: /searchResults.php?keywordBox=computing+finance Althou ...

Is it possible for the sum to turn into NaN in Bootstrap Table JavaScript?

I used bootstrap to create a table that links with phpmyadmin. I need to show the total current amount in the table, which should update when using the search function. However, I keep getting NaN as my result. Below is the relevant code: // PART OF CODE ...

Using CSS, create a layout with a small 2x2 box positioned beside a larger 2x2 box

https://i.sstatic.net/nC2PI.png Can a flexible ul li structure be achieved with flexbox? I attempted to set the width of the squares to 25% and make the 1st, 3rd, or 5th one 50% wide using a combination of float:left, clear[left|right], but the last squar ...

Strategies for managing grid overflow situations

Check out my codepen showcasing the current issue I'm dealing with: https://codepen.io/marcdaframe/pen/qeBWNd <div> 123 abc <div class="container"> <div class="wrapper"> <div>One</div> <div>Two</div> ...

Continue applying CSS edits even after reloading the page

I have successfully implemented the Cookie Yes plugin with wordpress, however, there is one final issue that I need help with. Our goal is to ensure that the banner always remains at the top of the page without overlapping the navigation bar. To achieve t ...

Leveraging the power of HTML 5 to dynamically insert content into a jQuery table

I am experiencing an issue with my jquery stock ticker. It displays the latest stocks including Company Name, stock price, and percentage changed. The stock price can be in GBP, USD, or YEN, but the current ticker does not indicate the currency. I attemp ...

Trouble with downloading files using the anchor (a) tag in React

Every time I try to click on the a tag to download the file named approved_leads.zip, I keep receiving an error message saying "failed - no file". It seems like the path is correct, so I'm not sure what is causing the issue. <a href="../../ass ...

Access to Orders on Shopify has been denied due to a GraphQL error

When trying to fetch orders with '@shopify/koa-shopify-auth', I encountered an error. [GraphQL error: access denied] The query I used is as follows: query { orders(first:2) { edges { node { id name } } } ...

Assign the value selected from a dropdown menu to a PHP variable for MySQL

Is there a way to adjust the variable $Category in the following mysql query based on the selection made in the dropdown list? This seems like a straightforward task, but I'm having trouble figuring it out. It would be really helpful if the page coul ...

The tag's onclick function that was dynamically created was not triggering in jQuery

I created a web application using jquery mobile and ran into an issue. I am trying to call a function by clicking on a dynamically generated anchor tag, but it's not working and showing an error that the function is not defined. Any assistance on this ...

Error: The schema configuration is invalid. The value ${name} is not allowed

Project Link: https://github.com/k4u5hik/node-express-course I'm currently experimenting with populate.js to automatically import data from products.json into my MongoDB database using mongoose. The schema is defined in product.js. product.js co ...

What is the most effective method for animating an image to move along a circular path using JQuery?

Looking to have an image (colored red below) move along a circular path, returning to its original starting point. Important Points: The circular path is represented by grey lines for reference. What method or library would be recommended for achieving ...

In Vue.js, when an if-else statement is nested within a loop, it will display the

I'm trying to create a loop that displays blog posts. Within this loop, I have another loop to retrieve the likes for each blog post. My goal is to show an "unlike" button if the authenticated user has liked the blog post, and a "like" button if they ...

What are the steps involved in manipulating objects within an asynchronous result object?

I'm interested in learning how to manipulate a JS object from one file into another asynchronously, as my experience with asynchronous code principles is limited. Scenario: In my app.js file, I dynamically generate 'app panels' based on ...

Is it feasible to unload modules in Node.js once they have been loaded?

app.post('/userlogin',function(req,res){ var Module1=require('./lib/module1'); app.use(Module1); var Module2=require('./lib/module2'); app.use(Module2); }); Is it possible to unload or destroy the modules after they ...

Creating a layout with three rectangular shapes using HTML and CSS

What is the most effective method to achieve the following layout using HTML/CSS: +---------+---------------------------------------------------+ | my | Home About Categories Donate | | best +---------------------------------- ...

Circular reference detected during JSON serialization

Two classes were created: "Candidate" and "Experience". A Candidate can have multiple experiences. public class Consultant { public int ConsultantID { get; set; } public string ConsultantNom { get; set; } public string ConsultantPrenom { get; ...