Fixed Position of An Element Relevant to Parent


/ Published in: JavaScript
Save to your folder(s)

Great for those situations where you need an element fixed on a page - so when a user scrolls it stays in the same position - *relative to its parent element*.


Copy this code and paste it in your HTML
  1. var top = $('#tabs').offset().top - parseFloat($('#tabs').css('marginTop').replace(/auto/, 0));
  2. $(window).scroll(function (event) {
  3. // what the y position of the scroll is
  4. var y = $(this).scrollTop();
  5.  
  6. // whether that's below the form
  7. if (y >= top) {
  8. // if so, ad the fixed class
  9. $('#tabs').addClass('fixed');
  10. } else {
  11. // otherwise remove it
  12. $('#tabs').removeClass('fixed');
  13. }
  14. });
  15. });

URL: http://jqueryfordesigners.com/fixed-floating-elements/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.