createEvent-dispatchEvent and preventDefault example

This example demonstrates simulating a click on a checkbox using DOM document.createEvent, event.initMouseEvent, and element.dispatchEvent methods, as well as using the event.preventDefault method in an event handler to prevent the default action associated with the event from happening.

Example

Example Markup
<input type="checkbox" id="checkbox"/><label for="checkbox">Checkbox</label>
<input type="button" onclick="simulateClick();" value="Simulate click"/>
<input type="button" onclick="addHandler();" value="Add a click handler that calls preventDefault"/>
<input type="button" onclick="removeHandler();" value="Remove the click handler that calls preventDefault"/>

Scripts used

function preventDef(event) {
  event.preventDefault();
}

function addHandler() {
  document.getElementById("checkbox").addEventListener("click", 
    preventDef, false);
}

function removeHandler() {
  document.getElementById("checkbox").removeEventListener("click",
    preventDef, false);
}

function simulateClick() {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var cb = document.getElementById("checkbox"); 
  var canceled = !cb.dispatchEvent(evt);
  if(canceled) {
    // A handler called preventDefault
    alert("canceled");
  } else {
    // None of the handlers called preventDefault
    alert("not canceled");
  }
}