9
Jul/09
2

Quick Tip: don’t use links with JavaScript unless the link goes some where

We have all done it, many times I am sure. You need an element to attach some JavaScript to, that will execute some function, so you use <a href=”#” onclick=”myfunction(); return false;”>click me</a>. The link does not go any where so we take steps to prevent the link from actually going any where. I say don’t use a link, use any other DOM element instead and style it like a link, if you actually want it to look like a link.

1
2
3
4
5
6
7
8
9
  <style>
    .linkLike{
      cursor: pointer;
      text-decoration: underline;
      color: #0000ff;
    }
  </style>
  <span class="linkLike" onclick="document.getElementById('clickie').innerHTML += 'clickity click<hr />'">Click Here</span>
  <div id="clickie"></div>

Click Here     Clear

I can think of one situation that you would actually want to use links and that is if you want the link to go some where in the case that JavaScript is disabled. You could for instance take users to a page detailing the need for JavaScript for the page to function properly with instructions to enable JavaScript.

[Post to Twitter]  [Post to Plurk]  [Post to Yahoo Buzz]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to Reddit]  [Post to StumbleUpon] 

Tweet This Post links powered by Tweet This v1.3.9, a WordPress plugin for Twitter.