Friday 20 April 2012

Use a button instead of an anchor tag

When using JQuery and href's we sometimes see the following:-
<a id='MyLink' href="#">My Link</a>
or even worse:-
<a id='ClickMe' href="javascript:void(0);">Click Me</a>
and some jQuery which executes some code, BUT does not redirect the user.
<script>
 $('#ClickMe').click(function(e) {
   e.preventDefault();
   alert('Me clicked');
 });
</script>
Now this works if:-
  1. Javascript is enabled
  2. If JS is disabled then the link should actually should have a fall back, however in this case we don't want to redirect anywhere
  3. Not all browsers support e.preventDefault() so to circumvent this we add a return false at the end of the function
  4. If the page is long; that is longer than the height of the screen then in some browsers the page will jump to the top, losing the Y position

If you think about it these "anchors" exist solely to provide a click event, but do not actually link to other content.

So is there a better solution?

One very nice approach is to convert the anchor tag to a button element.

It can be styled like so:
<button id='Click Me' style="border:none; background:transparent; cursor: pointer;">Click me</button>
the javascript can then be changed to:-
<script>
 $('#ClickMe').click(function(e) {
   alert('Me clicked');
 });
</script>
And of course click events can be attached to buttons without worry of the browser jumping to the top, and without adding extraneous javascript such as onclick="return false;" or event.preventDefault() or even return false.

2 comments:

  1. I was searching online for this very question. I agree with you. Its more semantically correct anyways, is it not?

    ReplyDelete
  2. Wat are yo saying

    ReplyDelete