jQuery Plugin For Better CSS Position:Sticky - Sticky.js

jQuery Plugin For Better CSS Position:Sticky - Sticky.js
File Size: 112 KB
Views Total:
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

Sticky.js is a jQuery plugin to enhance the CSS position: sticky property that makes your sticky element fit within the viewport height. The plugin has the ability to automatically enable/disable the function depending on the current screen size.

Installation:

# NPM
$ npm install sticky.jquery.js --save

How to use it:

1. Create a normal sticky element using CSS position: sticky property.

<aside class="sidebar sticky-sidebar-css">
  <h3>Sticky Sidebar</h3>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ut urna
    id nisi mollis sagittis. Donec erat tellus, dignissim id elit a, lacinia
    dignissim odio. Vestibulum ac ligula libero. Ut id ullamcorper est, id
    porttitor mi. Phasellus vel ligula sit amet mauris suscipit lacinia.
    Maecenas orci metus, iaculis sed fringilla nec, aliquam sit amet augue.
    Integer lorem dolor, convallis ut arcu sed, feugiat rutrum ante.
  </p>
</aside>
.sticky-sidebar-css {
  position: sticky;
  position: -webkit-sticky;
  top: 0; /* required */
}

2. Download and insert the jQuery Sticky.js plugin after jQuery JavaScript library.

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" 
        integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" 
        crossorigin="anonymous">
</script>
<script src="sticky.jquery.min.js"></script>

3. Enable the plugin with just one line of code:

(function($) {

  $('.sticky-sidebar-css').sticky();

})(jQuery);

4. Set the default CSS position property:

$('.sticky-sidebar-css').sticky({
  /*
   * This should be the position if you wouldn't use "position: sticky;". If
   * the element was positioned absolute then you would specify absolute.
   * Otherwise relative.
   */
  defaultPosition: 'relative',
});

5. Enable/disable the plugin based on the screen size.

$('.sticky-sidebar-css').sticky({
  breakpoints: [
    {
      min: 0,
      max: 768,
    },
  ],
});

Change logs:

2018-01-20

  • fixed working version on safari; fixed calcalculation when scrolling up;

2017-10-25

  • v2.1.4

2017-10-16

  • check if element exists on the page;

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