Bite1: Your First Events in JavaScript

Learn what events are in JavaScript and how to use them to make your webpage interactive.


What are Events?

Events are actions or occurrences that happen in the browser. Examples include:

  • Clicking a button
  • Moving your mouse over an element
  • Typing text in an input field

JavaScript allows you to “listen” for these events and respond to them.


The Click Event

Let’s start with the simplest event: a button click. We’ll write a program that changes the color of some text when you click a button.


Example Code:

html:

  <p id="text">Click the button to change my color!</p>
  <button id="colorButton">Click me!</button>

css:

.colorful {
  background: orange;
}

js:

    // Find the HTML elements
    const text = document.getElementById("text");

    const button = document.getElementById("colorButton");

    // Add an event listener to the button

    button.addEventListener("click", function() {

      text.classList.toggle("colorful"); // Add/remove the CSS class

    });

  


How Does This Work?

  1. Find the elements:
    • document.getElementById(“text”) gets the paragraph element.
    • document.getElementById(“colorButton”) gets the button element.
  2. Add an event listener:
    • button.addEventListener(“click”, …) tells the button to “listen” for click events.
    • When the button is clicked, the function inside addEventListener runs.
  3. Toggle a CSS class:
    • text.classList.toggle(“colorful”) adds the class colorful if it isn’t there, or removes it if it is.

Try It Yourself!

https://codepen.io/anetachwala/pen/QwLZEGL