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.
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:
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: