On Tue, 04 May 2004 11:37:52 +0200, Guido Wesdorp <guido@infrae.com> wrote:
[snip]
[color=blue]
> I guess what you want to do is use JavaScript to find all anchors in a
> document (document.getElementsByTagName('a'))[/color]
A more reliable approach is to use the document.links collection. It's
supported by more browsers.
[color=blue]
> and put an onclick on them, that does what you want it to do and also
> cancels the event ('event.preventDefault()' on Mozilla,
> 'event.returnValue = false' on IE).[/color]
If you use other approaches for attaching listeners (which I've added
below), returning false will suffice.
As we're attaching listeners directly to the A elements, one can simply
use the this operator to get a reference to the element.
[color=blue]
> function process_link_click(event) {
> var link = event.target ? event.target : event.srcElement;
> var href = link.getAttribute('href');[/color]
Unless you're working with XML, link.href will do and is more reliable.
[color=blue]
> // do something with your href here
> if (event.preventDefault) {
> // mozilla
> event.preventDefault();
> } else {
> event.returnValue = false;
> };
> };[/color]
By the way, you don't usually need to terminate blocks with a semi-colon.
The only exceptions I can think of at the moment are with the function
operator
ref = function() {
};
and the object literal
obj = {};
Notice that the difference is due to the assignment which, as a statement,
should be terminated.
[color=blue]
> function find_and_patch_links() {
> var links = document.getElementsByTagName('a');[/color]
var links = documents.links;
is more compatible.
[color=blue]
> for (var i=0; i < links; i++) {[/color]
That's an error. In any case, it's better to save the property value
rather than repeatedly looking it up:
for( var i = 0, n = links.length; i < n; ++i ) {
[color=blue]
> if (link.addEventListener) {[/color]
This is also an error as 'link' is undefined.
[color=blue]
> // mozilla
> link.addEventListener('click', process_link_click, false);
> } else if (link.attachEvent) {[/color]
Unfortunately, Microsoft's attachEvent() mechanism is flawed and doesn't
set the this operator correctly. As I'm adding support for older browsers
anyway, we'll skip attachEvent() and use the event properties with IE.
[color=blue]
> // IE
> link.attachEvent('onclick', process_link_click);
> };
> };
> };[/color]
The culmination of which produces:
function process_link_click( event ) {
var href = this.href;
event = event || window.event;
// do something with your href here
// ...
if( event.preventDefault ) {
event.preventDefault();
}
return false;
}
function find_and_patch_links() {
var links = document.links, link;
for( var i = 0, n = links.length; i < n; ++i ) {
link = links[ i ];
if( link.addEventListener ) {
link.addEventListener( 'click', process_link_click, false );
} else {
link.onclick = process_link_click;
}
}
}
Mike
--
Michael Winter
M.Winter@blueyonder.co.invalid (replace ".invalid" with ".uk" to reply)