Super sticky

Options

Vertical Layout Position

By default, a StickyBits element will stick to the top of the viewport when vertically scrolled to.

Stickybits loosely works for positioning as well.

To have a StickyBits element stick to the :

stickybits('selector', {verticalPosition 'bottom'});

Custom Scroll Element

By default, if Stickybits uses scrolling to define Sticky Elements. An element besides can be used if is by selecting the desired scrolling element with the option. For more custom sticky featuring, the option can be used. However, those implementations require the implementing developers support.

To have Stickybit use an selector besides :

stickybits('selector', {scrollEl 'an-id'});

StickyBit Sticky Offset

By default, a StickyBits element will have a sticky layout top offset. This means that the element will stick flush to the top of the viewport.

To have a StickyBits element stick with a offset to its vertical layout position:

stickybits('selector', {stickyBitStickyOffset 20});

StickyBits Cleanup

To cleanup an instance of Stickybits:

const stickybitsInstancetoBeCleanedup = stickybits('selector');
stickybitsInstancetoBeCleanedup.cleanup();

StickyBits Update

To update the calculations of an instance of Stickybits:

const stickybitsInstancetoBeUpdated = stickybits('selector');
stickybitsInstancetoBeUpdated.update();

Re-calculates each Stickybits instance’s offsets (stickyStart, stickyStop).
If the Stickybits implementer would like re-calculate offsets when the DOM window is resized or when the url changes. can be invoked within an event listener.

const stickybitsInstancetoBeUpdated = stickybits('selector');
stickybitsInstancetoBeUpdated.update({ stickyBitStickyOffset 20 });

More Stickybits Update Examples

// when the window is resized
const stickybitsInstancetoBeUpdated = stickybits('selector');
window.addEventListener('resize', () => {
  stickybitsInstancetoBeUpdated.update();
});
// when the url hash changes
window.addEventListener('hashchange', () => {
  stickybitsInstancetoBeUpdated.update();
});

Note: does not re-initialize classnames or pre-set calculations. Perhaps the update value can help you with that (see the paragraph below).

StickBits Update Props

Props can be updated to each instance by passing then into the function as an object.

// .update({ someProp: somePropValue })
const stickybitsInstancetoBeUpdated = stickybits('selector');
stickybitsInstancetoBeUpdated.update({ stickyBitStickyOffset 20 });

To use StickyBits without inline styles except for or :

stickybits('selector', {noStyles true});

StickyBits Custom CSS Classes

To use custom CSS classes for Stickybits, add the appropriate properties and values.

parentClass:

stickybits('selector', {parentClass 'new-parent-classname'});

stickyClass:

stickybits('selector', {stickyClass 'new-sticky-classname'});

stuckClass:

stickybits('selector', {stuckClass 'new-stuck-classname'});

StickyBits useFixed

To not use ever, add the following key value to a stickybit initalization.

parentClass:

stickybits('selector', {useFixed true});

To change all of the CSS classes

stickybits('selector', {
  parentClass 'new-parent-classname',
  stickyClass 'new-sticky-classname',
  stuckClass 'new-stuck-classname',
  stickyChangeClass 'new-sticky-change-classname'
});
stickybits('selector', {useGetBoundingClientRect true});

* For jQuery and Zepto support, read the jQuery notes .

StickyBits applyStyle

If you want to take control of how styles and classes are applied to elements
provide a function . This is useful for example if you want to
integrate with a framework or view library and want to delegate DOM
manipulations to it.

stickybits('selector', {
  applyStyle ({ classes, styles }, instance) => {
    // Apply styles and classes to your element
  }
});

Options

  • : (default: ) Pixels between the page top and the element’s top.
  • : (default: ) Pixels between the page bottom and the element’s bottom.
  • : (default: ) CSS class added to the element’s wrapper when «sticked».
  • : (default: ) CSS class added to the wrapper.
  • : (default: ) Boolean determining whether the sticky element should be horizontally centered in the page.
  • : (default: ) Selector of element referenced to set fixed width of «sticky» element.
  • : (default: ) Boolean determining whether width of the «sticky» element should be updated to match the wrapper’s width. Wrapper is a placeholder for «sticky» element while it is fixed (out of static elements flow), and its width depends on the context and CSS rules. Works only as long isn’t set.
  • : (default: ) Boolean determining whether widths will be recalculated on window resize (using getWidthfrom).
  • : (default: ) controls z-index of the sticked element.

useStickyClasses Feature

