[JS Project 100] 1. Change Background Color

BbickBbick_Develop·2022년 6월 22일
0

JS Project 100

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

문제 주소


Description

Hosted Project

Github Source Files


This background color changing app was short and sweet to complete. Since I was given the HTML and CSS assets (really, just the styled BootStrap4 button), all I had to do was create an array of different colors and then add a ‘click' event listener to the button. Once the button was clicked, a different background color would appear.


New things learned or refreshed:

I didn't learn any new JavaScript features during this project but I was refreshed on using JavaScript to style CSS (e.g. element.style.backgroundColor = red;)


Lines of code:

12 lines of code.


Time to code:

This took about 5 minutes to code.


Biggest take away:

None.


Your Turn!

What to accomplish:

Download the source code from the github repository above.
Delete the script.js file.
Implement the JavaScript code such that every time the button is clicked, the background changes color.
Add a link to your finished project below!


구현 코드

<!DOCTYPE html>
<--! Head 부분은 생략-->

<body>
    <div class="container">
        <div>
            <div class="col">
                <button>Click Me!</button>
            </div> 

        </div>
               
    </div>
    

    <script>
        const button = document.querySelector('button')
        const body = document.querySelector('body')
        const colors = ['red', 'green', 'blue']

        body.style.backgroundColor = 'white'
        button.addEventListener('click', changeBackground)

        function changeBackground(){
            const colorIndex= parseInt(Math.random()*3)
            body.style.backgroundColor = colors[colorIndex]
        }
    </script>
</body>
</html>

배운 점

  1. querySelector를 통해 button 지정
  1. body를 저렇게 가져와도 되지만, 혹은 document.body.style.backgroundcolor라고 전체를 택해도 됨.
  1. addEventListener를 통해 click을 할 때마다 changeBackground 함수가 실행되도록 설정
  1. changeBackground 함수는 Math.random 함수를 이용하여 랜덤하게 색깔을 선택할 수 있도록 함.
  1. 버튼을 클릭할 때마다 페이지 배경 색깔이 바뀜
profile
삑삑도요가 되자

0개의 댓글