[JavaScript] 바닐라 JS로 크롬 앱 만들기_#09

강성일·2023년 3월 8일
0
post-thumbnail

quote

현재 홈페이지에 명언을 추가시키려 한다.
매번 새로고침 시, 새로운 명언을 랜덤으로 가져오게 할 것이다.

먼저 Html을 세팅해야한다.

Html 안에 id 값 quote를 하나 만들고 안에 span을 두 개 넣는다.


// Html

<div id="quote">
      <span></span>
      <span></span>
</div>

<script src="js/quotes.js"></script>


// JS

const quotes = [
  {
    quote:
      "Any fool can write code that a computer can understand. Good programmers write code that humans can understand.",
    author: "Martin Fowler",
  ...
  {
    quote: "Just Do it. Now.",
    author: "Kang Seong Il",
  },
];

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

JS로 넘어와, querySelector를 이용하여 html에서 선언했던
첫 번째 span은 quote, 두 번째 span은 author로 매치시켜준다.

JS 파일에서 명언을 배열로 랜덤으로 띄울 수 있도록 const로 선언한다.
이 배열 안에는 명언(quote)과 저자(author)를 구분하여 object로 넣어준다.

다음은 이 quotes를 랜덤으로 가져오는 작업을 할 것이다.

이는 Java에서 기본으로 제공하는 Math를 이용하면 된다.


  • Math 객체 기능
    Math 객체는 JavaScript에서 계산을 위한 함수와 상수를 제공하는 전역 객체이다.
    Math.random() 함수는 0부터 1사이의 무작위 값을 반환한다.
    Math.floor() 함수는 입력한 숫자를 내림하여 반환한다.
    Math.ceil() 함수는 입력한 숫자를 올림하여 반환한다.
    Math.round() 함수는 입력한 숫자를 반올림하여 반환한다.

여기서 내가 이용할 것은 .random과 .floor이다.

Math.random을 이용하면 0~1 사이에 수가 나오고, 이를 명언 안의 배열 수인 quotes.length로 곱해주면 배열의 수의 float 값이 나온다.

우리가 필요한 것은 소수점을 가지는 float가 아니라 정수 integer이다.
따라서 이는 구한 값에 다시 Math.floor로 묶어 정수 값을 todaysQuote로 받아온다.

받아온 todaysQuote을 각각 quote와 author innerText로 띄워주면 끝 !


✅ 최종코드

const quotes = [
  {
    quote:
      "Any fool can write code that a computer can understand. Good programmers write code that humans can understand.",
    author: "Martin Fowler",
  ...
  {
    quote: "Just Do it. Now.",
    author: "Kang Seong Il",
  },
];

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

방금 전에 했던 quote와 비슷하다. 랜덤 값으로 이미지를 불러오는 것이기 때문이다.

하지만 차이점이 있다면 이는 js에 html을 불러올 수 없다는 점이다.
html안에 img src=”img/0.jpeg” 이런식으로 모든 이미지를 다 하드코딩하기는 힘들다는 뜻이다.

따라서 반대로 html에서 js를 불러오는 작업을 할 것이다.
js에서 이미지를 만들어서 html로 보낸다는 뜻이다.

다시 한 번 말하면, 위 img src=”img/0.jpeg” 이런 작업을
html이 아닌 js에서 만들어 역으로 html로 보내준다는 것이다.


const images = [
  "cat1.jpeg",
  ...
  "pok6.jpeg",
];

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

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

bgImage.src = `img/${chosenImage}`;

document.body.appendChild(bgImage);

마찬가지로 Math를 이용하여 랜덤 값으로 추출하여 chosenImage에 받아준다.

하지만 여기에선 위에서 말한 js에서 이미지를 만들어 html로 보내는 작업이 필요하다.

이는 creatElement를 사용하면 된다. 이것을 사용하면 html에 요소를 추가할 수 있다.
나는 이미지를 만들거니까 img로 선택하여 bgImage라고 선언해주었다.
이는 bgImage.src를 사용할 수 있다는 것이고, img 폴더 링크에 추출했었던 랜덤 값을 넣어주었다.

마지막으로 bgImage를 body 내부에 추가하면 끝이다.
여기까지는 아직 JS에만 존재하고, document에는 존재하지 않기 때문이다.
이는 appendChild를 이용하여 body에 html을 추가해준다.


  • appendChild() - 함수 안의 경로에 정의한 값을 가장 뒤에서 기입함
  • prepend - 반대로 앞에서 기입

그럼 끝이다!!



❗️ 주의할 점

const bgImage = document.createElement("img") 에서 img는 html 태그의 img이고,

bgImage.src = img/${chosenImage} 에서 img는 내가 이미지를 담아뒀던 폴더명이다.

헷갈리지 않도록 하자!



ps)


// Html

< img id="bg-img" src="#" >

// JS

const bgImage = document.querySelector("#bg-img");

bgImage.src = `img/${chosenImage}`;

bg-img 의 src를 #으로 적어놓고 querySelector로 불러와도 가능하더라 😮

profile
아이디어가 넘치는 프론트엔드를 꿈꿉니다 🔥

0개의 댓글