하루를살자

JS Clone Project [Quotes] 본문

JS

JS Clone Project [Quotes]

Kai1996 2021. 12. 5. 22:05

Momentum application 에 사용될 문구들은 아래와 같이 따로 하드 코딩으로 JSON 형식으로 저장하였고, "quote" 와 "author" 라는 Key 값들로 이루워 져있다. 

- quote.js

const quotes = [
    {
      quote: "The way to get started is to quit talking and begin doing.",
      author: "Walt Disney",
    },
    {
      quote: "Life is what happens when you're busy making other plans.",
      author: "John Lennon",
    },
    {
      quote:
        "The world is a book and those who do not travel read only one page.",
      author: "Saint Augustine",
    },
    {
      quote: "Life is either a daring adventure or nothing at all.",
      author: "Helen Keller",
    },
    {
      quote: "To Travel is to Live",
      author: "Hans Christian Andersen",
    },
    {
      quote: "Only a life lived for others is a life worthwhile.",
      author: "Albert Einstein",
    },
    {
      quote: "You only live once, but if you do it right, once is enough.",
      author: "Mae West",
    },
    {
      quote: "Never go on trips with anyone you do ntot love.",
      author: "Hemmingway",
    },
    {
      quote: "We wander for distraction, but we travel for fulfilment.",
      author: "Hilaire Belloc",
    },
    {
      quote: "Travel expands the mind and fills the gap.",
      author: "Sheda Savage",
    },
  ];

  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;

  function clickQuote(){
    const todaysQuote = quotes[Math.floor(Math.random() * quotes.length)];
    quote.innerText = todaysQuote.quote;
    author.innerText = todaysQuote.author;
  }

quote.addEventListener("click",clickQuote);

-Key points 

1. Html 소스에서 <div id = "quote"> 라는 요소 안에 두개의 <span> 요소들이 추가 되었고, 이를 js 파일에서 first-child, last-child 로 reference 처리 해주었다. 

 

2. quotes 의 배열 안에 랜덤 하게 값을 받아내기 위해서 Math.random() --> returns number between 0 ~ 1, 과 quote 배열의 길이가 곱해졌고, Math floor 를 통해서 소수점 내림 값을 인덱싱 하여서 quote 와 author 의 innerText 에 quote 와 author 의 값을 넣어주었다. 

 

3. 마지막으로 문구를 클릭 할 때 마다 랜덤 으로 바뀌도록 해보았다. 

'JS' 카테고리의 다른 글

JS Clone Project [to-do list] - 1,2  (0) 2021.12.05
JS Clone Project [Background]  (0) 2021.12.05
JS Clone Project [Clock] - 2, PadStart  (0) 2021.12.05
JS Clone Project [Clock] - 1  (0) 2021.12.04
JS Clone Project [Login] - 3, Saving User Input  (0) 2021.12.04
Comments