Vanilla JS PJ (Color Flipper)

송민혁·2022년 8월 16일
0
post-thumbnail

Color Flipper

클릭이벤트를 통해서 배열 안에 인덱스번호를 부여받기

  • 인덱스 번호 (난수 받기)
  • 16진수 표현하기

code

html

우선적으로 html의 요소 중에서는 nav를 만들고, 거기 안에 두 가지 모드(링크리스트)를 만든다. 그리고 간단한 버튼을 만들고 텍스트만 만들면 된다.

JS

Simple version

const colors = ["green", "red", "rgba(133,122,200)", "#f15025"];

const btn = document.getElementById('btn');
const color = document.querySelector(".color");

btn.addEventListener('click', function() {
 const randomNumber = getRandomNumber();
 document.body.style.backgroundColor = colors[randomNumber];
 color.textContent = colors[randomNumber];
}
                     
function getRandomNumber() {
  return Math.floor(Math.random()*colors.length);
}

색깔이 되는 후보지를 배열로 만들고, 각각 요소들에 대한 접근을 위해 상수를 선언한다.
그리고 클릭 이벤트(클릭 함수)랜덤 숫자 배정 함수를 만든다.

랜덤숫자를 배정 받으면 그 숫자를 이용하여 인덱싱넘버로 남기면 된다.
그리고 여기서 유지보수를 위해 .length 속성을 이용하는 게 좋다.

Hexadecimal version

16진수는 배열의 요소가 총 16가지로 되어있고, #과 6개의 난수가 필요하다.
배열 안에 임의의 요소를 배정 받기 위해서는 수학 개념에서 조합이 필요하다.
코딩으로 표현하기 위해서는 반복문을 사용하면 된다.

const hex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"];

const btn = document.getElementById('btn');
const color = document.querySelector(".color");

btn.addEventListener('click', function() {
  for (let i=0'; i<6; i++) {
  	let hexRandomNumber = '#';
    hexRandomNumber += hex[getRandomNumber()];
  };
  
  document.body.style.backgroundColor = hexRandomNumber;
  color.textContent = hexRandomNumber;
  
}

function getRandomNumber() {
  return Math.floor(Math.random()*hex.length);
}

실수한 점

  • let hexRandomNumber = '#';을 const로 표현해서 재할당을 못하게 하였다.
    이거 하나로 작동 안 되어서 let 과 const 차이점을 다시 한 번 상기하였다.
  • 배열.length을 제대로 사용하지 않아서 노가다할 뻔했다.

0개의 댓글