-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
59 lines (50 loc) · 2.3 KB
/
script.js
File metadata and controls
59 lines (50 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
let page = 1;
const limit = 3;
const totalPosts = 100; // Sabemos que a API tem 100 posts
const loadMoreButton = document.getElementById('load-more');
const postsList = document.getElementById('posts-list');
const loadingMessage = document.getElementById('loading');
const errorMessage = document.getElementById('error');
// Lógica de carregar os 3 primeiros posts ao abrir a página
function carregarPosts() {
const start = (page - 1) * limit;
loadingMessage.style.display = 'block';
errorMessage.style.display = 'none';
fetch(`https://jsonplaceholder.typicode.com/posts?_start=${start}&_limit=${limit}`)
.then(response => {
if (!response.ok) {
throw new Error('Erro na resposta da API');
}
return response.json();
})
.then(posts => {
posts.forEach(post => {
const li = document.createElement('li');
li.innerHTML = `<strong>${post.title}</strong><p>${post.body}</p>`;
postsList.appendChild(li);
});
page++; // avança a página só depois de carregar os posts
// Oculta o botão se já carregou tudo
if ((page - 1) * limit >= totalPosts) {
loadMoreButton.style.display = 'none';
}
})
.catch(error => {
console.error('Erro ao carregar posts:', error);
errorMessage.style.display = 'block';
})
.finally(() => {
loadingMessage.style.display = 'none'; // esconde "Carregando..." ao final
});
}
// Carrega os primeiros posts
carregarPosts();
loadMoreButton.addEventListener('click', carregarPosts);
// Botão de Reiniciar Lista
const resetButton = document.getElementById('reset-list');
resetButton.addEventListener('click', () => {
postsList.innerHTML = ''; // limpa a lista
page = 1; // volta para a página 1
loadMoreButton.style.display = 'block'; // mostra o botão de novo
carregarPosts(); // recarrega os primeiros posts
});