1

In javascript what are the different ways of adding an event listener to browser DOM? i have tried the following code, and i was wondering if there are more ways to do this.

let div = document.getElementById("div");
let btn = document.getElementById("btn");

function sayHello() {
    div.innerText = "Hello World";
    console.log("awesome");
}

btn.addEventListener("click", sayHello);
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • 2
    From the documentation: [_β€œThe `addEventListener` method is the_ recommended _way to register an event listener.”_](//developer.mozilla.org/docs/Web/API/EventTarget/addEventListener). The docs also describe the inferior alternatives. – Sebastian Simon Nov 20 '21 at 07:52
  • In JavaScript, there are two ways: [`addEventListener` and the `on` attribute](https://stackoverflow.com/questions/6348494/addeventlistener-vs-onclick). You can further use an inline listener in the HTML but that's not "in JavaScript". – VLAZ Nov 20 '21 at 07:58

1 Answers1

0

In JavaScript, there are two ways for event handling.

  • One of them is addEventListener that you used yourself.
  • Another option is onEvent, here is an example:

Javascript

let hiButton = document.getElementById('someButton');

function sayHello() {
    console.log("Hi");
}

hiButton.onclick = sayHello();