Awesome Sticky Element Without Content Jumping

File Size: 5.33 KB
Views Total: 4326
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Awesome Sticky Element Without Content Jumping

A simple and lightweight jQuery script to fix any element (typically header navigation) to the top of the webpage when scrolling down.

The script provides a quick fix to prevent the fixed positioned element jumping when scrolling & resizing the webpage.

How to use it:

1. Create an element that is pinned to the top when scrolling.

<nav class="sticky">
  <p>jQuery Script</p>
</nav>

2. Make the element sticky using the position: fixed propery.

.sticky {
  transition: ease .3s;
}

.sticky-pin {
  position: fixed;
  top: 0;
}

3. Include the necessary jQuery library at the bottom of the webpage.

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" 
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" 
        crossorigin="anonymous">
</script>

4. The main function for the sticky element.

var stickyElement = $(".sticky"),
    stickyClass = "sticky-pin",
    stickyPos = stickyElement.offset().top, //Distance from the top of the window.
    stickyHeight;

// Sticker function:
function stickerFn() {
  var winTop = $(this).scrollTop();
  //Check element position:
  winTop >= stickyPos ?
    stickyElement.addClass(stickyClass):
    stickyElement.removeClass(stickyClass) //Boolean class switcher.
};
stickerFn(); //Run.

// Function trigger:
$(window).scroll(function(){
  stickerFn();
});

5. Create a negative margin to prevent content 'jumps':

stickyElement.after('<div class="jumps-prevent"></div>');
function jumpsPrevent() {
  stickyHeight = stickyElement.innerHeight();
  stickyElement.css({"margin-bottom":"-" + stickyHeight + "px"});
  stickyElement.next().css({"padding-top": + stickyHeight + "px"}); 
};
jumpsPrevent(); // Run.

// Function trigger:
$(window).resize(function(){
  jumpsPrevent();
});

This awesome jQuery plugin is developed by TatianaPost. For more Advanced Usages, please check the demo page or visit the official website.