infinite scrolling
Javascript 2021. 1. 19. 18:30선행 학습
------------------------------------------------------------------------------------------------------------------------------
async , await
------------------------------------------------------------------------------------------------------------------------------
CORS : https://developer.mozilla.org/ko/docs/Web/HTTP/CORS
Access to fetch at 'https://randomuser.me/api' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
참고
https://cchoimin.tistory.com/entry/JavaScript-CORS%EB%9E%80
SOP 원칙을 깨고 외부 도메인에서의 요청(접근)을 허용해주는 규약.
SOP (Same Origin Policy) 동일출처 정책
JS로 같은 출처(도메인)에서만 접근이 가능하다 라는 정책이다.
같은 출처 : 프로토콜, 호스트명, 포트가 같다라는 것을 의미
------------------------------------------------------------------------------------------------------------------------------
fetch
https://chinsun9.github.io/2020/11/23/random-user-api/
참고
https://jsonplaceholder.typicode.com/
https://randomuser.me/api
https://jsonplaceholder.typicode.com/post/24
references:
www.youtube.com/watch?v=L8X4zAsoxb4
codepen.io/FlorinPop17/pen/RwwvKYJ
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Infinite Scroll</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<div class="container" id="container">
<h1>Blog Posts</h1>
<!-- <div class="blog-post">
<h2 class="title">Blog post title</h2>
<p class="text">
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Ad, aliquam!
Eum accusantium explicabo magni voluptate reprehenderit incidunt
quisquam culpa aliquam, vero minima nisi ducimus quas quam cupiditate
nam enim! Optio.
</p>
<div class="user-info">
<img
src="https://randomuser.me/api/portraits/women/26.jpg"
alt="pic"
/>
<span>Leah Taylor</span>
</div>
</div> -->
</div>
<div class="loading">
<div class="ball"></div>
<div class="ball"></div>
<div class="ball"></div>
</div>
<script src="./main.js"></script>
</body>
</html>
@import url("https://fonts.googleapis.com/css2?family=Open+Sans:ital@1&display=swap");
* {
box-sizing: border-box;
}
body {
background-color: #fafafa;
font-family: "Open Sans", sans-serif;
padding-bottom: 100%;
}
.container {
margin: 0 auto;
max-width: 600px;
}
.blog-post {
background-color: #fff;
box-shadow: 0px 1px 2px rgba(50, 50, 50, 0.1),
0px 2px 4px rgba(60, 60, 60, 0.1);
border-radius: 4px;
padding: 40px;
margin: 20px 0;
}
.title {
margin: 0;
}
.text {
color: #555;
/* 세로 | 가로 */
margin: 20px 0;
}
.user-info {
display: flex;
align-items: center;
}
.user-info img {
border-radius: 50%;
width: 30px;
height: 30px;
}
.user-info span {
font-size: 13px;
margin-left: 10px;
}
/* loading */
.loading {
opacity: 0;
display: flex;
position: fixed;
bottom: 50px;
left: 50%;
transform: translateX(-50%);
transition: opacity 0.3s ease-in;
}
.loading.show {
opacity: 1;
}
.ball {
background-color: #777;
border-radius: 50%;
margin: 5px;
width: 10px;
height: 10px;
animation: jump 0.5s ease-in infinite;
}
.ball:nth-of-type(2) {
animation-delay: 0.1s;
}
.ball:nth-of-type(3) {
animation-delay: 0.2s;
}
@keyframes jump {
0%,
100% {
transform: translateY(0);
}
50% {
transform: translateY(-10px);
}
}
const container = document.getElementById('container');
const loading = document.querySelector('.loading');
getPost();
getPost();
getPost();
window.addEventListener('scroll', ()=>{
const{ scrollTop, scrollHeight, clientHeight} = document.documentElement;
console.log({scrollTop, scrollHeight, clientHeight});
if(clientHeight + scrollTop >= scrollHeight){
console.log('to the bottom');
//show the loading animation
showLoading();
}
});
function showLoading(){
loading.classList.add('show');
//load more data
getPost();
}
async function getPost(){
const url = `https://jsonplaceholder.typicode.com/posts/${getRandomNr()}`;
const postResponse = await fetch(url);
const postData = await postResponse.json();
const userResponse = await fetch('https://randomuser.me/api');
const userData = await userResponse.json();
const data = {post: postData, user:userData.results[0]};
addDataToDOM(data);
}
function getRandomNr(){
return Math.floor(Math.random() * 100) + 1;
}
function addDataToDOM(data){
const postElement = document.createElement('div');
postElement.classList.add('blog-post');
postElement.innerHTML = `
<h2 class="title">${data.post.title}</h2>
<p class="text">${data.post.body}</p>
<div class="user-info">
<img src="${data.user.picture.large}" alt="${data.user.name.first}"/>
<span>${data.user.name.first} ${data.user.name.last}</span>
</div>
`;
container.appendChild(postElement);
loading.classList.remove('show');
}
'Javascript' 카테고리의 다른 글
Destructuring 구조분해 할당 (0) | 2022.01.23 |
---|---|
spead, rest operator (0) | 2022.01.22 |
즉시실행함수(IIFE) : 익명의 함수 표현 (0) | 2020.09.28 |
[Async function] async/await 비동기 처리 (0) | 2020.09.10 |
Uncaught TypeError: Cannot read property 'popup_show_trigger' of undefined (0) | 2020.07.22 |