Javascript “Not Links”
In playing around with ways to attach events to <a> elements without triggering the default behavior (mainly when href is ”#”), I came up with a ‘cute’ way to handle it (simply using preventDefault(), but in a somewhat creative way).
The reasons I have for doing it this way are:
1) I’m working with existing code that uses href=”#” pretty much everywhere an event needs to fire on an <a> element
2) to make sure the page NEVER jumps to the top when clicking on a “Not LInk™” (even when Javascript is disabled)
to make it easier to find these Not Links™ when quickly scanning the code.
3) to make my IDE happy (IntelliJ IDEA) so it doesn’t criticize my code and highlight it and call it names (I take it very personally)
So, here’s what I do:
1) Use href=”##” instead of just href=”#”. This makes these Not Links™ stand out a little more, plus I’ll know which ones I put in there since the existing code just uses ”#”. You could really use anything (like ”*” or “!” or be like the cool kids and use “!#”), but if the href at least starts with ”#” then the browser won’t even attempt to navigate away from the current page.
2) Add <a name=”#”></a> as the first element in the <body> and give it an inline style of “position:fixed;left:-9999px;” so your browser wouldn’t jump up to that anchor even if it WANTED to (this makes IntelliJ happy since the href=”##” theoretically has something to link to). Alternatively, you could set up a page on your site to link to so the knuckleheads who have Javascript disabled will get a friendly message that this site requires Javascript to function properly - like href=”/-/” (to keep it short and clean) with your friendly helpful “Turn on Javascript you freak!” message, or maybe set ”/-/” for your 404 page.
3) Attach a ‘click’ event listener to all a elements with href=”##” (or starting with ”##”, which may be useful if you want to make it descriptive of what the Not Link™ is doing, like ”##show_modal”, but that would crankify IntelliJ). We’ll use jQuery’s .on() method so that this technique will work even if these <a> elements are added after the initial DOM load (by some AJAX-y Javascript stuff).
Here’s the jQuery code (on one line):
$('body').on('click','a[href^="##"]',function(e){e.preventDefault();});
So now you can have distinctive looking links that don’t work as a regular link but still let you attach Javascript events to them so you can do nifty Javascript stuff with a little Javascript. Got it? Javascript.
What do you think? Wast of time or useful technique? Or a moderately somewhat useful technique that’s really a waste of time (much like writing this blog post)?