JavaScript JS – A simple script for adding & attaching multiple Event Listeners

It’s often impractical to keep all required event listeners bundled in one declaration. The larger your file, the greater the need for organization. It’s good practice to keep individual script and functional components together. Attempting to integrate and merge code that doesn’t belong together will become an organizational nightmare as your script grows. From a semantic stand-point, it’s better to keep your individual script blocks separate and consolidated, which means you need to separate your event declarations. To do this you need an efficient method of declaring multiple events without adding excess code bloat.

A simple solution is to include a template function that allows you to easily add multiple instances of an event listener without excessive code bloat.

You can use this function as a core template for declaring event listeners:

function addEvent(type,func) {
	if (document.addEventListener) document.addEventListener('DOMContentLoaded', function(){
		window.addEventListener(type, func);
	});
	else if (document.attachEvent) document.attachEvent('DOMContentLoaded', function(){
		window.attachEvent('on'+type, func);
	});	
}

Later on, when you need to add an event, simply invoke the addEvent(type, func)  function using the event of your choice (load, scroll, resize, etc) with a function you wish to attach to the event.

addEvent('load', myFunction);

or even…

addEvent('load', function() { /*do something*/ })

Well that’s all there is to it. Now you can keep your JavaScript code tidy and organized.

You can also find this code on GitHub.

Gabriel Nix

Just another blogger. I'm also passionate about graphic design, programming, photography, circuitry, technology, philosophy, religion, and the human experience.