Events

  • To create a new Event
let event = new Event(type[, options]);
  • To create CustomEvent
let event = new CustomEvent(type[, options]);
  • type: a string like “click” or “my-event”
  • options:
    • bubbles: (boolean) if true, event bubbles up
    • cancellable: (boolean) if true, event.preventDefault() will work
    • detail: (only in CustomEvent) to provide extra data

Dispatch Events

  • Use method dispatchEvent(event)
<button id="elem" onclick="alert('Click!');">Autoclick</button>
<script>
	let event = new Event("click");
	elem.dispatchEvent(event);
</script>
  • if event.isTrusted is true then event comes from real user action else it is script-generated
  • dispatchEvent runs async for native events and synchronously for custom events

Custom Events

<h1 id="elem">Hello for John!</h1>
 
<script>
  // additional details come with the event to the handler
  elem.addEventListener("hello", function(event) {
    alert(event.detail.name);
  });
 
  elem.dispatchEvent(new CustomEvent("hello", {
    detail: { name: "John" }
  }));
</script>
  • If inside handler you call event.preventDefault(), then the dispatchEvent() returns false