How To Track Callback Function Events In JavaScript?

- 1 answer

I recently created a simple function for simple JavaScript events which do not need all the bells and whistles of addEventListener. All was well until I needed to track Events (outside of Internet Explorer). While window.event seems to work in IE and Chrome, Firefox and some other browsers did not implement it. I'm trying to figure out how to get the same results on this example below.

Currently this example works for "Test Button 2" which returns the event object. How can we fix the addEvent function to support the same behavior? I tried various option without any luck...

function addEvent (type, object, callback) {
  if (typeof object[type] != 'undefined') {
    var existingFunctions = object[type];
    object[type] = null;
    object[type] = function () {
      if (existingFunctions) {

var testButton1 = document.getElementById("test1");

function callBack(event) {

addEvent('onclick', testButton1, callBack); // This returns 'undefined' :(

var testButton2 = document.getElementById("test2");

testButton2.onclick = function(event) {
	callBack(event); // This works. 
<button id="test1">
Test Button 1

<button id="test2">
Test Button 2



Due to the lack of answers about using simplified custom event listener functions, I ended up going back to using a addEventListener polyfill.

To make sure recent browsers don't load this script for no reasons, I'm conditionally loading it while still in <head> with this simplified conditional loader:

// Event listener methods for IE8.
if (!Element.prototype.addEventListener && !document.body) {
     document.write('<script src="addEventListener.js"></script>');