Created
January 27, 2014 15:20
-
-
Save sergiolopes/8650300 to your computer and use it in GitHub Desktop.
Código que cuida do scroll das apostilas da Caelum e faz a URL acompanhar a seção atual.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// funcionalidade de trackear a seção scrollada no #hash da URL | |
define(['fw/Query', 'domready'], function(Q){ | |
// helper fn: | |
// observa scroll e resize e rotate mas com limite de rate. | |
function onSmoothScroll(callback, interval) { | |
var timer = undefined; | |
Q(window).on('scroll, resize, rotationchange', function () { | |
timer && clearTimeout(timer); | |
timer = setTimeout(callback, interval); | |
}); | |
} | |
// feature detect: | |
// só aceita se tiver History API | |
if (!("history" in window && "replaceState" in window.history)) return; | |
// indica que o proximo scroll deve ser cancelado | |
var cancelScroll = false; | |
// cache das secoes do documento | |
var secoes = document.querySelectorAll('.section'); | |
if (secoes.length == 0) return; | |
// descobre a seção sendo vista | |
onSmoothScroll(function(){ | |
// limite para troca de seção é o título ter passado da metade | |
// da parte visível da tela. | |
var limite = Math.floor(window.scrollY + window.innerHeight / 2); | |
// percorre todos as seções em busca da atualmente visivel | |
var secaoAtual = undefined; | |
for (var i = 0; i < secoes.length; i++) { | |
// ja passamos da altura? o ultimo 'secaoAtual' que vale entao | |
if (secoes[i].offsetTop > limite) break; | |
secaoAtual = secoes[i]; | |
} | |
// manda a secaoAtual pra History | |
if (secaoAtual !== undefined) { | |
var slug = secaoAtual.getAttribute('data-section'); | |
if (slug !== location.hash.replace('#','')) { | |
history.replaceState({scroll: true}, '', '#' + slug); | |
} | |
} else if (location.hash.replace('#','') !== '' && location.pathname) { | |
// se nao houver secao selecionada, provavelmente estamos no topo do capitulo. | |
// ai é melhor nao ter #hash nenhum e deixar a URL do capitulo mesmo. | |
history.replaceState({scroll: true}, '', location.pathname); | |
} | |
}, 200); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment