javascript - Toggle Class Based On Vertical Scroll -


fiddle below:

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

just struggling wrap head around best way calculate when add + remove class based on vertical scoll position.

i'm looking add side panels (possibly contain banners etc) site, appear:

  • between header & footer
  • & left & right of main container

the height of header + footer constant throughout site, i'm able add class based on scrolltop position, im requiring 'side panels' not go beyond start of footer. in example, fixed class removed once scroll position + window height greater document height, im wanting achieve these panels reach start (top) of footer & begin scroll page user scrolls down footer. ie fixed position switched absolution positioning + bottom:0??

the issue i've got how calculate as:

  • the height of main panel vary across site
  • plus height of banner 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()){         panels.removeclass('fixed').addclass('absolute');     }else if(windowpos >= pos){         panels.addclass('fixed');     }else{         panels.removeclass('fixed');     } }); }); 

is method best way of achieving or there better/simpler solution?

any appreciated

cheers

if both of side panels going same height assume because kind of silly otherwise can following create on scroll function , 2 instances of add , remove classes based on div's positions. here 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> <div class="footer">footer</div> 

the jquery

$(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 css

.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; } 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -