Skip to content

JavaScript addEventListener click | Example code

  • by

JavaScript addEventListener click work on HTML element fires some action when I click, as anticipated. You need to pass a reference to the function.

document.getElementById("btn").addEventListener("click", function(){
   displayTooltip(2)
});

JavaScript addEventListener click

A simple example code, where clicking on the button will show an alert box with a message.

<!DOCTYPE html>  
<html>  
<body>  

  <button id = "btn"> Click</button>  

  <script>  
    document.getElementById("btn").addEventListener("click", fun);  
    function fun() {  
      alert("Hello addEventListener()")  
    }  
  </script>  
</body>  
</html>  

Output:

JavaScript addEventListener click

Or use this code

const element = document.querySelector(".class__name");

element.addEventListener("click", () => {
	console.log("clicked element");
});

Do comment if you have any doubts or suggestions on this Js event listener topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading