1

I'm having some trouble adding a sticky on scroll "Add to Cart" area to a product page.

So far I'm able to make the selected element become position: fixed from a certain point while scrolling until it reaches a 'cutoff point' so to speak, where it becomes position: absolute.

I also have a rule written to remove the position styling when I scroll above the 'starting point' for position: fixed. All of these are written inside one function which fires on $(document).scroll(). I'll post my code below.

The rules I've written seem to be working fine except for one specific thing. When I scroll down, the element becomes fixed. When the fixed element reaches the 'cutoff point' it switches to position: absolute and stays there when I continue scrolling. This is what I want.

The problem is when I start scrolling back up past the 'cutoff point' the element's positioning doesn't switch back to position: fixed. It stays position: absolute until I reach the top of the page where the styling is removed. I can then scroll down again and it will start all over again, fixed > absolute > not reverting back to fixed on scroll up.

function checkOffset() {

    var div1 = $(".ProductMain");
    var div2 = $(".SideRelatedProducts");
    var div3 = $("#cssmenu");

    var div1_top = div1.offset().top;
    var div2_top = div2.offset().top;
    var div3_top = div3.offset().top;

    var div1_bottom = div1_top + div1.height();
    var div2_bottom = div2_top + div2.height();
    var div3_bottom = div3_top + div3.height();

  // This is what removes styling assigned from scrolling, when element gets back to top of page

    if (div1_bottom >= div3_bottom && $(window).width() > 900) {
        $('.ProductMain').css({
            'position': 'absolute',
            'top': 'auto',
            'bottom': '55px'
        });
        console.log('ABSOLUTE');
    }

  // This is what removes styling assigned from scrolling, when element gets back to top of page

    if ($(document).scrollTop() > $('.main').offset().top + 20 && $(document).scrollTop() + div1.height() < (div2_top + 75) && div1_bottom < div3_bottom && $(window).width() > 900) {
        $('.ProductMain').css({
            'position': 'fixed',
            'top': '60px',
            'bottom': 'auto'
        }); // restore when you scroll up
        console.log('FIXED');
    }

  // This is what removes styling assigned from scrolling, when element gets back to top of page

    if($(document).scrollTop() < $('.main').offset().top && $(document).scrollTop() + window.innerHeight < div2_top || $(window).width() < 900) {
        $('.ProductMain').removeAttr('style');
    }
}

$(document).scroll(function() {
    checkOffset();
});

Thanks for your help!

gBasgaard
  • 61
  • 1
  • 3
  • 9

1 Answers1

2

This seems to be answered already. Please try this answer here:

Using jQuery to keep scrolling object within visible window

Luke Becker
  • 864
  • 7
  • 14