quotes.js
, background.js
를 추가해줌// quotes.js
const quotes = [
{
quote:
"Nothing in life is to be feared, it is only to be understood. Now is the time to understand more, so that we may fear less.",
author: "Marie Curie",
},
...(이런식으로 배열요소 10개 생성)
];
const quote = document.querySelector("#quotes span:first-child");
const author = document.querySelector("#quotes span:last-child");
const todaysQuote = quotes[Math.floor(Math.random() * quotes.length)];
quote.innerText = todaysQuote.quote;
author.innerText = todaysQuote.author;
// background.js
const images = ["river.jpg", "cliff.jpg", "coast.jpg"];
const chosenImage = images[Math.floor(Math.random() * images.length)];
const bgImage = document.createElement("img");
bgImage.src = `img/${chosenImage}`;
document.body.appendChild(bgImage);
const todaysQuote = quotes[Math.floor(Math.random() * quotes.length)];
quotes
배열에서 랜덤하게 명언을 추출하기 위해 Math.random()
을 사용했다.
이때 random
을 통해 생성한 수가 0~1 사이의 수이기 때문에 소수점을 제거해주기 위해 floor
를 사용했다.
Math.ceil()
: 소수점을 무조건 올려서 정수로 반환
Math.round()
: 소수점을 반올림해서 정수로 반환
Math.floor()
: 소수점을 무조건 내려서 정수로 반환
지금 예제야 무작위로 추출할 내용이 10개 뿐이지만, 그 이상일 때는 일일이 숫자를 세기가 힘드므로 array.length()
를 사용해서 배열 요소의 크기만큼 돌리도록 지정했다.
JavaScript
에서 HTML
에 요소를 추가하는 방법const bgImage = document.createElement("img"); bgImage.src = `img/${chosenImage}`; document.body.appendChild(bgImage);
createElement()
를 사용해서 img
태그인 bgImage
라는 변수를 추가했다.bgImage
의 소스를 지정해준다. 랜덤한 이미지를 보여줄 것이므로 chosenImage
가 소스 부분에 쓰인다.appendChild
를 통해 body
부분에 bgImage
라는 img
태그를 추가(append) 해준다.