How to add event handlers on html elements by JavaScript?

0 votes
27 views
Ravi Vishwakarma asked 10 days ago in Web Application by Ravi Vishwakarma

How to add event handlers on html elements by JavaScript?

1 Answer

0 votes
Ethan Karla answered 7 days ago by Ethan Karla

How to add event handler

The addEventListener() method attaches an event handler to the specified element. The addEventListener() method attaches an event handler to an element without overwriting existing event handlers.

You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two 'click' events. You can add event listeners to any DOM object not only HTML elements. i.e the window object. The addEventListener() method makes it easier to control how the event reacts to bubbling. When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup.

You can easily remove an event listener by using the removeEventListener() method.

Syntax

element.addEventListener(event, function, useCapture);

The first parameter is the type of the event (like 'click' or 'mousedown' or any other HTML DOM Event.). 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.

<button id='myBtn'>Try it</button>

<script>
document.getElementById('myBtn').addEventListener('click', function() {
  alert('Hello World!');
});
</script>
<button id='myBtn'>Try it</button>
<script>
document.getElementById('myBtn').addEventListener('click', myFunction);
function myFunction() {
  alert ('Hello World!');
}
</script>


<button id='myBtn' >click me</button>
<p id='demo'></p>
<script>
let p1 = 5;
let p2 = 7;
document.getElementById('myBtn').addEventListener('click', function() {
  myFunction(p1, p2);
});
function myFunction(a, b) {
  document.getElementById('demo').innerHTML = a * b;
}
</script>