Last active
August 29, 2015 13:57
-
-
Save pedrochaves/9690776 to your computer and use it in GitHub Desktop.
Esboço simples de scroll infinito
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
(function($) { | |
var // Distância entre o fundo da tela e a altura. Quanto maior o valor, mais rapido ele vai buscar | |
threshold = 200, | |
is_searching = false, | |
doc_height, | |
$d; | |
updateReferences(); | |
// Só dispara o evento quando o usuário para o scroll. Depois de 150ms | |
$d.on('scroll', function(evt) { | |
// Cancela o evento anterior | |
clearTimeout(window.timeout); | |
// Se não estiver buscando | |
if (!is_searching) { | |
window.timeout = setTimeout(onScroll, 150); | |
} | |
}); | |
// Atualiza as referências de $d | |
function updateReferences() { | |
$d = $(document); | |
doc_height = $d.height(); | |
} | |
// Busca quando chega no limite da tela | |
function onScroll() { | |
if ($d.scrollTop() > doc_height - threshold) { | |
getData(); | |
} | |
} | |
function getData() { | |
is_searching = true; | |
$.ajax({ | |
url: '/path/to/data', | |
success: function() { | |
// Renderiza o dado que veio do servidor | |
renderData(); | |
// Atualiza as referências porque $d muda de altura | |
updateReferences(); | |
}, | |
complete: function() { | |
// Libera para uma nova busca | |
is_searching = false; | |
} | |
}); | |
} | |
function renderData() { | |
// Adiciona os elementos buscados na tela | |
} | |
}(jQuery)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment