PROWAREtech

articles » current » javascript » event-utility

JavaScript: Event Utility

A utility for handling events in the browser.

Here is an object for adding and removing event handlers.

var EventUtility = {
	addHandler: function(element, type, handler){
		if (element.addEventListener){
			element.addEventListener(type, handler, false);
		} else if (element.attachEvent){
			element.attachEvent("on" + type, handler);
		} else {
			element["on" + type] = handler;
		}
	},
	getClipboardText: function(event){
		var clipboardData = (event.clipboardData || window.clipboardData);
		return clipboardData.getData("text");
	},
	setClipboardText: function(event, value){
		if (event.clipboardData){
			return event.clipboardData.setData("text/plain", value);
		} else if (window.clipboardData){
			return window.clipboardData.setData("text", value);
		}
	},
	getCharCode: function(event){
		if (typeof event.charCode == "number" && event.charCode) {
			return event.charCode;
		} else {
			return event.keyCode || 0;
		}
	},
	getEvent: function (event) {
		return event ? event : window.event;
	},
	getTarget: function (event) {
		return event.target || event.srcElement;
	},
	preventDefault: function (event) {
		if (event.preventDefault) {
			event.preventDefault();
		} else {
			event.returnValue = false;
		}
	},
	removeHandler: function(element, type, handler){
		if (element.removeEventListener){
			element.removeEventListener(type, handler, false);
		} else if (element.detachEvent){
			element.detachEvent("on" + type, handler);
		} else {
			element["on" + type] = null;
		}
	},
	stopPropagation: function (event) {
		if (event.stopPropagation) {
			event.stopPropagation();
		} else {
			event.cancelBubble = true;
		}
	}
};

Using the EventUtility object:

EventUtility.addHandler(document.getElementById("textbox"), "keypress", function(event){
	event = EventUtility.getEvent(event);
	var target = EventUtility.getTarget(event);
	var charCode = EventUtility.getCharCode(event);
	if (!/[a-zA-Z]/.test(String.fromCharCode(charCode))){
		EventUtility.preventDefault(event);
	}
});

One thing worth noting here is that users may paste anything into this field so, on the blur event, code should double check that there are only letters entered.


This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE