[JS Project 100] 2. Hex Change Background Color

BbickBbick_Develop·2022년 6월 25일
0

JS Project 100

목록 보기
2/8
post-thumbnail
자바스크립트를 이용한 기능 구현 프로젝트 2번 : Hex값을 이용해 배경색 바꾸기

문제 주소


Description

Hosted Project

Github Source Files


Project Objectives This HEX background color changing app was also short and sweet to complete.
However, I did find the instructor's solution interesting.

The idea was to make a random hex value created from an array of all the possible different hex values, loop through them, and concatenate 6 different values to a String that begun with the # character.

In other words, once the HEX value string is created, you'd simply change the background color to that value just like in the change background color project.

New things learned or refreshed

I learned that the simplest solution is probable the best solution.

I spent a lot of time trying to figure out the best way to create a HEX value with creating an array. But, turns out the array was a pretty simple solution.

Lines of code:

19 lines of code.

Time to code:

This took about 7 minutes to code.

Biggest take away:

KISS. Keep it Simple. Make a working solution. Refactor if you must, later.

Your Turn!

What to accomplish:

  1. Download the source code from the github repository above.
  2. Delete the app.js file.
  3. Implement the JavaScript code in your own app.js file.
  4. Every time the button is clicked, the background should
  5. changes color and you should show the Hex value of the color.
  6. Add a link to your finished project below!

구현 코드

<script>

// 버튼을 getElementById로 호출
	const btn = document.getElementById('btn')

// body 전체를 호출

	const body = document.querySelector('body')

// hex값을 나타내는 span을 호출
	let hex_value = document.getElementById('hex-value')

// 0~F까지를 값으로 저장
	const hex_line  = '0123456789ABCDEF'
	const length = hex_line.length

// hex_line 중 하나를 선택하는 함수를 설정

    function hex_number () {
        let hexs = []
        for (let i=0; i<6; i++){
            let random_hex_number = parseInt(Math.random()*length)
            let hex = hex_line[random_hex_number]
            hexs.push(hex)
        }
        let result = hexs.join('')
        hex_value.textContent = '#'+result
        body.style.backgroundColor = '#'+result
    }


    btn.addEventListener('click', hex_number)
</script>

배운 점

  1. querySelector와 getElementById의 차이점(querySelector로 할 때는 잘 안됐던 것)
  1. function 안에서 For문 사용하기(Python과 다른 문법)
  1. 문자열 붙이기(+, concat, join)
  1. Math.random() 함수(0~1까지의 소수값을 가지기 때문에, 값을 곱하고 처리를 해주어야 한다)
  1. paserInt 함수(parseInt 함수는 첫 번째 인자를 문자열로 변환하고, 그 값을 파싱하여 정수나 NaN을 반환)
  1. span값에 문자열 값을 집어넣을 수 있는 것 = textContent
  1. let과 const의 명확한 차이점 알기(값 재할당 가능, 불가)
profile
삑삑도요가 되자

0개의 댓글