How To Keep An Element At The Top Of Its Parent jQuery

To keep an element sticky you will have to use fixed position in css but to keep an element at the top of its parent we will have to use some javascript because we can't to that only with css only if the structure will allow us to that. In some cases due to auto generated html from some jquery plugins we can't change the structure in order to achive what we need, so in this cases we will use javascript to keep the element at the top of its parent

Required steps to keep and element at the top of its parent

First of all we will need to do some checks using jquery, and these steps are the following:

  • Add scroll event on the scrollable element
  • Check height of the main element
  • Check the distance already scrolled from the top
  • Add the distance already scrolled to our element which have to be fixed at the top

All these steps can be achived using the following jquery function:

jQuery('.scrollable_element').on('scroll', function(){
  var content_area = jQuery('#content_textarea').outerHeight(),
    offset_top = jQuery(this).scrollTop();
  if(content_area >= offset_top){
    jQuery('.sticky_element').css('top', offset_top);
  }
});

Try the function and let me know if it worked in your case, if not tell us your issue and we will happy to help you.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x