배웠던 기본적인 자바스크립트 지식을 활용하여 몇가지 간단한 application들을 만들어 봤다.
const btn = document.getElementById('btn'); const hex = document.getElementById('hex'); const body = document.querySelector('body'); const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f']; function changeColor() { let color = '#'; for (let i = 1; i < 7; i++) { num = Math.floor(Math.random() * arr.length); val = arr[num]; color += val; } hex.textContent = color; body.style.backgroundColor = color; } btn.addEventListener('click', changeColor);
- 버튼 클릭할 때마다, 무작위의 색상 hex code에 따라 배경 색상이 바뀌게 된다.
function generateQuote() { const random = Math.floor(Math.random() * quotes.length); quotation.textContent = quotes[random].quote; writer.textContent = '- ' + quotes[random].author; }
- 버튼 클릭할 때마다, 무작위의 quote가 화면에 출력된다.
function generateText(e) { e.preventDefault(); if (input.value) { enteredMsg.textContent = input.value; input.value = ''; } else { errorMsg.classList.add('show'); setTimeout(() => { errorMsg.classList.remove('show'); }, 1000); } } form.addEventListener('submit', generateText);
form
을 submit 이벤트와 함께 사용할 때는e.preventDefault()
를 이용해주어야 한다.
또한 이e.preventDefault()
는a
태그 클릭할 때 페이지가 새로고침되는 현상도 막아 준다.input
필드에 입력한 값이 화면에 출력된다.- 입력값이 없다면 error 메시지를 띄운다.
강의 없이 혼자 color hex code generator를 만들 때 color += val
부분이 헷갈렸지만, 강의를 보고 쉽게 이해할 수 있었다.
github에 업데이트되었다.