I built this very basic .map () function with jQuery to store the upper offsets of my HTML sections in an array (inside the script tag at the very end of the body):
JQuery
$(window).load(function() {
var obj = $(this),
sec = $('section'),
arr = sec.map(function() {
return obj.offset().top
}).get();
})
It is almost as simple as in the jQuery documentation . And it already worked! ... Until a week ago.
My HTML (jade [compiled with CodeKit]) has a very simple structure:
HTML
body.preload
section#id1
whateverContent
section#id2
moreContent
section#id3
evenMoreContent
...
Surprisingly, today the console decided to tell me that top undefined:
Console
Uncaught TypeError: Cannot read property 'top' of undefined
.map() section , :
DOM .
, .
, ?
? - ? , , ? - ? CodeKit? !
, JS ( ):
$(window).load(function() {
$('body').removeClass('preload')
var win = $(window),
doc = $(document),
obj = $(this),
sec = $('section'),
nav = $('nav'),
anc = $('nav a'),
pos = nav.offset().top,
arr = sec.map(function() {
return obj.offset().top
}).get(),
act = function() {
win.scrollTop() > pos ? nav.addClass('sticky')
: nav.removeClass('sticky'),
$.each(arr, function(i, val) {
(win.scrollTop() > val && win.scrollTop() < (val + sec.eq(i).outerHeight(true) + 1) ) ? anc.eq(i).addClass('active')
: anc.eq(i).removeClass('active')
})
};
win.scroll(act)