7537247
7537247

Reputation: 323

Fix positioned element stops at certain point when scrolling

box2 is a fix positioned element, I need it stops at the top and bottom of box1 when scrolling. Any help would be appreciated.

   $(window).scroll(function() {
     var h1 = $('.box1').height();
     var h2 = $('.box2').height();
     var h3 = $('.footer').outerHeight(true);
    $('.box2').css('bottom', h3);
});

example

Upvotes: 1

Views: 424

Answers (2)

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

If I understand the question correctly, you want box2 to appear static within the viewport, except it should never go above or below box1's extent.

Use this code:

$(window).scroll(function() {
  var scrollTop= $(window).scrollTop(),
      b1= $('.box1'),
      b2= $('.box2'),
      min= b1.position().top,
      max= (b1.position().top + b1.outerHeight()) - b2.outerHeight();

  b2.css({
    top: Math.min(Math.max(scrollTop,min),max) - scrollTop
  });
});

Working Fiddle

Upvotes: 4

Dustin Hayes
Dustin Hayes

Reputation: 236

Great answer from Rick Hitchcock, made some improvements:

var $b1 = $('.box1'); // 1
var $b2 = $('.box2'); // 1
var min = $b2.position().top; // 2

$(window).scroll(function() {
  var scrollTop = $(window).scrollTop();
  var max = ($b1.position().top + $b1.outerHeight()) - $b2.outerHeight();

  $b2.css({
    top: Math.min(Math.max(scrollTop, min), max)
  });
});
  1. Cache DOM queries
  2. Make min the original top of $b2 on page load.

jsbin demo

Upvotes: 1

Related Questions