By default, if is supported, StickyBits will exit allowing the browser to manage stickiness and avoid adding a event listener.

If the argument is set to then even if a browser supports , StickyBits will still add a event listener to . This option is available so that CSS styles can use when StickyBits elements become sticky or stuck at the bottom of their parent.

To provide more feature richness to the Stickybits experience, a CSS class is added after the Stickybit element is sticky for a certain duration of scroll. By default this duration of scrolling is the height of the Stickybit element. The scroll duration for when is added can be modified by providing a number for option.

To use :

stickybits('selector', {useStickyClasses true});

Then, in css you can do:

.some-sticky-element.js-is-sticky {
  background-color: red;
}
.some-sticky-element.js-is-sticky--change {
  height: 50px;
}
.some-sticky-element.js-is-stuck {
  background-color: green;
}

View for more information on StickyBits CSS Classes.

Notes

CSS Class Usage

3 CSS classes will be added and removed by Stickybits if is not supported or if the option is added to the plugin call. These Classes can be modified as desired. See the With Custom Classes example above.

  • if the selected element is sticky.
  • if the selected element is stopped at the bottom of its parent.
  • so that styles can easily be added to the parent of a Stickybits element

Not a Polyfill

Stickybits is a no dependency JavaScript plugin. It provides the smallest API possible in both features and kb size to deliver working sticky elements. This means that opinionated featuring is left out as much as possible and that it works with minimal effort in Frameworks.

CSS when is not supported

Sticky Start and Sticky Stop: Because Stickybits is minimal, when is not supported Stickybits will use which is relative to the browser window. If the StickyBits parent element has a height recognized by the browser, Stickybits will take care of the sticky top and sticky bottom invocation. If the parent’s height is not recognized by the browser there will be issues.

Left and Right Positioning: With the Stickybit element will work relative to the browser window by default. To work with this issue, there are several options. Some are noted here. More solutions to come!

jQuery and Zepto Usage

Basic

$('selector').stickybits();

With

$('selector').stickybits({scrollEl '#scrollEl'});

// or

const el = document.querySelector('#scrollEl');
$('selector').stickybits({scrollEl el});

With

const  instance = $('selector').stickybits();
instance.update();

With

$('selector').stickybits({useStickyClasses true});

With

$('selector').stickybits({verticalPosition 'bottom'});

With

$('selector').stickybits({stickyBitStickyOffset 20});

Events

  • : When the element becomes sticky.
  • : When the element returns to its original location
  • : When the element is sticked but position must be updated for constraints reasons
  • : When the element reached the bottom space limit
  • : When the element unreached the bottom space limit

To subscribe to events use jquery:

script>$('#sticker').on('sticky-start',function(){console.log("Started");});$('#sticker').on('sticky-end',function(){console.log("Ended");});$('#sticker').on('sticky-update',function(){console.log("Update");});$('#sticker').on('sticky-bottom-reached',function(){console.log("Bottom reached");});$('#sticker').on('sticky-bottom-unreached',function(){console.log("Bottom unreached");});script>

4. jQuery:

Call stickyNavbar function on the navigation wrapper (), nav tag or ul tag either without options object:

$(function () {
	 $('.header').stickyNavbar();
});

or with the options object:

$(function () {
	$('.header').stickyNavbar({
		activeClass "active", // Class to be added to highlight nav elements
		sectionSelector "scrollto", // Class of the section that is interconnected with nav links
		animDuration 350, // Duration of jQuery animation as well as jQuery scrolling duration
		startAt , // Stick the menu at XXXpx from the top of the this() (nav container)
		easing "swing", // Easing type if jqueryEffects = true, use jQuery Easing plugin to extend easing types - gsgd.co.uk/sandbox/jquery/easing
		animateCSS true, // AnimateCSS effect on/off
		animateCSSRepeat false, // Repeat animation everytime user scrolls
		cssAnimation "fadeInDown", // AnimateCSS class that will be added to selector
		jqueryEffects false, // jQuery animation on/off
		jqueryAnim "slideDown", // jQuery animation type: fadeIn, show or slideDown
		selector "a", // Selector to which activeClass will be added, either "a" or "li"
		mobile false, // If false, nav will not stick under viewport width of 480px (default) or user defined mobileWidth
		mobileWidth 480, // The viewport width (without scrollbar) under which stickyNavbar will not be applied (due user usability on mobile)
		zindex 9999, // The zindex value to apply to the element: default 9999, other option is "auto"
		stickyModeClass "sticky", // Class that will be applied to 'this' in sticky mode
		unstickyModeClass "unsticky" // Class that will be applied to 'this' in non-sticky mode
	});
});

