简体   繁体   中英

Jquery sticky menu not being caught by footer

Can anyone help me pinpoint the issue with my script please?

$(function () {
var top = $('#sidebar').offset().top - parseFloat($('#sidebar').css('marginTop').replace(/auto/, 0));
var footTop = $('#footer').offset().top - parseFloat($('#footer').css('marginTop').replace(/auto/, 0));
var maxY = footTop - $('#sidebar').outerHeight();
$(window).scroll(function (evt) {
    var y = $(this).scrollTop();
    if (y > 100) {
        if (y < maxY) {
            $('#sidebar').addClass('stickyside').removeAttr('style');
        } else {
            $('#sidebar').removeClass('stickyside').css({
                position: 'absolute',
                top: (maxY - top) + 'px'
            });
        }
    } else {
        $('#sidebar').removeClass('stickyside');
    }
});
});

Live site here - https://tregothnan.co.uk/tea-herbal-infusions/

Sticky sidenav is spilling over the footer div and no matter what I try I can't get it to work. It works fine in my jsfiddle prototype.

The problem is that you are forgetting the margin-top of your sidebar in your calculation:

var maxY = footTop - $('#sidebar').outerHeight() - 68;

In your Prototype JSFiddle the sidebar just happened to have no margin-top .


On a sidenote: you may want to cache your selectors to improve performance. If you use the same selector more than once, for example $("#sidebar") , put it in a variable:
var sidebar = $("#sidebar"); .

Ok - many thanks @dark-ashelin

ended up with this - bit of a hack but it works.

$(function () {
var sidebar = $("#sidebar");
var top = $('#sidebar').offset().top - parseFloat($('#sidebar').css('marginTop').replace(/auto/, 0));
var footTop = $('#footer').offset().top - parseFloat($('#footer').css('marginTop').replace(/auto/, 0))-60;
var maxY = footTop - $('#sidebar').outerHeight() - 85;
$(window).scroll(function (evt) {
    var y = $(this).scrollTop();

    if (y > 100) {
        if (y < maxY) {
            $('#sidebar').addClass('stickyside').removeAttr('style');
        } else {
            $('#sidebar').removeClass('stickyside').css({
                position: 'absolute',
                top: (maxY + 50) + 'px'
            });
        }
    } else {
        $('#sidebar').removeClass('stickyside');
    }
});
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM