JavaScript: Dynamically Attach Event Handler to any HTML Element

Want to attach an event handler to HTML element but not by writing as HTML property but directly using JavaScript! Attaching event dynamically for an element can be needed for the reason you do not have direct access to HTML element or for the reason you think that not attaching event directly makes clean markup and it separates JavaScript and HTML codes.

Attaching event handler to an HTML Element:

Here onClick event is attached to the link having id=link1. Now, when user click on link1, the user will be redirected to blank page.

HTML:
<a href="http://only-your-views.blogspot.com" id="link1" >test</a>

JavaScript:

<script type="texxt/javascript">
    document.getElementById('link1').onclick = function() {
                  location.href='about:blank';
                  return false;
    }
</script>

Another Example of Attaching Event Handler:

HTML:
<p id="p1">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque adipiscing elementum tristique. Nulla facilisi. Curabitur vestibulum tempus tempus. Proin eu laoreet sem.
</p>

JavaScript:

<script type="text/javascript">
  document.getElementById('p1').onclick = function() {
     alert(this.innerHTML)
   }
</script>

The above example will output the alert box with paragraph text.

Another way of writing the above event handler code: Here, instead of anonymous function, real function is used.

<script type="text/javascript">
document.getElementById('p1').onclick = paragraphHTML; // no parentheses in paragraphHTML
function paragraphHTML()
{
	alert(this.innerHTML);
}
</script>

The above method is good, it works and is simple to write also. But by using the above way of registering the event handler, we cannot register more than one handler to an event (onClick, onMouseOver, etc). So, it seems below method is not needful when you want to register only one event handler to an element but this is the new way of registering event handler and W3C accepted method.

So, we have new way of doing the same thing - Registering Event Handler for any HTML element.

Again the same example of registering the onClick Event to a link:

<a href="http://www.satya-weblog.com" id="link1" >test</a>

<script type="text/javascript">
 function eventHandler(e) {
	window.location.href='about:blank';
	if (!e) var e = window.event;
        // Stop event propagation
	//if( e.stopPropagation ) {
	//	e.stopPropagation();
	//}
	//e.cancelBubble = true;  // IE
        // Prevent default action
	if( e.preventDefault ) { e.preventDefault(); }
	e.returnValue = false;
 }
var lnk = document.getElementById('link1');
if( lnk.addEventListener ) // W3C, FF
{
  // event , handler and True/False=Capture/Bubble
  lnk.addEventListener('click', eventHandler, false);
  //lnk.addEventListener('click', eventHandler2, false); // Another handler
}
else if( lnk.attachEvent ) // IE
{
  lnk.attachEvent('onclick', eventHandler);
  //lnk.attachEvent('onclick', eventHandler2); // Another Handler
}
</script>

I hope, you found the code and example useful. so, why not share it with others and spread the word!

Comments are open for an year period. Please, write here on Facebook page.