Outlaw011
Outlaw011

Reputation: 103

Absolute positioning but only inside div

I am having issues with sticky javascript function which allows fixed positioning of the div.

This is the function:

$(function(){ // document ready
  if (!!$('.sticky').offset()) { // make sure ".sticky" element exists
    var stickyTop = $('.sticky').offset().top; // returns number 
    $(window).scroll(function() { // scroll event
      var windowTop = $(window).scrollTop(); // returns number 
      if (stickyTop < windowTop) {
    $('.sticky').css({ position: 'fixed', width: 'inherit', top: 10 });
      } else {
    $('.sticky').css('position','static');
      }
    });
  }
});

But I need that to happen only inside the parent div, not the whole page. Here is the example:

http://www.astroprodavnica.com/59/izrada-i-tumacenje-natalne-karte.html

It is the div on the right.

Upvotes: 1

Views: 236

Answers (2)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

while you use fixed position you need to use (relative parent position will not work with fixed child)

if (windowTop > stickyTop 
  && windowTop < $('.right').offset().top + $('.right').outerHeight(true)) {
    $('.sticky').css({ position: 'fixed', width: 'inherit', top: 10 });
  }else if(windowTop < stickyTop ){
     $('.sticky').css('position','static');
  }else{
    $('.sticky').css('position','absolute').css('bottom', '0px');
  }

Upvotes: 0

scareddragon
scareddragon

Reputation: 445

Parent div should have position: relative or any other than static, which is used by default.

Then to position inside this parent, child should have position: absolute.

You can read more about positioning e.g. here.

Upvotes: 3

Related Questions