'jQuery to Detect Scrolling Div Position

I have a bit of problem trying to detect scrolling position on my divs. This is my code:

index.html

<div id="wrapper">
  <div id="headerOne">I am a header</div>
  <div id="contentContainer">
    <div id="content">
      I am some content
    </div>
   </div>
</div>

jQuery function (not working version)

$(document).ready(function() {

    var aboveHeight = $('#headerOne').outerHeight();

$('#contentContainer').scroll(function(){
      if ($('#contentContainer').scrollTop() > aboveHeight){
      $('#headerOne').addClass('fixed').css('top','0').next().css('padding-top','60px');
      } else {
      $('#headerOne').removeClass('fixed').next().css('padding-top','0');
     }
    });
  });

jQuery function (working version)

$(document).ready(function() {

    var aboveHeight = $('#headerOne').outerHeight();

$(window).scroll(function(){
      if ($(window).scrollTop() > aboveHeight){
      $('#headerOne').addClass('fixed').css('top','0').next().css('padding-top','60px');
      } else {
      $('#headerOne').removeClass('fixed').next().css('padding-top','0');
     }
    });
  });

There are two different jQuery function because when I first tested I was using the working version and the header stays when scrolling down. But I want the header header to stay fixed user is scrolling #contentContainer div not the window so I change it to $(window). to $('#contentContainer') and it's not working anymore.

Can scroll feature detect div scrolling or must it be $(window). ?

Thank you.



Solution 1:[1]

Perhaps you could use this?

jQuery(document).ready(function($) {
    //Calculate the height of <header>
    //Use outerHeight() instead of height() if have padding
    var aboveHeight = 130;

    //when scroll
    $(window).scroll(function(){

        //if scrolled down more than the header’s height
        if ($(window).scrollTop() > aboveHeight){

            // if yes, add “fixed” class to the <nav>
            // add padding top to the #content 
            //(value is same as the height of the nav)
            $('nav').addClass('fixed').css('top','0').next()
            .css('padding-top','60px');

        } else {

            // when scroll up or less than aboveHeight,
            //remove the “fixed” class, and the padding-top
            $('nav').removeClass('fixed').next()
            .css('padding-top','0');
        }

    });
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Brampage