본문 바로가기

개발/JavaScript

바닐라JS - 앱 만들기 randomness

Quotes

- 랜덤으로 뜨는 명언

- 명언-작가

const quotes {
    quote: "여성들이여, 국가의 영혼을 구해야 한다면, 나는 여러분이 국가의 영혼이 되어야 한다고 믿는다.",
    author: "코레타 스콧 킹",
},
{
    quote: "당신이 어떤 운동이 참여했는데 유색 인종 여성을 따르고 있지 않다면, 그 운동은 잘못된 것이다.",
    author: "린다 사르수르",
},

// quote object 생성
        <div id="quote">
            <span></span>
            <span></span>
        </div>
        
        <!-- html body에 div 생성

 

Math module

Math.random()

- 0~1 사이 숫자를 랜덤으로 생성

- * n을 하면 0~n 사이의 수를 얻을 수 있음

 

result

- 소수점 결과를 정수로 바꾸기 위해 아래 코드 사용

Math.floor() 버림

Math.round() 반올림

Math.ceil() 올림

 

    <body>
        <form class="hidden" id="login-form">
            <input required maxlength="15" type="text" placeholder="What is your name?" />
            <input type="submit" value="Log In" />
        </form>
        <h2 id="clock">00:00:00</h2>
        <h1 id="greeting" class="hidden"></h1>
        <div id="quote">
            <span></span>
            <span></span>
        </div>
        <script src="js/greetings.js"></script>
        <script src="js/clock.js"></script>
        <script src="js/quotes.js"></script>
        <script src="js/background.js"></script>
    </body>
const quotes = [...];

const quote = document.querySelector("#quote span:first-child");
const author = document.querySelector("#quote span:last-child");

const todaysQuote = quotes[Math.floor(Math.random()*quotes.length)];


quote.innerText = todaysQuote.quote;
author.innerText = todaysQuote.author;

 

Background

- 랜덤으로 바뀌는 배경

- 같은 폴더에 이미지 저장

- js에서 생성한 이미지를 html에 적용 

 

const images = ["1994.jpg","1978.jpg","1666.jpg"];

const chosenImage = images[Math.floor(Math.random()*images.length)];

const bgImage = document.createElement("img");

bgImage.src = `img/${chosenImage}`; // tag 안에 경로 속성 추가

document.body.appendChild(bgImage);

js로 html에 element를 추가하기

document.creatElement() element 생성

document.body.appendChild() element를 body 안에 추가

append는 맨 밑에, prepend는 가장 위에 삽입하는 것

 

문제: 배경이 아니고 그냥 이미지가 삽입