AI Hints
Home›JavaScript Tutorial›Events and Forms
JavaScript · Lesson 97 of 138

The Event Object

Details of what happened.

⏱ 2 min read▶ Video at 1:56:19🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

When an event fires, your function receives an event object. It describes what happened. Which element was clicked, which key was pressed, or where the mouse was.

The Event Object
From the video: The Event Object
  • Your function gets an event
  • What happened
  • Which element, which key

Using the event

Our listener takes the event as a parameter, usually called e. E dot target is the element that was clicked, so one listener on the box can tell the buttons apart. Here, clicking the Blue button wrote its text into the paragraph, as you can see.

index.htmlpython
<link rel="stylesheet" href="style.css">
<div id="colors">
  <button>Red</button>
  <button id="blue">Blue</button>
  <button>Green</button>
</div>
<p id="out" class="big">Pick a colour</p>
<script>
  const out = document.querySelector("#out");
  document.querySelector("#colors").addEventListener("click", (e) => {
    if (e.target.tagName !== "BUTTON") return;
    out.textContent = `You picked ${e.target.textContent}`;
  });
</script>
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#f7df1e;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} .big{font-size:64px;font-weight:800}
Also uses actions.json
[{"click": "#blue"}]

Useful event properties

E dot target is the element the event started on. E dot key tells you which key was pressed, like Enter. And e dot prevent default stops the browser's normal behaviour, like a form reloading the page, or a link opening a new page.

keyvalue
e.targetthe element
e.keywhich key
e.preventDefault()stop the default
e.typeclick, input...

Summary

The event object tells you what happened. Target is the element, key is the key, and prevent default stops the browser's normal action. Next, forms and input.

Key takeaways
  • (e) => { }
  • e.target
  • e.preventDefault()
Next up: Forms and Input — reading what people type