27
loading...
This website collects cookies to deliver better user experience
getBoundingClientRect
)
scroll
event listener to a HTML Element. This will fire a callback every time the element gets scrolled.left
, top
, right
, bottom
property of the element.left
, top
, right
, bottom
we can determine if the element is in our view port. If it is then we can add more items to our list or do perform some other action.getBoundingClientRect
function.IntersectionObserver
)
<main id="main">
<h2>List of Random Names</h2>
<ul id="ul"></ul>
<button id="load">Load more names</button>
</main>
ul
) and a button
at the end of the list. This is how the above HTML structure looks when rendered.li
tags under the existing ul
tags.const loadBtn = document.getElementById('load')
// Observe loadBtn
const options = {
// Use the whole screen as scroll area
root: null,
// Do not grow or shrink the root area
rootMargin: "0px",
// Threshold of 1.0 will fire callback when 100% of element is visible
threshold: 1.0
};
const observer = new IntersectionObserver((entries) => {
// Callback to be fired
// Entries is a list of elements out of our targets that reported a change.
entries.forEach((entry) => {
// Only add to list if element is coming into view not leaving
if (entry.isIntersecting) {
// Perform some operation here
}
});
}, options);
observer.observe(loadBtn);
async function addNamesToList(ul_id, num) {
const ul = document.getElementById(ul_id);
// Mock func to return array of dummy names
const names = await mockAPI(num);
// For each name in names append it to the ul element
names.forEach((name) => {
const li = document.createElement("li");
li.innerText = name;
ul.appendChild(li);
});
}
import mockAPI from "./mockAPI";
const loadBtn = document.getElementById("load");
async function addNamesToList(ul_id, num) {
const ul = document.getElementById(ul_id);
// Mock func to return array of dummy names
const names = await mockAPI(num);
// For each name in names append it to the ul element
names.forEach((name) => {
const li = document.createElement("li");
li.innerText = name;
ul.appendChild(li);
});
}
(function () {
addNamesToList("ul", 50);
// Observe loadBtn
const options = {
// Use the whole screen as scroll area
root: null,
// Do not grow or shrink the root area
rootMargin: "0px",
// Threshold of 1.0 will fire callback when 100% of element is visible
threshold: 1.0
};
const observer = new IntersectionObserver((entries) => {
// Callback to be fired
entries.forEach((entry) => {
// Only add to list if element is coming into view not leaving
if (entry.isIntersecting) {
addNamesToList("ul", 10);
}
});
}, options);
observer.observe(loadBtn);
})();
loadBtn.onclick = () => {
addNamesToList("ul", 10);
};