Skip to content

Instantly share code, notes, and snippets.

@jtwalters
Last active February 5, 2019 23:28
Show Gist options
  • Save jtwalters/4c6ce689472fcdb3a4c6 to your computer and use it in GitHub Desktop.
Save jtwalters/4c6ce689472fcdb3a4c6 to your computer and use it in GitHub Desktop.
List with sticky headings/titles, where each sticky element is constrained/bound to its parent. Requires jQuery, Waypoints (http://imakewebthings.com/waypoints/)
/**
* Sticky, single elements bound to their containers.
* Parent: .sticky-single
* Child: .sticky-single__element
*/
$('.sticky-single__element').each(function initializeStickySingle() {
// Create an "enter" sticky-single waypoint handler.
new Waypoint({
element: this,
offset: 0,
handler: function (direction) {
if (direction === 'down') {
$(this.element).addClass('sticky-single--stuck');
}
else {
$(this.element).removeClass('sticky-single--stuck');
}
},
});
// Create an "exit" sticky-single waypoint handler.
new Waypoint({
element: this,
offset: function () {
var containerHeight = $(this.element).parents('.sticky-single').height(),
elementHeight = $(this.element).outerHeight(true);
// Calculate the offset as the difference of the container height and
// element height.
// The trigger point is effectively the top of the element when the element hits
// its parent's bottom.
return containerHeight + elementHeight;
},
handler: function (direction) {
if (direction === 'down') {
$(this.element).addClass('sticky-single--bottom');
}
else {
$(this.element).removeClass('sticky-single--bottom');
}
},
});
// If you change around the DOM or sizing yourself, you'll need to refresh your waypoint trigger points.
// Waypoint.refreshAll();
});
.sticky-single {
position: relative;
}
.sticky-single--stuck {
position: fixed;
top: 0;
z-index: 10;
}
.sticky-single--bottom {
position: absolute;
top: auto;
bottom: 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment