한 걸음씩
[JS] Random Color 2 - color flipper 만들기 본문
[요구사항]
버튼을 클릭할 때마다 배경색이 랜덤으로 지정되고 무슨 색상인지 화면에 표시하기
// index.html
<body>
<nav>
<div id="title">Color Flipper</div>
<div>Hex</div>
</nav>
<div class="colorBox">Background Color :
<span class="color-text">#ffffff</span>
</div>
<button>CLICK ME</button>
<script src="app.js"></script>
</body>
body의 배경색 초기색상은 #ffffff으로 지정해 준다.
// app.js
const body = document.querySelector('body')
const hex = document.querySelector('nav div:first-child')
const btn = document.querySelector('button')
const colorText = document.querySelector('.color-text')
const colors = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F']
function onChangeColor(){
let randomHexColor = '#'
for (let i = 0; i < 6; i++){
randomHexColor += colors[colorGenerator()]
}
colorText.innerText = `${randomHexColor}`
body.style.backgroundColor = randomHexColor
}
function colorGenerator(){
return Math.floor(Math.random() * colors.length)
}
btn.addEventListener('click', onChangeColor)
hex코드로 랜덤컬러를 생성하는 방법은 다음과 같다
hex는 0 ~ 9, A ~ F의 숫자와 문자로 구성되어 있는 코드이다.
따라서 0 ~ 9, A ~ F가 들어있는 배열을 생성해 준다. colors
버튼을 눌렀을 때 onChangeColor 함수가 실행될 수 있도록 이벤트를 설정해 준다.
onChangeColor함수에서 위에서 만들어둔 배열을 가지고 6자리로 조합하여 코드를 완성해줘야 한다.
colorGenerator 함수를 생성해 colors 배열길이만큼의 수를 랜덤으로 생성해 준다.→ 인덱스로 접근하기 위함
onChangeColor함수에서 randomHexColor라는 변수에 6번의 반복을 하면서 hex코드를 완성해 준 후
colorText, span 태그에 randomHexColor변수로 텍스트를 추가하고
body의 배경색상을 randomHexColor변수를 이용해 변경해 준다.
'JS' 카테고리의 다른 글
[JS] Carousel 만들기 (0) | 2023.07.06 |
---|---|
[JS] Number Counter 만들기 (0) | 2023.07.06 |
[JS] To Do List (0) | 2023.07.03 |
[JS] weather API and Date (0) | 2023.07.02 |
[JS] canvas 2 - meme maker, text, save (0) | 2023.07.01 |