HTML Events You Should Know

Introduction to HTML Events




HTML events are actions recognized by web browsers that can trigger JavaScript functions or other responses. These events can be initiated by users, such as clicks and keystrokes, or generated by the system, like when the page finishes 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.

Example:


<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.

Example:


    
<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.


Example:


      
<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.


Example:


      
<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>

Event Listeners in JavaScript 🧩

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

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>


In the above example, clicking the button triggers both `handleButtonClick` and `handleDivClick` due to event bubbling.

Follow our blog for usefull content related like web development, coding and free udemy course 

If you like this content: Buy me a coffee

Previous Post Next Post