Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Infinite scroll in JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
*,
*::before,
*::after {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: inherit;
}
body {
font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI",
Roboto, "Helvetica Neue", sans-serif;
}
.article {
padding: 10px 20px;
border: 1px solid #dbdbdb;
border-radius: 5px;
line-height: 37px;
margin-bottom: 60px;
}
.container {
max-width: 800px;
margin: 30px auto;
}
.article:hover {
background: #f7f7f7;
}
.article__title {
font-size: 23px;
font-weight: 400;
}
.article__text {
color: #979797;
font-size: 14px;
font-weight: 400;
}
.space {
height: 200vh;
}
</style>
</head>
<body>
<div class="container">
<div class="space"></div>
<div id="articles">
<div class="article">
<h1 class="article__title">Lorem ipsum dolor sit ame</h1>
<p class="article__text">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam,
quidem.
</p>
</div>
</div>
<p id="status"></p>
</div>
<script>
const articlesContainer = document.querySelector("#articles");
const status = document.querySelector("#status");
let loading = false;
let lastLoadedArticle = 0;
const addArticle = (title, desc) => {
const article = document.createElement("div");
article.classList.add("article");
article.innerHTML = `
<h1 class="article__title"></h1>
<p class="article__text"></p>
`;
article.querySelector(".article__title").textContent = title;
article.querySelector(".article__text").textContent = desc;
articlesContainer.appendChild(article);
};
const update = () => {
articlesContainer.classList.add("loading");
fetch(`index.json?${lastLoadedArticle}`)
.then((data) => data.json())
.then(({ title, body }) => {
addArticle(title + lastLoadedArticle, body);
lastLoadedArticle++;
loading = false;
articlesContainer.classList.remove("loading");
})
.catch(() => {
articlesContainer.classList.remove("loading");
alert("Something went wrong");
});
if (lastLoadedArticle > 99) {
document.removeEventListener("scroll", loadArticle);
}
};
const loadArticle = (e) => {
if (loading) return;
if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
loading = true;
setTimeout(() => {
status.textContent = "Loading more...";
update();
}, 400);
}
};
document.addEventListener("scroll", loadArticle);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment