
Untitled
By: a guest on
Apr 26th, 2012 | syntax:
None | size: 1.80 KB | hits: 14 | expires: Never
List with elements that attaches the top magically when scrolling
<h3>Category 1</h3>
<ul>
<li>blabla</li>
<li>blabla</li>
etc...
</ul>
<h3>Category 2</h3>
<ul>
<li>blabla</li>
<li>blabla</li>
etc...
</ul>
<h3>Category 3</h3>
etc...
$('#scroller').scroll(function () {
var positions = $('h3', this).map(function() {
return {
top: $(this).position().top,
el: this
};
}).get();
//Go backwards through the array and pick the first negative (smallest) value
for(var i = positions.length - 1; i >= 0; i--) {
if(positions[i].top < 0) {
$('#header').text($(positions[i].el).text());
return;
}
}
});
$('#scroller').scroll(function () {
var category = '';
$($('h3', this).get().reverse()).each(function () {
if($(this).position().top < 0) {
category = $(this).text();
return false;
}
});
$('#header').text(category);
});
<div style="position:fixed;right:0px;" id="place">Category 1</div>
<h3>Category 1</h3>
<ul>
<li>blabla</li>
<li>blabla</li>
etc...
</ul>
<h3>Category 2</h3>
<ul>
<li>blabla</li>
<li>blabla</li>
etc...
</ul>
<h3>Category 3</h3>
<ul>
<li>blabla</li>
<li>blabla</li>
etc...
</ul>
<script>
var headers = document.getElementsByTagName("h3");
var place = document.getElementById("place");
addEventListener("scroll", function(e) {
var scroll = document.body.scrollTop;
var foundHeader = false;
for(var i = headers.length-1; i >= 0; i--) {
var h = headers[i];
var top = h.offsetTop;
if(!foundHeader && scroll+50 > top) {
place.innerHTML = h.innerHTML;
foundHeader = true;
}
}
}, true);
</script>