jQuery plugin for making an element fixed when it goes out of view.
- detecting when an element goes out of view and making it fixed
- replacing the element with an invisible clone that will temporarily occupy the original spot
- updating size and position of the fixed element
Tested in Mozilla Firefox, Google Chrome, Safari, Opera and MSIE 7+
The plugin provides a single jQuery method you can use:
- element - element that will be fixed
- options - object with various settings (see list below)
Name | Default | Description |
---|---|---|
fixClass | "scroll-fix" | Class added to the element when it is fixed. |
fixTop | 0 | Top offset of the fixed element. |
fixOffset | 0 | Offset aplied when detecting whether to fix the element. |
unfixOffset | 0 | Offset aplied when detecting whether to unfix the element. |
syncSize | true | Update element's size when it is fixed. |
syncPosition | true | Update element's position when it is fixed. |
style | true | Apply position: fixed and top: ..px directly to the element when it is fixed. Disable this if you wish to style the element through your own CSS rules using the fixClass (example: #myElement.scroll-fix {position: fixed;} ). |
null | Custom function to call when the fixed element is updated. The function is passed an instance of Shira.ScrollFix.Watcher .This option is deprecated. Use DOM events instead. |
List of dom events dispatched by the watcher:
Name | Description |
---|---|
fix.shira.scrollfix | fired before the element is fixed; calling e.preventDefault() will prevent fixing |
fixed.shira.scrollfix | fired after the element has been fixed |
update.shira.scrollfix | fired after a fixed element has been updated |
unfix.shira.scrollfix | fixed before the element is unfixed; calling e.preventDefault() will prevent unfixing |
unfixed.shira.scrollfix | fired after the element has been unfixed |
All of the event objects have a property called watcher
that contains an instance of Shira.ScrollFix.Watcher
.
$('#myelement')
// listen to the "fixed" and "unfixed" events
.on('fixed.shira.scrollfix unfixed.shira.scrollfix', function (e) {
// make the background green when fixed, red otherwise
$(this).css('background-color', e.watcher.fixed ? 'green' : 'red');
})
// apply scrollfix
.scrollFix()
;
The following data attributes are available after the plugin is applied to an element.
Call $(element).data('key')
to access the value.
shira.scrollfix
- instance ofShira.ScrollFix.Watcher