You have the following HTML structure:
<div class='some-class'>...</div>
<div class='container'>
<div class='my-target'>...</div>
<div class='my-target'>...</div>
<div class='my-target'>...</div>
</div>
<div class='other-class'>...</div>
If you want to run Javascript code whenever someone clicks on a <div class='my-target'>...</div>
, you can do this in three different ways:
function code(event) {
alert("Someone clicked on .my-target!");
}
document.addEventListener('click', function(event) {
if (event.target.closest('.my-target')) {
code(event)
}
})
document.querySelector('.container').addEventListener('click', function(event) {
if (event.target.closest('.my-target')) {
code(event)
}
})
for (let target of document.querySelectorAll('.my-target')) {
target.addEventListener('click', code)
}
Use the resources below and talk with your mentor to find out the pros and cons of each approach.
You should at least talk about the following issues and tradeoffs:
Furthermore, you should gain a solid understanding about the differences of stopPropagation()
, stopImmediatePropagation()
and preventDefault()
.
event.target
vs. event.currentTarget
Show archive.org snapshot
We will implement a simplified version of Whac-A-Mole Show archive.org snapshot in HTML and Javascript.
Start with this HTML structure:
<div class="arena">
<div class="mole"></div>
<div class="mole"></div>
<div class="mole"></div>
<div class="mole"></div>
<div class="mole"></div>
<div class="mole"></div>
</div>
<div class="score">
</div>
<div class="time-left">
</div>
Now add some Javascript to implement the following game:
alert
pops up, informing the player about her final score. Pressing "OK" starts another game.Build two different implementations of this: