자바스크립트를 이용한 기능 구현 프로젝트 1번 : 배경색 바꾸기
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.
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;)
12 lines of code.
This took about 5 minutes to code.
None.
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>
- querySelector를 통해 button 지정
- body를 저렇게 가져와도 되지만, 혹은 document.body.style.backgroundcolor라고 전체를 택해도 됨.
- addEventListener를 통해 click을 할 때마다 changeBackground 함수가 실행되도록 설정
- changeBackground 함수는 Math.random 함수를 이용하여 랜덤하게 색깔을 선택할 수 있도록 함.
- 버튼을 클릭할 때마다 페이지 배경 색깔이 바뀜