Toggle Class Based On Vertical Scroll

- 1 answer

Fiddle is Below:

Just struggling to wrap my head around the best way to calculate when to add + remove a class based on the vertical scoll position.

I'm looking to add some side panels (possibly contain Banners etc) to my site, that will appear:

  • between the Header & Footer
  • & to the left & right of my main container

The height of my header + footer is constant throughout the site, so I'm able to add a class based on the ScrollTop position, however what im requiring is for the 'Side Panels' to not go beyond the start of the footer. In my example, the fixed class is removed once the Scroll Position + Window height is greater than the Document height, however what im wanting to achieve would be for these panels to reach the start (top) of the Footer & begin to scroll up the page as the user scrolls down the footer. ie the fixed position would be switched to absolution positioning + bottom:0??

The issue I've got now is how to calculate this as:

  • The height of the main panel will vary across the site
  • Plus The height of the banner could vary aswell
$(function() {
var panels = $(".side-panels");
var pos = panels.offset().top;  

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

    if(windowpos + $(window).height() >= $(document).height()){
    }else if(windowpos >= pos){

Is this method the best way of achieving this or is there a better/simpler solution?

Any help would be greatly appreciated




If both of your side panels are going to be the same height which I assume they are because it would look kind of silly otherwise you can do the following very simply just create an on scroll function and 2 instances of add and remove classes based on your div's positions. Here is a working fiddle Fiddle

The html

<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 class="footer">Footer</div>

The Jquery

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

And the css

  position: relative;
  height: 100%;
  width: 100%;
  width: 60%;
  height: 1000px;
  position: relative;
  margin: 0 auto;
  background: #8a8a8a;
.side-panel {
  top: 0;
  left: 10%;
  right: 10%;
  position: fixed;
  position: absolute;
  bottom: 0;