element.addEventListener(event, function, useCapture);
<!DOCTYPE html>
<html>
<body>
<p> Example of the addEventListener() method. </p>
<p> Click the following button to see the effect. </p>
<button id = "btn"> Click me </button>
<p id = "para"></p>
<script>
document.getElementById("btn").addEventListener("click", fun);
function fun() {
document.getElementById("para").innerHTML = "Hello World" + "<br>" + "Welcome to the bianchenghao6.com";
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p> This is an example of adding multiple events to the same element. </p>
<p> Click the following button to see the effect. </p>
<button id = "btn"> Click me </button>
<p id = "para"></p>
<p id = "para1"></p>
<script>
function fun() {
alert("Welcome to the bianchenghao6.com");
}
function fun1() {
document.getElementById("para").innerHTML = "This is second function";
}
function fun2() {
document.getElementById("para1").innerHTML = "This is third function";
}
var mybtn = document.getElementById("btn");
mybtn.addEventListener("click", fun);
mybtn.addEventListener("click", fun1);
mybtn.addEventListener("click", fun2);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p> This is an example of adding multiple events of different type to the same element. </p>
<p> Click the following button to see the effect. </p>
<button id = "btn"> Click me </button>
<p id = "para"></p>
<script>
function fun() {
btn.style.width = "50px";
btn.style.height = "50px";
btn.style.background = "yellow";
btn.style.color = "blue";
}
function fun1() {
document.getElementById("para").innerHTML = "This is second function";
}
function fun2() {
btn.style.width = "";
btn.style.height = "";
btn.style.background = "";
btn.style.color = "";
}
var mybtn = document.getElementById("btn");
mybtn.addEventListener("mouseover", fun);
mybtn.addEventListener("click", fun1);
mybtn.addEventListener("mouseout", fun2);
</script>
</body>
</html>
addEventListener(event, function, useCapture);
<!DOCTYPE html>
<html>
<head>
<style>
div{
background-color: lightblue;
border: 2px solid red;
font-size: 25px;
text-align: center;
}
span{
border: 2px solid blue;
}
</style>
</head>
<body>
<h1> Bubbling </h1>
<div id = "d1">
This is a div element.
<br><br>
<span id = "s1"> This is a span element. </span>
</div>
<h1> Capturing </h1>
<div id = "d2"> This is a div element.
<br><br>
<span id = "s2"> This is a span element. </span>
</div>
<script>
document.getElementById("d1").addEventListener("dblclick", function() {alert('You have double clicked on div element')}, false);
document.getElementById("s1").addEventListener("dblclick", function() {alert('You have double clicked on span element')}, false);
document.getElementById("d2").addEventListener("dblclick", function() {alert('You have double clicked on div element')}, true);
document.getElementById("s2").addEventListener("dblclick", function() {alert('You have double clicked on span element')}, true);
</script>
</body>
</html>