|
| > Is it possible to set up an event handler or something else
| > so that when *any* link on the page is clicked it 'fires-up',
| > executes some JS and then continues to process the link
| > that was clicked?
| > (Without having JS or 'onClick' added to each & every link?)
|
| In theory, yes, but in practice, no. In the event model defined by the
| World Wide Web Consortium's (W3C) Document Object Model (DOM) Level 2
| Events specification, the first phase that an event goes through is called
| capturing. In this phase, the event object that represents the action
| moves from the document root (the parent of the HTML element) down to the
| target element. For example:
|
| <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
| "
http://www.w3.org/TR/html4/strict.dtd">
|
| <html>
| <head>
| <title>Example</title>
| </head>
|
| <body>
| <div>
| <a href="somePage.html">A link</a>
| </div>
| </body>
| </html>
|
| When the user clicks on the link, a click event moves from the root, to
| HTML, to BODY, to DIV, to A. The DOM 2 Events specification allows you to
| attach an event listener in "capturing" mode. Listeners in this mode
| receive events on their way towards the target.
|
| All this means that you *could* attach a capturing listener on the
| document root to listen for the click event. When it occurs, you'd use
| Event.target to check that the destination was a link, then do whatever
| processing you wanted (including cancelling the event, if you wish).
| Unfortunately, IE doesn't implement DOM 2 Events, and it doesn't provide
| an equivalent for the capturing phase.
|
| I did write code that would emulate this, but it's probably too much for
| this case (it also isn't totally finished).
|
| > I've looked everywhere but can't find out how,
| > or if it's even possible via Javascript...
|
| There is a more workable solution. It involves programatically iterating
| through all links in the page and adding a click listener.
|
| function addListener(e, t, l) {
| /* You can remove the if statement below as it's not needed by
| * this code. I included it simply to be a "good example".
| */
| if(('object' == typeof e) &&
| ('string' == typeof t) &&
| ('function' == typeof l)) {
| if(e.addEventListener) {
| e.addEventListener(t, l, false);
| } else {
| e['on' + t] = l;
| }
| }
| }
|
| function init() { // Call from "onload"
| for(var i = 0, l = document.links, n = l.length; i < n; ++i) {
| addListener(l
, 'click', <function>);
| }
| }
|
| In the init() function above, replace <function> with the name of the
| function you called when the user clicks a link.
|
| Hope that helps and good luck,
| Mike
|
| --
| Michael Winter
| Replace ".invalid" with ".uk" to reply by e-mail
Thanks
Regards