The Web Developer 부트캠프 2023/JS
js DOM 이벤트
tjdvyzl
2023. 7. 6. 21:41
랜덤 컬러 연습하기
<!DOCTYPE html>
<head>
<title>100 Buttons!</title>
</head>
<body>
<h1>Click me!</h1>
<button>change</button>
<script>
const button = document.querySelector('button');
const h1 = document.querySelector('h1');
button.addEventListener('click', function() {
const newColor = randColor();
document.body.style.backgroundColor = newColor;
h1.innerText = newColor;
})
const randColor = () => {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
return `rgb(${r}, ${g}, ${b})`
}
</script>
</body>
</html>
이벤트와 this 키워드
https://m.blog.naver.com/nuberus/221463728867
이벤트 객체
https://tangoo91.tistory.com/32
e.preventDefault()
https://programming119.tistory.com/100
이벤트 버블링 & 이벤트 위임
https://joshua1988.github.io/web-development/javascript/event-propagation-delegation/
점수 관리자 제작하기
더보기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1><span id="p1display">0</span> to <span id="p2display">0</span></h1>
<button id="p1button">+1 Player One</button>
<button id="p2button">+1 Player Two</button>
<select id="winScoreSelect"></select>
<button id="reset">reset</button>
<script src="temp.js"></script>
</body>
</html>
const resetButton = document.querySelector('#reset');
let isGameOver = false;
let winPoint = 3;
const winScoreSelect = document.querySelector('#winScoreSelect');
for (let i = 3; i <= 11; i += 2) {
const newOption = document.createElement('option');
newOption.setAttribute('value', i);
newOption.innerText = newOption.value;
winScoreSelect.append(newOption);
}
const p1 = {
score: 0,
button: document.querySelector('#p1button'),
display: document.querySelector('#p1display'),
}
const p2 = {
score: 0,
button: document.querySelector('#p2button'),
display: document.querySelector('#p2display'),
}
function updateScores(player, opponent) {
if (!isGameOver) {
player.score += 1;
if (player.score === winPoint) {
isGameOver = true;
player.disabled = true;
opponent.disabled = true;
}
player.display.textContent = player.score;
}
}
p1button.addEventListener('click', function () {
updateScores(p1, p2);
})
p2button.addEventListener('click', function () {
updateScores(p2, p1);
})
winScoreSelect.addEventListener('change', function (e) {
winPoint = parseInt(e.target.value);
reset();
})
resetButton.addEventListener('click', reset)
function reset() {
isGameOver = false;
for (let p of [p1, p2]) {
p.score = 0;
p.display.textContent = p.score;
}
}