Debugging

Stickybits 2.0 provides the same API but with more debugging feedback.

To view the Stickybits API in it’s simpliest form:

const  stickybit = stickybits('a selection');
console.log(stickybit);

For more debugging and managing Stickybits, view the wiki.

Utility properties

Stickybits provides both and properties which were added to offer insight into the browser and Stickybits.

These utility properties can be accessed as direct child properties of the instantiated Stickybits item.

const stickybit = stickybits('a selection')
stickybit.version // will show the version of stickybits being used
stickybit.userAgent // will show which userAgent stickybits is detecting

Usage

import Sticky from 'react-stickynode';

Sticky enabled={true} top={50} bottomBoundary={1200}>
    YourComponent>
Sticky>
import Sticky from 'react-stickynode';

Sticky top='#header' bottomBoundary='#content'>
    YourComponent>
Sticky>

Props

Name Type Note
Boolean The switch to enable or disable Sticky (true by default).
Number/String The offset from the top of window where the top of the element will be when sticky state is triggered (0 by default). If it is a selector to a target (via ), the offset will be the height of the target.
Number/String The offset from the top of document which release state will be triggered when the bottom of the element reaches at. If it is a selector to a target (via ), the offset will be the bottom of the target.
Number/String z-index of the sticky.
Boolean Enable the use of CSS3 transforms (true by default).
String Class name to be applied to the element when the sticky state is active ( by default).
String Class name to be applied to the element when the sticky state is released ( by default).
Function Callback for when the sticky state changes. See below.
Function Callback to indicate when the sticky plugin should freeze position and ignore scroll/resize events. See below.

Handling State Change

You can be notified when the state of the sticky component changes by passing a callback to the prop. The callback will receive an object in the format , with being an integer representing the status:

Value Name Note
The default status, located at the original position.
The released status, located at somewhere on document, but not default one.
The sticky status, located fixed to the top or the bottom of screen.

You can access the statuses as static constants to use for comparison.

import Sticky from 'react-stickynode';

const handleStateChange = (status) => {
    if (status.status === Sticky.STATUS_FIXED) {
        console.log('the component is sticky');
    }
}

Sticky onStateChange={handleStateChange}>
    YourComponent>
Sticky>

Also supports children functions:

import Sticky from 'react-stickynode';

Sticky>
  {status => {
    if (status.status === Sticky.STATUS_FIXED) {
      return 'the component is sticky';
    }
    if (status.status === Sticky.STATUS_ORIGINAL) {
      return 'the component in the original position';
    }
    return 'the component is released'
  }}
Sticky>

Freezing

You can provide a function in the prop which will tell the component to temporarily stop updating during prop and state changes, as well as ignore scroll and resize events. This function should return a boolean indicating whether the component should currently be frozen.

3. CSS:

Add class into your and style it as you like, eg.:

.active {
		color: #fff !important;
		text-decoration: underline !important;
		-webkit-transform: translate3d(, , );
		-moz-transform: translate3d(, , );
		-o-transform: translate3d(, , );
		-ms-transform: translate3d(, , );
		transform: translate3d(, , ); // hardware acceleration of CSS animation
}

Note: You can change class to anything you want and pass your own class into options object of stickyNavbar function.
Be sure to add to class if you want your page to be scrolled on top after each page refresh and not to vertical position presents before page refresh.

API

Adds the elements as stickies. Skips the elements that have stickies associated with them.

Refreshes all existing stickies, updates their parameters and positions.

All stickies are automatically refreshed after window resizes and device orientations changes.

There’s also a fast but not very accurate layout change detection that triggers this method. Call this method manually in case automatic detection fails.

Removes sticky associated with the element.

Removes stickies associated with the elements in the list.

Removes all existing stickies.

Sticky class. You can use it directly if you want:

conststicky=newStickyfill.Sticky(element);

Throws an error if there’s a sticky already bound to the element.

Refreshes the sticky, updates its parameters and position.

Removes the sticky. Restores the element to its original state.

