Winnie The Pooh Bear 모던자바스크립트 마무리 문제 1 명언랜덤표시

배움기록/JAVASCRIPT

모던자바스크립트 마무리 문제 1 명언랜덤표시

코딩은 처음이라 2023. 4. 15. 20:27

“ 지연되는 프로젝트에 인력을 더 투입하면 오히려 더 늦어진다. ”

- Frederick Philips Brooks
Mythical Man-Month 저자
728x90
반응형

모던자바스크립트 마무리 문제 1 명언랜덤표시

 

 

 

 

오늘은 모던자바스크립트 책의 p.520 마무리문제를 만들어보도록 하겠습니다.

 

명언 js파일을 불러와 화면에 보여주게 합니다.

추가적으로 10초에 한번씩 명언이 바뀌게 해주겠습니다.

 

- fetch와 then, catch를 사용해 URL에서 자료 가져오기

- 가져온 데이터에 어떤 값이 어떤 구조로 저장되어 있는지 확인하고 그 중에 명언과 말한 사람 정보를 가져오기

- 무작위로 명언 보여주기

- 10초에 한번씩 명언 바꾸기

 

 

💜 명언

코드 보기 / 완성 화면

 

 

 

HTML

<div id="result">
    <div class="quote"></div>
    <div class="author"></div>
</div>

HTML은 이렇게 마무리해줬습니다.

 

script

<script>
    const Result = document.querySelector("#result");
    const Quote = result.querySelector(".quote");
    const Author = result.querySelector(".author");

    const dataresult = () => {
        fetch('json/dummy.json')
        .then(res => res.json())
        .then(items => {
            const randomIndex = Math.floor(Math.random() * items.length);
            Quote.textContent = items[randomIndex].quote;
            Author.textContent = "- " + items[randomIndex].author;
        })
        .catch((err) => console.log(err));
    }
    dataresult();
    setInterval(dataresult, 10000);
</script>

우선 선택자를 만들어주고,

 

const dataresult = () => {} dataresult 함수를 정의하고

JSON 데이터를 가져와Quote와 Author 요소의 내용을 랜덤으로 변경합니다.

 

fetch로 josn파일을 가져와줍니다.

 

.then(res => res.json()) 응답 데이터를 JSON 형식으로 변환합니다.

.then(items => {}) json 데이터를 랜덤으로 인용구아 작가를 선택하고 Quote와 Author요소의 내용을 변경합니다.

 

dataresult(); dataresult 함수를 한 번 더 호출

 

setInterval(dataresult, 10000) 로 함수를 10초마다 호출합니다.

 

style

<style>
    @import url('https://webfontworld.github.io/score/SCoreDream.css');
    * {
        margin: 0 auto;
        padding: 0;
    }
    body {
        width: 100%;
        height: 100vh;
        background-color: #ccc;
        background-image: url(/javascript/slider/img/bg.jpg);
        background-size: cover;
        position: relative;
        overflow: hidden;
    }
    body::after {
        content: '';
        position: absolute;
        left:0; top:0;
        width: 100%;
        height: 100%;
        background-color: rgba(14, 14, 14, 0.545);
        z-index: -1;
    }
    #result {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        text-align: center;
        font-size: 20px;
        line-height: 70px;
        font-family: 'SCoreDream';
        color: #fff;
    }
    .quote {
        font-weight: bold;
        font-size: 30px;
    }
</style>

폰트설정과 배경설정

글씨 중앙정렬

 

배경에 투명한 검정색 오버레이 적용 등의 간단한 스타일을 적용시켜줬습니다.

반응형