views:

194

answers:

2

This question is mainly out of curiosity (I have a different working solution to the issue). Trying to do some basic progressive enhancement: a table should have each row clickable to go to another page using JavaScript. For people w/out JavaScript, there's a link in the first column of each row. If JavaScript is enabled, the links should be disabled. One of the many simple ways to do so is

a.setAttribute("onclick", "return false;");

after initializing the click events on the rows. But it appears more elegant to use addEventListener to achieve the same

a.addEventListener("click", function() { return false; }, false);

However, the latter doesn't work. I believe the reason for this is that more than one event listener can be added this way and if they'd return different truth values the result would be ambiguous. Is this assumption correct or am I getting something wrong? Please explain the inner workings behind this.

+1  A: 
a.addEventListener("click", function(event) { event.preventDefault(); return false; }, false);

This should fit your needs.

Philipe Fatio
Thanks for the quick answer. I'll try this tomorrow morning (it's very late where I live) and will vote it up if it works.
Gerald Senarclens de Grancy
Another small thing: why is it necessary to have both preventdefault() and to return false?
Gerald Senarclens de Grancy
+1  A: 

a.setAttribute("onclick", "return false;");

Avoid setAttribute, you should never need it for handling HTML documents and there are browser problems (especially with IE, and especially with event handlers). Instead use the direct DOM HTML properties:

a.onclick= function() {
    return false;
};

addEventListener is fine if you use preventDefault() as suggested by fphilipe, but you'd need an attachEvent backup for IE where DOM Events aren't supported. This might be overkill for just trying to disable a link.

Personally to disable a link I'd prefer to get rid of it completely, so that it's no longer available for operations like open-in-new-window or bookmark-link, and it doesn't take part in the keyboard tabbing order.

So you could removeChild() it, or replaceChild it with a span with the same text, or kick the text out of the link:

while (a.firstChild)
    a.parentNode.insertBefore(a.firstChild, a);
a.parentNode.removeChild(a);
bobince