Progressive enhancement of anchor tags to avoid onclick="return false;"
- by Chris Beck
Unobtrusive JS suggests that we don't have any onclick attributes in our HTML templates.
<a href="/controller/foo/1">View Foo 1</a>
A most basic progressive enhancement is to convert an that anchor tag to use XHR to retrieve a DOM fragment. So, I write JS to add an event listener for a."click" then make an XHR to a.href.
Alas, the browser still wants to navigate to "/controller/foo". So, I write JS to dynamically inject a.onclick = "return false;". Still unobtrusive (I guess), but now I'm paying the the cost of an extra event handler.
To avoid the cost of 2 event listeners, I could shove my function call into the onclick attribute
<a href="/controller/foo/1" onclick="myXHRFcn(); return false;">
But that's grodo for all sorts of reasons.
To make it more interesting, I might have 100 anchor tags that I want to enhance. A better pattern is a single listener on a parent node that relies on event bubbling. That's cool, but how do I short circuit the browser from navigating to the URL without this on every anchor node?
onclick="return false;"
Manipulating the href is not an option. It must stay intact so the context menu options to copy or open in new page work as expected.