HTML | DOM addEventListener() Method

The addEventListener() method attaches an event handler to the specified element.

Syntax:

element.addEventListener(event, function, useCapture)

Note: The third parameter use capture is usually set to false as it is not used.

Below program illustrates the DOM addEventListener():

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>DOM Location host Property</title>
    <style>
        h1 {
            color: green;
        }
          
        h2 {
            font-family: Impact;
        }
          
        body {
            text-align: center;
        }
    </style>
</head>
  
<body>
    <h1>GeeksforGeeks</h1>
    <h2>addEventListener() method</h2>
  
    <p>
     This example uses the addEventListener() 
     method to add many events on the same 
     button.
    </p>
  
    <button id="myBtn">Try it</button>
  
    <p id="demo"></p>
  
    <script>
        var x = document.getElementById("myBtn");
        x.addEventListener("mouseover", myFunction);
        x.addEventListener("click", mySecondFunction);
        x.addEventListener("mouseout", myThirdFunction);
  
        function myFunction() {
            document.getElementById("demo").innerHTML += "Moused over!<br>"
            this.style.backgroundColor = "red"
        }
  
        function mySecondFunction() {
            document.getElementById("demo").innerHTML += "Clicked!<br>"
        }
  
        function myThirdFunction() {
            document.getElementById("demo").innerHTML += "Moused out!<br>"
        }
    </script>
  
</body>
  
</html>                 

chevron_right


Output:

  • Initially:

  • Mouse Over Event:

  • Mouse Clicked Event:

  • Mouse Out Event:

Supported Browsers: The browser supported by Location host Property are listed below:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Opera
  • Safari


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.