Friday, October 4, 2013

javascript:void(0)

A common need that we come across (like, multiple times daily), is to have a button or hyperlink which opens a dialog or does some other action in JavaScript.

Way back in the late 90s, our technique was this:
 <a href="javascript:void(0)" onClick="doWhatever()">Click me</a>
But over the years, this was pointed out as being not entirely a good thing. It's a hyperlink to nothing, it can confuse screen readers (really? who has those, and do they really read out the entire URL?)
, and it's more semantically correct to do this:
<span class="lookslikelink" onClick="doWhatever();">Click me</span>

So I adopted this technique. A class called fakelink can be constructed which looks like other hyperlinks (cursor:pointer; text-decoration:underline; color:blue;) and now we don't have these semantically-incorrect null-links, just DIVs and SPANs with event handlers.

But, enter mobile...

As you have probably noticed, mobile devices won't necessarily detect these "hotspots", and they give strong preference to hyperlinks. On my six-month-old telephone running Android 2.1, for example, I have a menu of 3 links:
<li><a href="/postings">Postings</a></li>
<li><span class="fakelink" onClick="openSignupDialog();">Sign Up</span></li>
<li><a href="/catalog">Our Catalog</a></li>

On the desktop, this works great: three links, one of which opens the popup dialog. On mobile not so much: it's impossible to click the middle link. It seems the phone detects the tap and the nearest hotspot, and you've tapped on one of the two outside links. Even without a menu of other hyperlinks, the tap events often "just didn't work"

So, back to the old ways...

<li><a href="/postings">Postings</a></li>
<li><a href="javascript:void(0);" onClick="openSignupDialog();">Sign Up</a></li>
<li><a href="/catalog">Our Catalog</a></li>

The desktop doesn't really care about this sort of semantic violation, and it works on phones. And I'd rather have working links, than win an argument about semantics.



No comments:

Post a Comment

Note: Only a member of this blog may post a comment.