bhylu.com

Advertisements

JS Event Listener

Connect several choices through one event listener. This project practises reading the target and updating a separate result.

Where to run this

This example changes a document. Open it in the HTML playground, then select Run code. It runs inside a separate preview.

A practical example

HTML + JavaScript

<div id="choices">
  <button type="button">Morning</button>
  <button type="button">Afternoon</button>
</div>
<p id="result" role="status"></p>
<script>
  document.getElementById("choices").addEventListener("click", event => {
    if (event.target.tagName === "BUTTON") document.getElementById("result").textContent = "Selected: " + event.target.textContent;
  });
</script>

What happens

The chosen session is displayed without adding a listener to every button.