JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://bigspotteddog.github.io/ScrollToFixed/jquery-scrolltofixed-min.js"></script>
<script src="http://www.jsviews.com/download/jsrender.min.js"></script>
<body>
<script id="template" type="text/x-jsrender">
<div class="marker-container">
<div class="marker">Date {{>number}}</div>
</div>
<div class="section">One event</div>
<div class="section">Another event</div>
</script>
<div class="wrapper"></div>
</body>
CSS
body {
margin-top:10px;
}
.wrapper {
width: 500px;
margin: 0 auto;
}
.marker {
position: absolute; // This is important!
margin: 0 auto;
width: 200px;
height: 98px;
border: 3px dashed red;
text-align: center;
font-size: 20px;
}
.section {
margin: 0;
text-align: center;
font-size: 40px;
height: 800px;
border: 3px #666 dashed;
}
JavaScript
$(function() {
function addContainers() {
var nextN = $('.marker-container').length + 1;
var containers = []
// Each container has 2 sections now
for(var i = nextN; i <= nextN + 1; i++) {
containers.push({ number: i})
};
$(".wrapper").html($(".wrapper").html() + $("#template").render(containers));
}
function registerMarkers() {
var collection = $('.marker');
$.each(collection, function(index, marker) {
// The last element always does not have a limit
if (index == collection.length - 1) {
if ($.isScrollToFixed(marker)) $(marker).trigger('remove.ScrollToFixed');
$(marker).scrollToFixed();
} else {
var nextMarker = $(collection[index + 1]);
// Skip current, if it and the following one are already registered
if ($.isScrollToFixed(marker) && $.isScrollToFixed(nextMarker)) return true;
// On this stage we have all unregistered markers and the last registered one, which precedes the first unregistered marker.
var nextMarkerC = nextMarker.parent(); // For offsets we rely on stable position of marker container
$(marker).scrollToFixed({
limit: nextMarkerC.offset().top - 100
});
}
});
}
addContainers();
registerMarkers();
$(window).bind('scroll', function() {
// If we reached the end of window
if (document.body.scrollHeight - $(this).scrollTop() <= $(this).height()) {
addContainers();
registerMarkers();
}
});
});