Search code examples
jquerycssfixed

Stop moving div with page before footer


I am using this tutorial http://jqueryfordesigners.com/fixed-floating-elements/ to make my div move with page while user scrolling. It works like a charm, but until you reach bottom of my web and div have still position fixed and still moving from his parental div to footer. JavaScript:

$(document).ready(function () {
  var top = $('#comment').offset().top - parseFloat($('#comment').css('marginTop').replace(/auto/, 0));
  $(window).scroll(function (event) {
    // what the y position of the scroll is
    var y = $(this).scrollTop();

    // whether that's below the form
    if (y >= top) {
      // if so, ad the fixed class
      $('#comment').addClass('fixed');
    } else {
      // otherwise remove it
      $('#comment').removeClass('fixed');
    }
  });
});

CSS:

#comment.fixed {
  position: fixed;
  top: 0;
}

Here is my page, so you can look what exactly is my problem: http://testportal.jon.cz/projekt-konfigurator/konfig.html

Sorry for my english and thanks for your answers :)


Solution

  • I've done it once using css property transform on Cart Page. All you need to calculate the offset which you can do dynamically with .

    jQuery(window).load(function() {
      offset = jQuery('fieldset').offset().top;  // offset from top of the left content
      fieldset = jQuery('fieldset').outerHeight();  // outer height of the left content
      collaterals = jQuery('.cart-collaterals').outerHeight();  // outer height of the movable right content
      maxTop = fieldset > collaterals ? (fieldset - collaterals) + offset : offset;
      jQuery(window).scroll(function() {
        st = jQuery(window).scrollTop();
    
        if (st > offset && st < maxTop) {
    
          jQuery('.cart-collaterals').css('transform', 'translate(0px, ' + (st - offset) + 'px)');
        } else if (st < offset) {
          jQuery('.cart-collaterals').css('transform', 'translate(0px, 0px)');
        } else if (st > maxTop) {
          jQuery('.cart-collaterals').css('transform', 'translate(0px, ' + (maxTop - offset) + 'px)');
        }
      });
    
    });
    

    UPDATE

    $(document).ready(function(){
        var top = $('#pravyKonfig').offset().top - parseFloat($('#pravyKonfig').css('marginTop').replace(/auto/, 0));
        var max = $('#odber').offset().top - $('#pravyKonfig').outerHeight();
        $(window).scroll(function(evt){
            var y = $(this).scrollTop();
            $('#pravyKonfig').removeClass('fixed');
            if(y > top && y < max){
                $('#pravyKonfig').css('transform', 'translate(0px, ' + (y - top) + 'px)');
            }else if(y < top){
                $('#pravyKonfig').css('transform', 'translate(0px, 0px)');
            }else if(y > max){
                $('#pravyKonfig').css('transform', 'translate(0px, ' + (max - top) + 'px)');
            }
        });
    });