DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Fire Javascript DOM Events

08.17.2008
| 8110 views |
  • submit to reddit
        Fire Javascript DOM events

function fireEvent(obj, evt) {
  var fireOnThis = obj;
  if (document.createEvent) {
    var evObj = document.createEvent("MouseEvents");
    evObj.initEvent(evt, true, false);
    fireOnThis.dispatchEvent(evObj);
  else if (document.createEventObject) {
    fireOnThis.fireEvent("on" + evt);
  }
}

Usage: clicking on a link using Javascript

HTML
<a href="foo.html" id="fooanchor" style="display: none>Nothing to see here</a>
Javascript
fireEvent(document.getElementById('fooanchor'), "click")