JavaScript Events

React to clicks, input and more.

✍️ 3 exercises + code challenge in this lesson

An event is something that happens on the page: a click, a key press, a form submission, the page finishing loading.

Common events

  • click, dblclick, mouseover, mouseout
  • input, change, submit, focus, blur
  • keydown, keyup
  • load, DOMContentLoaded

Attach handlers with element.addEventListener("click", handler). It keeps JavaScript out of your HTML and allows several handlers per event.

Key Takeaways: JavaScript Events

Mastering JavaScript Events helps you write clean and reliable JavaScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

JavaScript Events Code Example

JavaScript
<input id="name" placeholder="Type your name">
<p id="hello">Hello!</p>
<button id="btn">Click me</button>
<p id="count">Clicks: 0</p>

<script>
  let clicks = 0;

  document.getElementById("name").addEventListener("input", (e) => {
    document.getElementById("hello").textContent = "Hello, " + (e.target.value || "!");
  });

  document.getElementById("btn").addEventListener("click", () => {
    clicks++;
    document.getElementById("count").textContent = "Clicks: " + clicks;
  });
</script>
Free sign-in required · Google login available

JavaScript Events Practice Exercises

Check what you learned in “JavaScript Events”.

/ 3 solved
Fill in the blank

Run a function when the button is clicked.

button.("click", handleClick);
✓ Correct! Not quite. Try again.
Multiple choice

Which event fires every time the value of an input changes while typing?

✓ Correct! Not quite. Try again.
Code challenge

When the button is clicked, set the text of #msg to "Clicked!". (The check clicks the button for you.)

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services