How to work with events

<!-- add event listener in html code -->
<div id ="mydiv1" onclick="alert('i am clicked')">...</div>
// add event listener in JavaScript
var element = document.getElementById("mydiv2");

element.addEventListener("click", function(e) {
   alert("handle onclick event via a callback function");
});

element.onclick = (e) =>{
    alert("handle onclick event via a callback function");
};

element.addEventListener("click", 
  {handleEvent: function(e) {
    alert("handle onclick event via a HandleEvent object");
  }});

// emulate click event
var event = new MouseEvent('click', {
    'view': window,
    'bubbles': true,
    'cancelable': true
  });

element.dispatchEvent(event);

element.removeEventListener("click", cb);

event attributes

HTML elements have special event attributes with names on<event name>. The value of these attributes is the javascript code that implements the action associated with the event.

The this keyword refers to the HTML element on which the event occurs.

The event variable holds the Event object.

<div style="width:100px; height: 100px;
             background-color: green;"
     onclick="console.log(this, event.target, this===event.target);">
</div>

Event object

The Event object is base object for other events like MouseEvent.

propertydescription
target The element where event was occur.
type Name of event. There are many types of events, most useful are
  • load - element and related resources have been loaded
  • click - mouse click on element
  • change - content of a form element have changed