Search code examples
jquerycsssticky

How to make an element sticky that is within a div after it gets scrolled past?


How do I make it so that when the user scrolls past the close button 'close' it will get stuck on the top of the page?

The catch is that I want it aligned to the right of the window (right: 0px) and that 'close' is contained in a div 'container' which has a width of say 500px and centered with margin: auto.

I tried making it so when you scroll past the element it'll add a class of 'sticky' which has a position: fixed. That doesn't seem to work.

jsFiddle: http://jsfiddle.net/7j18fwpa/

jQuery:

var top = $('.close').offset().top;
$(window).scroll(function (event) {
    var y = $(this).scrollTop();
    if (y >= top)
        $('.close').addClass('sticky');
    else
        $('.close').removeClass('sticky');
            $('.close').width($('.close').parent().width());
});

Solution

  • In your case you're trying to make a absolute positioned element sticky relative to its container.

    I have changed your jsfiddle into this:
    http://jsfiddle.net/7j18fwpa/3/

    So you will have:

    HTML:

    <div class="container">
        <div class="close sticky">CLOSE</div>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In ut dui nisi. Morbi cursus nibh eget imperdiet gravida. Etiam ultricies lectus quis mollis mattis. Quisque at tincidunt nisl, ut commodo turpis. Sed dapibus mi porta, tempor metus et, luctus mi. Donec hendrerit odio at augue mollis interdum. Vestibulum efficitur metus eget diam tempor egestas. Maecenas sit amet urna consectetur, ultrices tortor sit amet, convallis odio. Phasellus ut ante luctus, elementum est consequat, cursus velit. Phasellus eleifend massa in tellus sagittis, id viverra risus efficitur. Fusce auctor a nisi in mollis. Cras auctor ullamcorper consectetur. Nunc imperdiet feugiat nulla non tincidunt. Praesent pulvinar ut lacus sit amet sagittis. Sed et elit in ipsum elementum lobortis.
    
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum sed volutpat enim, sit amet varius elit. Sed vel diam consequat, lobortis diam vitae, aliquet diam. Morbi eget erat metus. Cras eget sollicitudin velit, eu cursus erat. Sed placerat, magna vitae feugiat rhoncus, ex turpis varius magna, nec laoreet nulla magna ac eros. Curabitur ut sollicitudin nibh. Proin et accumsan eros.</p>
    </div>
    

    CSS:

    .container{
        width: 500px;
        height: 500px;
        background: red;
        margin: auto;
        position:relative;
    }
    
    .close{
        background: blue;
        width: 50px;
        height: 20px;
        position: absolute;
        right:0;
        top:100px;
    }
    

    JS:

    $(function(){ // document ready
    
      if (!!$('.sticky').offset()) { // make sure ".sticky" element exists
    
        var containerTopOffset = $('.container').offset().top; // get offset the container
        var stickyTopOffset = $('.sticky').offset().top; // get offset of the sticky element
        var stickyTopCss = parseInt($('.sticky').css('top'), 10); // get original top pixels set on the sticky element from css
    
        $(window).scroll(function(){ // scroll event
          var windowTop = $(window).scrollTop(); // returns number 
          if (stickyTopOffset < windowTop){
            $('.sticky').css({ top: (windowTop-containerTopOffset) }); // set new top value for the sticky element that would be the window offset minus the container's offset
          } else {
            $('.sticky').css({ top: stickyTopCss }); // restore the original top value of the sticky element
          }
        });
    
      }
    
    });