document.getElementById("myBtn").addEventListener("click", displayDate);
<body>
<p>This example uses the addEventListener() method to attach a click event to a button.</p>
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
document.getElementById("myBtn").addEventListener("click", displayDate);
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
</body>
</html>
Add an Event Handler to an Element
element.addEventListener("click", function(){ alert("Hello World!"); });
The addEventListener() method allows you to add many events to the same element, without overwriting existing events:
element.addEventListener("click", myFunction); element.addEventListener("click", mySecondFunction);
You can add events of different types to the same element:
element.addEventListener("mouseover", myFunction); element.addEventListener("click", mySecondFunction); element.addEventListener("mouseout", myThirdFunction);
When passing parameter values, use an "anonymous function" that calls the specified function with the parameters:
element.addEventListener("click", function(){ myFunction(p1, p2); });
With the addEventListener() method you can specify the propagation type by using the "useCapture" parameter:
The removeEventListener() method removes event handlers that have been attached with the addEventListener() method:
element.removeEventListener("mousemove", myFunction);
The addEventListener() and removeEventListener() methods are not supported in IE 8 and earlier versions
var x = document.getElementById("myBtn"); if (x.addEventListener) { // For all major browsers, except IE 8 and earlier x.addEventListener("click", myFunction); } else if (x.attachEvent) { // For IE 8 and earlier versions x.attachEvent("onclick", myFunction); }
<html> <head> <title>DOM Tutorial</title> </head> <body> <h1>DOM Lesson one</h1> <p>Hello world!</p> </body> </html>
<div id="div1"> <p id="p1">This is a paragraph.</p> <p id="p2">This is another paragraph.</p> </div> <script> var para = document.createElement("p"); var node = document.createTextNode("This is new."); para.appendChild(node); var element = document.getElementById("div1"); element.appendChild(para); </script>
<div id="div1"> <p id="p1">This is a paragraph.</p> <p id="p2">This is another paragraph.</p> </div> <script> var para = document.createElement("p"); var node = document.createTextNode("This is new."); para.appendChild(node); var element = document.getElementById("div1"); var child = document.getElementById("p1"); element.insertBefore(para, child); </script>
the number of elements in an HTMLCollection:
var myCollection = document.getElementsByTagName("p"); document.getElementById("demo").innerHTML = myCollection.length;
"If you would thoroughly know anything, teach it to other."
- Tryon Edwards -