I am trying to build a ‘scrollSpy’ type function. I don’t know how to compare an argument against some values in an object, and return the (numerically) highest value’s name.
I have some markup:
<ul class="nav">
<li><a href="a"></a></li>
<li><a href="b"></a></li>
<li><a href="c"></a></li>
<li><a href="d"></a></li>
<li><a href="e"></a></li>
<li><a href="f"></a></li>
</ul>
<section id="a" class="scrollspy"></section>
<section id="b" class="scrollspy"></section>
<section id="c" class="scrollspy"></section>
<section id="d" class="scrollspy"></section>
<section id="e" class="scrollspy"></section>
<section id="f" class="scrollspy"></section>
And some script that creates an object consisting of each section and its distance in px from top:
var obj = {
sectionOffset: {},
scrollSpy: function (scrolled) {
// This should look in the object with the offset values, and from all
// the values that (scrolled) is higher than, take the largest, and
// return its name.
}
}
$(function () {
$(window).scroll(function () {
obj.scrollSpy($(document).scrollTop());
});
// Create an object consisting of all elements I want to 'spy' on.
// Names and values are made of element ID and top offset respectively.
$('.scrollspy').each(function () {
obj.sectionOffset[$(this).attr('id')] = (parseInt($(this).offset().top));
});
});
After I loop through the elements I want, it produces an object like:
{
d: 5195,
b: 3245,
a: 1319,
f: 5682,
c: 2139,
e: 3343
}
Just to be clear, if the user scrolls 3000px down the page, the function should return c.
1 Answer