Computer Science, asked by kunaldiwakar8905, 11 months ago

How to add an event handler to an element in JavaScript HTML DOM?

Answers

Answered by hassan911ee
0

Hi there. In order to add an event handler to any element, you first have to assign an ID to the element. For instance, Suppose I have a Button with an ID of "Btn".

Now in the JavaScript, you need to -

1) Get the element. -

var myButton = document.getElementById("btn");  

The next step is to add the event handler itself. Now for this example I'm using a "click" event listener but you can use the one which you want.

2) Add the event handler. -

myButton.addEventListener("click", function(){

// Your code here.

// Sample code -

alert("Hello. you clicked a button.");

})

Please Note -

You can use a function that has already been declared or even with an arrow function (Introduced in ES6)  but in this case I'm using anonymous function.

Similar questions
Math, 11 months ago