Events in HTML are actions or occurrences that happen on a page element, such as a mouse click, key press, or page load. These events can be handled with JavaScript to perform specific actions.

Types of events

There are several types of events in HTML, including:

  • Mouse events: like click, double click, mouse movement, etc.
  • Keyboard events: like pressing a key, releasing a key, etc.
  • Form events: how to submit a form, change a form field, etc.
  • Loading events: like loading a page, loading an image, etc.

Handling events with JavaScript

To handle events in HTML, you must use JavaScript. JavaScript allows you to define functions that will be executed when a specific event occurs on a page element.

For example, to run a function when a button is clicked, you could use the following code:

  
    <button onclick="myFunction()">Click here</button>

    <script>
      function myFunction() {
        alert("The button was clicked!");
      }
    </script>
  

In this example, the function "myFunction()" will be executed when the button is clicked. The function displays an alert with the message "The button was clicked!".

Adding events with JavaScript

It is also possible to add events with JavaScript. This allows you to define functions to be executed when a specific event occurs on a page element, without having to use the "onclick" attribute.

To add an event with JavaScript, you can use the "addEventListener()" method. For example, to run a function when a button is clicked, you could use the following code:

  
    <button id="myButton">Click here</button>

    <script>
      document.getElementById("myButton").addEventListener("click", myFunction);

      function myFunction() {
        alert("The button was clicked!");
      }
    </script>
  

In this example, the "addEventListener()" method is used to add a click event to the button with the ID "myButton". The "myFunction()" function is defined as the function to be executed when the click event occurs.

Conclusion

Events in HTML are an important part of creating interactive and dynamic web pages. With JavaScript, it is possible to handle events to perform specific actions when a user interacts with a web page.

Now answer the exercise about the content:

_Which method is used to add an event to a page element with JavaScript?

You are right! Congratulations, now go to the next page

You missed! Try again.

Article image Form validation with JavaScript

Next page of the Free Ebook:

15Form validation with JavaScript

2 minutes

Obtenez votre certificat pour ce cours gratuitement ! en téléchargeant lapplication Cursa et en lisant lebook qui sy trouve. Disponible sur Google Play ou App Store !

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text