2

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 Answers 3

3

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;
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

If the last one was really unobtrusive, the href would point to somewhere useful.
@David Dorward, I agree with you. Will include your comment in the answer.
0

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.

Comments

0

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

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

1 Comment

There's no need to add that. jQuery does that for you. Also, preventDefault is a method of Event objects, not the event target.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.