DOM Event Handling

June 08, 2024

Here's a JavaScript utility code to attach event listeners on elements for common UI interactions (click, submit, input, etc.).

Complete Utility Code

index.html

divlesshtml
[btn data-onclick="add-item"
  Add Item
]

dom-events.js

js
let DOMEvents = (function() {
    
  let eventsMap = { 
    onclick: {
  	  'add-item': () => app.AddItem(),
    },
  };
  
  let listening = function(selector, dataKey, eventType, callbacks) {
    let elements = document.querySelectorAll(selector);
    for (let el of elements) {
      let callbackFunc = callbacks[el.dataset[dataKey]];
      el.addEventListener(eventType, callbackFunc);
    }
  };
  
  function Init() {
    listening('[data-onclick]', 'onclick', 'click', eventsMap.onclick);
  }
  
  return {
    Init,
  };

})();


DOMEvents.Init();


Usage & Explanation

First, create eventsMap, an object containing a unique key for each event callbacks. The mapping structure is up to you. Then, we register the event mapping in Init().

dom-events.js

js
let eventsMap = { 
  onclick: {
  	'add-item': () => app.AddItem(),
  },
};

function Init() {
  // listening(selector, datasetKey, eventType, callbackKeyMapping);
  listening('[data-onclick]', 'onclick', 'click', eventsMap.onclick);
}

Next, create a button with data-onclick attribute. The value is a unique key in the eventsMap.

index.html

divlesshtml
[btn data-onclick="add-item"
  Add Item
]

Finally, initialize the utility on application start.

index.js

js
DOMEvents.Init();

Comments

Thank You

for your visit