Showing posts with label Cancel Event. Show all posts
Showing posts with label Cancel Event. Show all posts

01/05/2009

JavaScript: Chaining Cancelable Events - If you're not first, you're last

Another quick post on cancelable events in JavaScript. An example of a cancelable event is the keydown method. If I return false from a keydown method JavaScript will not allow the action of that keydown event to proceed. For example, I could return false on a document keydown event to cancel the ctrl+c behaviour etc. etc.

The following is a nice method I've built and tested only in IE 7 which allows users to chain JavaScript events together.

Obviously this could be compressed significantly.

addToObject: the HtmlElement we want to attach the cancelable event to.

eventName: the name of the event we want to trap.

methodDelegate: a JavaScript function delegate / closure for the JavaScript method to attach to the event.

order: First or Last. You can build on this however you want.

Enjoy,

function AddCancelableEvent(addToObject, eventName, methodDelegate, order) {
if (addToObject[eventName] != null) {
var oe = addToObject[eventName];
if (order == "first")
addToObject[eventName] = function(e) {
var r = methodDelegate(e);
if (r == false) return false;
return oe(e);
};
else // "if you're not first you're last" - Ricky Bobby
addToObject[eventName] = function(e) {
var r = oe(e);
if (r == false) return false;
return methodDelegate(e);
};

} else {
addToObject[eventName] = methodDelegate;
}
};


Over And Out

07/01/2009

JavaScript: Cancel Event Bubbling

Another common tidbit of JavaScript code:

Cancel event bubbling:

function stopEvent(evt){
evt = evt || window.event;
if (evt.stopPropagation){
evt.stopPropagation();
evt.preventDefault();
}else if(typeof evt.cancelBubble != "undefined"){
evt.cancelBubble = true;
evt.returnValue = false;
}
return false;
}