AddEventListener Click
- The document.addEventListener() method attaches an event handler to the document.
- The addEventListener() method attaches an event handler to an element without overwriting existing event handlers.
- The first parameter is the type of the event (like "click" or "mousedown").
- The second parameter is the function we want to call when the event occurs.
- The third parameter is a boolean value specifying whether to use event bubbling or event capturing. This parameter is optional.
Syntax
element.addEventListener(event, function, useCapture)
element.addEventListener(event, function, useCapture)
Explanation
- event - event name like click, keypress, keyup etc.
- function - We can directly write the function or call the function here.
- useCapture - This is the optional and the default value is false.
Code:-
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>addEventListener click function</h1>
<input id="btnid1" type="button" value="Button 1">
<input id="btnid2" type="button" value="Button 2">
<script>
var btn1 = document.getElementById("btnid1");
var btn2 = document.getElementById("btnid2");
btn1.addEventListener("click", fun_name, false);
btn2.addEventListener("click", function()
{
alert("call function definition directly");
}, false)
function fun_name()
{
alert("Function Called");
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>addEventListener click function</h1>
<input id="btnid1" type="button" value="Button 1">
<input id="btnid2" type="button" value="Button 2">
<script>
var btn1 = document.getElementById("btnid1");
var btn2 = document.getElementById("btnid2");
btn1.addEventListener("click", fun_name, false);
btn2.addEventListener("click", function()
{
alert("call function definition directly");
}, false)
function fun_name()
{
alert("Function Called");
}
</script>
</body>
</html>
JavaScript :- AddEventListener Click
Reviewed by Network security
on
May 28, 2019
Rating:
No comments: