Adam Robertson
Adam Robertson

Reputation: 567

How would I go about adding a top offset for an element that sticks when it hits the top of the window?

I want a sharing wrapper to stick to the top of the window when it reaches the top on scroll. It just appends a sticky class to the element with a fixed position. However, how would I go about adding an offset to the top? I have a fixed header that's 60px in height and currently the div is sticking to the very top of the window, hiding the top 60px of it. Instead, I want it to stick 60px from the top of the window.

My JS:

(function () {
    var $stickyShare, $window, top;
    $window = $(window);
    $stickyShare = $('.share-container');
    top = $stickyShare.offset().top;
    $window.scroll(function () {
        return $stickyShare.toggleClass('sticky-fixed', $window.scrollTop() > top);
    });
}.call(this));

A JSfiddle: http://jsfiddle.net/h6afrtpk/1/

Upvotes: 0

Views: 183

Answers (1)

trenthaynes
trenthaynes

Reputation: 1678

You can update your .sticky-fixed class to set top to 60px instead of 0.

.share-container.sticky-fixed {
    position: fixed;
    top: 60px;
    left: auto;
    right: auto;
    background-color: #fff;
    border-bottom: 1px solid #ccc;
}

And update the function to check against top - 60.

return $stickyShare.toggleClass('sticky-fixed', $window.scrollTop() > top - 60);

A Fiddle

Upvotes: 1

Related Questions