You can't really know which div is scrolled to. You can compare the original location of a div (relative to document), and see if the scrolled window has reached that location.
window.pageYOffset
will give you the number of pixels the document has already scrolled to, whenever it is requested. Now what you'll need is to attach an event listener to the scroll
event, give it the relative-to-document-top location of #01-02-2015
div, and checks to see if window.pageYOffset
is greater than that. If it is, you can replace the month name. If it's less, you can replace it back.
To know the #01-02-2015
div's offset relative to document, you can jquery's offset()
function, or try out the following and let me know if it works:
function getOffsetTop(element){
var offsetTop = 0;
do {
if ( !isNaN( element.offsetTop ) )
offsetTop += element.offsetTop;
} while( element = element.offsetParent );
return offsetTop;
}
(Adapted from finding element's position relative to the document )
** EDIT **
So, as you say the getOffsetTop
function works. At page load, you'll want to get the locations/offsets of all the .first
div's, and let's assume you also gave them a class or data-id
with the specific month. So, let's start by creating an array of these values, like:
var firsts = document.querySelectorAll('.first');
var array = []
for(var i=0;i<firsts.length;i++)
array.push({month:firsts[i].getAttribute('data-id'), offset:getOffsetTop(firsts[i])});
Now you have an array that looks like [{month:'january',offset:214},{month:'february',offset:462}...]
.
Again, without looking at code, I'm thinking you will need to have a global (or anyway declared outside the scroll function) variable, declared at load time, that stores the index of the current month being looked at (assuming window.pageYOffset
is zero then, you can start with array[0]). The scroll function will need to keep checking against the array item before and after this month to see if either of those scroll points are being reached, and if so, change the div content as you need, and also update the currentMonth
variable. Something like:
var currentMonth = 0;
window.onscroll = function(){
var index = currentMonth;
if(array[index-1] && window.pageYOffset < array[index-1].offset)){
// change the specific div's innerHTML to that of previous one. You can also target a particular `first` by using document.querySelector('.first[data-id="'+array[index].month+"]'):
currentMonth = currentMonth - 1;
}
else if(array[index+1] && window.pageYOffset > array[index+1].offset)){
// change the div to next one
currentMonth = currentMonth + 1;
}
}
I haven't tested any of this but let me know how you make out, or if the console throws errors.
** EDIT3 **: MDN reference (link) recommends using window.pageYOffset
instead of window.scrollY
for cross-browser compatibility, so I've updated my answer.