views:

39

answers:

3

There are several ways to define click action on anchor tag like:

<a href="javascript: void(0)" onclick="funciton_X()">click here</a>

or

<a href="javascript: funciton_X()">click here</a>

or

<a id="a_tag" href="javascript: void(0)">click here</a>  
<script type="text/javascript">  
$('#a_tag').click(function(){})  
</script>

Is there a significant difference which one will I use? What are their advantages and disadvantages. Is there a fourth option?

+3  A: 

The last one is called unobtrusive javascript and it's the one I would recommend you using as it advocates a clear separation between your markup and javascript. It also has also the advantage of smaller markup files, while external javascript files would be cached by the client browsers.

As @David Dorward pointed out in the comments section if you are using the last method it is recommended to have the href attribute point to some real url so that the client will be redirected if for example he has javascript disabled. This technique is called progressive enhancement when you define a minimal markup of your site and based on the client browser capabilities you enrich with functionality that's not available with markup such as AJAX and some other nice UI effects.

So to summarize:

<a id="a_tag" href="basic.htm">click here</a>

and then in a separate javascript file (example with jQuery but you could use anything you like):

$(function() {
    $('#a_tag').click(function() {
        // TODO: some nice effect
        return false;
    });
});
Darin Dimitrov
If the last one was really unobtrusive, the `href` would point to somewhere useful.
David Dorward
@David Dorward, I agree with you. Will include your comment in the answer.
Darin Dimitrov
Great answer, thank you both.
Ilian Iliev
A: 

I prefer the latter. Separating your javascript from your html is good practice, and enables easier maintenance of code. Libaries like JQuery, Prototype, Mootools etc help a lot with this. It's quite similar to doing CSS in an external stylesheet vs. inline-styles. The preference is keep them separated, allowing you to produce clean and semantic html.

Take another example:

<form id="myForm"> .... </form>

Say I want to submit this form, but I want to do it on the asynchronously, I could use JQuery to attach an event which will submit it via AJAX, and if javascript isn't available, it degrades nicely to do a standard post back.

Matthew Abbott
A: 

You need to even add this.preventDefault(); in the function.

//sry I didn't know how to add comment to DarinDimitrov's answer.

kapser
Why do we need this?
Ilian Iliev
There's no need to add that. jQuery does that for you. Also, `preventDefault` is a method of Event objects, not the event target.
Tim Down