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
- Philosophy, Idiocy, Internet Strategy, .Net Development and JavaScript Web Development
01/05/2009
30/04/2009
JavaScript: Overloading Window onload
Quick post on a very common methodology I've been using to chain events to the window.onload event in pure JavaScript:
if (window.onload == null) {
window.onload = loadAutoSubmitScript;
} else {
var ol = window.onload;
window.onload = function() { ol(); loadProc(); }
}
function loadProc() { alert("The window is loaded"); }
This should work for pretty much every page you use.
Over and Out
if (window.onload == null) {
window.onload = loadAutoSubmitScript;
} else {
var ol = window.onload;
window.onload = function() { ol(); loadProc(); }
}
function loadProc() { alert("The window is loaded"); }
This should work for pretty much every page you use.
Over and Out
03/04/2009
Google Street View Coming To Toronto
I had the privilege of witnessing the Google's street view car as it canvassed downtown Toronto yesterday.
Although I have a feeling the Google's street view car was stalking me, I will still grant Google the rights to use my image on their street view.
Here are the precise details of where I should appear in Toronto. Let's keep our fingers crossed for now!
View Larger Map
Although I have a feeling the Google's street view car was stalking me, I will still grant Google the rights to use my image on their street view.
Here are the precise details of where I should appear in Toronto. Let's keep our fingers crossed for now!
View Larger Map
Subscribe to:
Posts (Atom)