DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on

Day 61: HTML Events

Introduction to HTML Events

HTML events are occurrences recognized by web browsers that can trigger JavaScript functions or other actions. Events can be user-initiated, like clicks and keystrokes, or system-generated, such as the page finishing loading.

Types of HTML Events 🌈

  1. Mouse Events 🖱️

    • click: Triggered when the mouse is clicked.
    • mouseover: Fired when the mouse enters an element.
    • mouseout: Fired when the mouse leaves an element.
    <button onclick="handleClick()">Click me!</button>
    <script>
      function handleClick() {
        alert('Button clicked!');
      }
    </script>
    
  2. Keyboard Events ⌨️

    • keydown: Occurs when a key is pressed.
    • keyup: Fired when a key is released.
    <input type="text" onkeyup="handleKeyUp(event)">
    <script>
      function handleKeyUp(event) {
        console.log('Key pressed:', event.key);
      }
    </script>
    
  3. Form Events 📝

    • submit: Triggered when a form is submitted.
    • change: Fired when the value of an input changes.
    <form onchange="handleChange()">
      <input type="text" />
    </form>
    <script>
      function handleChange() {
        console.log('Input changed!');
      }
    </script>
    
  4. Window Events 🖼️

    • load: Fired when the page finishes loading.
    • resize: Triggered when the browser window is resized.
    <body onload="handleLoad()" onresize="handleResize()">
    <script>
      function handleLoad() {
        console.log('Page loaded!');
      }
    
      function handleResize() {
        console.log('Window resized!');
      }
    </script>
    

Event Handling in HTML 🤹‍♂️

Handling events can be done in HTML using inline attributes or in JavaScript using event listeners.

Inline Event Handling 🎭

<button onclick="handleClick()">Click me!</button>
<script>
  function handleClick() {
    alert('Button clicked!');
  }
</script>
Enter fullscreen mode Exit fullscreen mode

Event Listeners in JavaScript 🧩

<button id="myButton">Click me!</button>
<script>
  const button = document.getElementById('myButton');
  button.addEventListener('click', function () {
    alert('Button clicked!');
  });
</script>
Enter fullscreen mode Exit fullscreen mode

Event Propagation 🌐

Understanding event propagation is crucial. Events can propagate in two phases: capturing phase and bubbling phase.

<div onclick="handleDivClick()">
  <button onclick="handleButtonClick()">Click me!</button>
</div>
<script>
  function handleDivClick() {
    console.log('Div clicked!');
  }

  function handleButtonClick() {
    console.log('Button clicked!');
  }
</script>
Enter fullscreen mode Exit fullscreen mode

In the above example, clicking the button triggers both handleButtonClick and handleDivClick because of event bubbling.

Bonus Tip

One Time Listener

The { once: true } option is a boolean parameter you can add when using addEventListener. It's like a golden ticket that ensures your event listener fires only once. After the event is triggered and the handler executed, the listener is automatically removed.

Example

Consider a scenario where you want to show a welcome message to users but only the first time they click a button. The { once: true } option makes this a breeze:

<button id="welcomeButton">Click me for a welcome!</button>

<script>
  function showWelcome() {
    alert("Welcome! Thanks for visiting.");
  }

  document.getElementById("welcomeButton").addEventListener("click", showWelcome, { once: true });
</script>
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
cezarytomczyk profile image
Cezary Tomczyk

Most engineers forget about the very nice option called once.

A boolean value indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked. If not specified, defaults to false.

element.addEventListener("click", eventHandler, { once: true });

Collapse
 
dhrn profile image
Dharan Ganesan

Great tip! Thanks! 🙌

Collapse
 
maximprogramerxx profile image
Maximprogramerxx

gerat post