Function to trigger events in JavaScript

Bookmark and Share

The following is a generic function that can be used to trigger events in JavaScript.

It takes 2 parameters:

  • obj - the object to trigger the event on
  • evt - the name of the event to trigger (as a string)
 
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 ) { //IE
       var evObj = document.createEventObject();
       fireOnThis.fireEvent( 'on' + evt, evObj );
     } 
} 

Example implementation

 
fireEvent(document.getElementById('mylink'),'click'); //fires click event on element with id="click"
fireEvent(document.getElementById('myinput'), 'blur'); //fire blur event on element with id="blur"

The above can be accomplished via jQuery without the need for a custom function.


$('#mylink').trigger('click'); //fires click event on element with id="click"
$('#myinput').trigger('blur'); //fire blur event on element with id="blur"
References: 
http://www.w3schools.com/jsref/dom_obj_event.asp
http://stackoverflow.com/questions/827716/emulate-clicking-a-link-with-javascript-that-works-with-ie
http://api.jquery.com/trigger/

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.