probablybest
probablybest

Reputation: 1445

Responsive scrolltop

Im using the following code to detect when an object should become 'sticky' and stay fixed in its content.

var $window = $(window),
    $stickyEl = $('#single-post-details'),
    elTop = $stickyEl.offset().top;

$window.scroll(function() {
    $stickyEl.toggleClass('sticky', $window.scrollTop() + 52 > elTop);
});

However I would like to make this responsive. This means that somehow it needs to detect the height of the banner above it first so that it doesn't trigger at the wrong point.. Here is a fiddle with as an example.

Upvotes: 0

Views: 3045

Answers (1)

Karl-André Gagnon
Karl-André Gagnon

Reputation: 33870

The problem is that on the resize, the top position of you sticky element change. To solve that, you should not check the height of the image, but recalculate the top position.

The use of .resize event is usefull here. On the callback, just update you global variable :

var $window = $(window),
    $stickyEl = $('#single-post-details'),
    elTop = $stickyEl.offset().top;

$window.on({
    resize : function(){
        elTop = $stickyEl.offset().top;
        $window.trigger('scroll');
    },
    scroll : function() {
        $stickyEl.toggleClass('sticky', $window.scrollTop() + 20 > elTop);
    }
});

Note: the trigger('scroll') is important to prevent the sticky element to go over the image while expanding the window.

Fiddle

Upvotes: 3

Related Questions