Archive

Posts Tagged ‘event wrapper’

JavaScript Event Wrapper

March 6, 2010 Comments off

Event Wrapper

js_event.js


/*
* Cross browser Event wrapper
*
* @author:    Costin Trifan
* @date:      06.03.2010
* @license:   MIT License  http://en.wikipedia.org/wiki/MIT_License
* @version:   1.0
*/
var Event = {
	/**
	* Attach an event listener
	* @return this
	*/
	add : function(el, ev, func, capture)
	{
		if (capture == null) { capture = false; }
		if (window.addEventListener) {
			el.addEventListener(ev, func, capture);
		}
		else if (window.attachEvent) {
			el.attachEvent("on"+ev, func);
		}
		else { el['on'+ev] = func; }

		return this;
	}
	/**
	* Detach an existent event listener
	* @return this
	*/
	,remove : function(el, ev, func)
	{
		if (window.removeEventListener) {
			el.removeEventListener(ev, func, false);
		}
		else if (window.detachEvent) {
			el.detachEvent("on"+ev, func);
		}
		else { el['on'+ev] = func; }

		return this;
	}
	/**
	* Prevent the default action & stop the event from propagating
	* @return bool false
	*/
	,cancel : function(e)
	{
	  if(!e) { e = window.event; }
	  if(e.stopPropagation) { e.stopPropagation(); }
	  if(e.preventDefault) { e.preventDefault(); }

	  e.cancelBubble = true;
	  e.cancel = true;
	  e.returnValue = false;
	  return false;
  	}
};

Example


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Cross browser Event wrapper</title>
	<script src="js_event.js" type="text/javascript"></script>
	<script type="text/javascript">
    
	function toggle(el){
		if (el.style.display != 'none')
			el.style.display = 'none';
		else
			el.style.display = 'block';
	}
	
	
    Event.add(window, 'load', function(){
		var a = document.getElementById('a');
		var p = document.getElementById('p');
		Event
			.add(a, 'click', function(e){
				Event.cancel(e);
				toggle(p);
			})
			.add(p, 'click', function(e){
				alert('paragraph clicked');
			});
	});
    
    </script>
</head>

<body>

<p>
	<a id="a" href="#">Toggle</a>
    <span id="p" style="display: block">
    	Lorem ipsum dolor sit amet, consectetur adipisicing elit,
        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
        nisi ut aliquip ex ea commodo consequat.
    </span>
</p>

</body>
</html>