Options

  • : (default: ) Pixels between the page top and the element’s top.
  • : (default: ) Pixels between the page bottom and the element’s bottom.
  • : (default: ) CSS class added to the element’s wrapper when «sticked».
  • : (default: ) CSS class added to the wrapper.
  • : (default: ) Boolean determining whether the sticky element should be horizontally centered in the page.
  • : (default: ) Selector of element referenced to set fixed width of «sticky» element.
  • : (default: ) Boolean determining whether width of the «sticky» element should be updated to match the wrapper’s width. Wrapper is a placeholder for «sticky» element while it is fixed (out of static elements flow), and its width depends on the context and CSS rules. Works only as long isn’t set.
  • : (default: ) Boolean determining whether widths will be recalculated on window resize (using getWidthfrom).
  • : (default: ) controls z-index of the sticked element.

API

Adds the element as a sticky. Returns new instance associated with the element.

If there’s a sticky associated with the element, returns existing instance instead.

Adds the elements as stickies. Skips the elements that have stickies associated with them.

Returns an array of instances associated with the elements (both existing and new ones).

Refreshes all existing stickies, updates their parameters and positions.

All stickies are automatically refreshed after window resizes and device orientations changes.

There’s also a fast but not very accurate layout change detection that triggers this method. Call this method manually in case automatic detection fails.

Removes sticky associated with the element.

Removes stickies associated with the elements in the list.

Removes all existing stickies.

Force-enable the polyfill, even if the browser supports natively.

Array of existing instances.

Sticky class. You can use it directly if you want:

const sticky = new Stickyfill.Sticky(element);

Throws an error if there’s a sticky already bound to the element.

Refreshes the sticky, updates its parameters and position.

Removes the sticky. Restores the element to its original state.

Usage

Include after jQuery in your header or elsewhere on your page.

Stick an Element

The below example demonstrates a navigation div that sticks to the top of the screen after the element’s bottom has been
reached while scrolling down and un-sticks when the top of the element has been reached while scrolling up.

$('#sticky-nav').sticky({
    start 'bottom',
    end 'top'
});

Available property values for and are , and .

Smooth Element Transitions

Often when an element moves from being positioned relatively to fixed the effect is a page jump. jQuery.sticky attempts
to solve for this.

$('#sticky-nav').sticky({
    start 'bottom',
    end 'bottom',
    smooth true
});

Stack Multiple Stickies

Sometimes you’ll want multiple elements to stick to the top when they scroll out of view and stack in their relative
order.

$('#sticky-nav-1, #sticky-nav-2, #sticky-nav-3').sticky({
    start 'bottom',
    end 'top',
    smooth true,
    stack true
});

Callbacks On Sticky Events

It is often useful to have the ability to run some of your own code after an element has become a «sticky» or after it
has gone back to its original positioning.

$('#sticky-nav-1, #sticky-nav-2, #sticky-nav-3').sticky({
    start 'bottom',
    end 'bottom',
    smooth true,
    stack true,
    onStick function( elm ) {
        elm.addClass('transition');
    },
    onUnstick function( elm ) {
        elm.removeClass('transition');
    }
});

Adding an Offset

Sometimes you’ll want to trigger your sticky element at an arbitrary point. To do this add an offset. This allows you to
stick/unstick your element at a defined distance before the element reaches the top of the screen.

$('#sticky-nav-4').sticky({
    start 'top',
    end 'top',
    smooth true,
    stack true,
    offset 50,
    onStick function( elm ) {
        elm.addClass('transition');
    },
    onUnstick function( elm ) {
        elm.removeClass('transition');
    }
});

The above code triggers the stick event 50 pixels before the element reaches the top of the screen (or element stack if other
elements are being stuck).

Scrolling Callback

As a convenience you can attach a callback to the scroll event. This way you don’t need to create an additional scroll handler.

$('#sticky-nav-4').sticky({
    start 'top',
    end 'top',
    smooth true,
    stack true,
    onScroll function( elm ) {
        console.log('Yay, I am scrolling!');
    }
});

Ordering execution

