0

I want to add the class 'sticky' when scrolling over the div with class="product-options-sidebar" and remove the 'sticky' class at the end of the <section id="options">.

This so that the div will only contain the class for the height of the entire section. It should be a sticky sidebar as long as the <section> element is.

How can I achieve this?

My current code works almost perfect but we already have a sticky header with a height of 120px. So top 0 should be -120px of the current sticky header. And it is also causing a console error: TypeError: undefined is not an object (evaluating 'c.position().top')

$(document).ready(function() {
  var $window = $(window);  
  var $sidebar = $(".product-options-sidebar"); 
  var $sidebarHeight = $sidebar.innerHeight();   
  var $footerOffsetTop = $(".product-collateral").offset().top; 
  var $sidebarOffset = $sidebar.offset();

  $window.scroll(function() {
    if($window.scrollTop() > $sidebarOffset.top) {
      $sidebar.addClass("sticky");
    } else {
      $sidebar.removeClass("sticky");   
    }    
    if($window.scrollTop() + $sidebarHeight > $footerOffsetTop) {
      $sidebar.css({"top" : -($window.scrollTop() + $sidebarHeight - $footerOffsetTop)});       
    } else {
      $sidebar.css({"top": "0",});  
    }    
  });   


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<section id="options">
  <div class="product-options-block col-md-9 col-sm-9"> 
    <div class="product-options" id="product-options-wrapper">
      INNER CONTENT
    </div>
  </div>
  <div class="product-options-sidebar col-md-3 col-sm-3">
    <div class="header-options">HP ProBook 450 G5 CTO</div>
    <div class="product-options-subcontent">
      INNER CONTENT
    </div>
  </div>
</section>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.