Simple Sticky Element

October 14, 2016

 

The Action:

The user scrolls down the page and once the scrolling reaches the top of an element of my choosing, that element sticks to the top of the window, so it's always visible from that point on.

 

Directions:

1. Include the "sticky element" code.

2. Add a div with the class of "element-sticky", and a div within that with a class "element-sticky-content".

3. Add whatever content is needed within the "element-sticky-content" div.

 

Other Notes:

1. All of the css is included in this file, so there isn't a need for a stylesheet document with this

2. When the div sticks to the top of the page, an additional class ("element-sticky-fixed") is added to the "element-sticky-content" div.

 

Example:

http://www.drempd.com/examples/el_sticky.html

 

Code:

$(document).on("scroll", function (e) {

    var
        element = $('.element-sticky-content'),
        elementTop  = $('.element-sticky').position().top,
        scrollPos   = $(document).scrollTop();

    if (scrollPos > elementTop) {
        element
			.css({ 'position': 'fixed', 'top': '0px', 'left':'0px','zIndex':'3000','width':'100%' })
			.addClass('element-sticky-fixed');
    }
    else {
        element.css({ 'position': 'relative','zIndex':'auto' }).removeClass('element-sticky-fixed');
    }

});