On a site with many dependencies or multiple JavaScript files being loaded out of order it can sometimes be crucial to set the
initialization order of jquery.sticky. When the property is set all instances of jquery.sticky must use the property. The
order starts at 1 and sequentially ends at an increment of your last initialization (if your initializing jquery.sticky 4 times your
order properties will be 1 through 4. If you skip any numbers in between some of your jquery.sticky initializations will not work.

$('#sticky-nav-3').sticky({
    start 'top',
    end 'top',
    smooth true,
    stack true,
    offset ,
    order 3,
    onStick function( elm ) {
        elm.addClass('transition');
    },
    onUnstick function( elm ) {
        elm.removeClass('transition');
    }
});
$('#sticky-nav-1').sticky({
    start 'bottom',
    end 'top',
    smooth true,
    stack true,
    order 2,
    onStick function( elm ) {
        console.log('stick');
        elm.addClass('transition');
    },
    onUnstick function( elm ) {
        console.log('unstick');
        elm.removeClass('transition');
    }
});
$('#sticky-nav-4').sticky({
    start 'top',
    end 'top',
    smooth true,
    stack true,
    offset ,
    order 1,
    onStick function( elm ) {
        elm.addClass('transition');
    },
    onUnstick function( elm ) {
        elm.removeClass('transition');
    }
});

How CSS Position Sticky Really Works!

CSS position sticky has two main parts, sticky item & sticky container.

Sticky Item — is the element that we defined with the styles. The element will float when the viewport position matches the position definition, for example: .

Example

.some-component{    position: sticky;    top: 0px;}

Sticky Container —is the HTML element which wraps the sticky item. This is the maximum area that the sticky item can float in.

When you define an element with you’re automatically defining the parent element as a sticky container! This is very important to remember! The container is the scope of the sticky item, and the item can’t get out of its sticky container.

This is the reason why in the previous example, the sticky item didn’t stick in the first place: The sticky item was the only child element in a sticky container.

Visual Example of CSS Position Sticky:

Sticky item & Sticky container

CodePen Example:

Changelog

1.3.0

  • set keyboard focus to selected section after navigation — pull request #26 by @jacktonkin
  • allow relative links — pull request #25 by @stebru
    06/06/2015

1.2.0

  • new scrolling logic
  • fix: conditional checking if the selector option is an ‘li’ then get the child’s href attribute — pull request #21 by @dbrw
    21/03/2015

1.1.0

  • stickyMode/unstickyMode class added
  • custom mobileWidth for turning off stickyNavbar
  • window.outerWidth(true) changed to window.width() according to jQuery docs
  • optional z-index setting
  • added animation duration and easing for scrolling
  • bottomAnimation option removed (unstable behaviour)
  • navOffset option removed (unstable behaviour)
  • credits for feature requests/points: @Phyxion, @oniric85, @coolboy4598
    23/07/2014

Options

HC Sticky has a wide range of options you can set to have a full controll over the sticky elements.

Property Default Type Description
int The distance from the top of the Window at which to trigger HC-Sticky.
int The distance from the bottom of the Window at which to attach HC-Sticky.
int The distance from the top inside of the sticky element at which to trigger HC-Sticky.
null string / element object Element inside of the sticky element at which to attach HC-Sticky. This has higher priority than innerTop option.
int The distance from the bottom of the referring element at which to stop HC-Sticky.
null (parent element) string / element object Element that represents the reference for height instead of height of the container.
true boolean When set to , sticky content will not move with the page if it is bigger than Window.
‘sticky’ string HTML class that will be applied to sticky element while it is attached.
null object Object containing responsive breakpoints, on which you can tell HC Sticky what to do.
false boolean Direction of the responsive queries.
false boolean Disable the plugin. Usualy used with responsive object.
null function Callback function fired when the element becomes attached.
null function Callback function fired when the element stops floating.
null function Callback function fired before sticky has been resized (happens after Window resize and before sticky reinit).
null function Callback function fired after sticky has been resized (happens after Window resize and sticky reinit).
100 int Limit the rate at which the HC Sticky can fire on window resize.

More on how to use the responsive object .

Methods

Methods are used to control the plugin after initialization.

Method Accepts Description
string Returns current settings, or a specific setting if you specify it.
object Updates the settings with the new ones.
N/A Recalculates sticky size and position. Useful after altering DOM elements inside sticky.
N/A Detaches the HC-Sticky from element, preventing it from running.
N/A Attaches the HC-Sticky back to the element.
N/A Completely destroys HC-Sticky and reverts element to original state.

Options

  • : sets up className for the placeholder element, which is created to hold original element’s place in flow. Default value is .
  • : when true, the plugin will recalculate placeholder’s height. Otherwise, your CSS should define it. Defaults to .
  • : applies the plugin even if the browser has native position:sticky support. May be useful for testing.
  • : writes some info to browser’s console.
  • : copies parent’s width. Enabled by default.
  • : class added when stuck.

Example with options:

$('.i-sticky').iSticky({
    holderClass      'i-sticky__holder',
    holderAutoHeight false
});
/* if holderAutoHeight is off, don't forget to set some styles
   for the placeholder, generated by plugin */
.i-sticky + .i-sticky__holder {
    height: 30px;
}
Ссылка на основную публикацию