views:

136

answers:

4

From my experience I know three different ways to execute a Javascript function when a user clicks on a link

  1. Use the onclick attribute on the link

    <a href="#" onclick="myfunction();return false;">click me</a>
    
  2. Use the href on the link

    <a href="javascript:myfunction();">click me</a>
    
  3. Don't touch the link, do everything in js

    <a href="#">click me</a>
    

    (in the Javascript we will stop the default event, and call the function)

Which one is better? What are the advantages and disadvantages?

EDIT deleted the "javascript:" on onclick

+7  A: 

Unobtrusive Javascript (your third example) with graceful degredation is the best choice.

Kevin
It's the same as with the css styles - do not style="" inside the html, use the selectors to generic style the page and outsource the css.
sod
but the third sometimes means that you must provide an id in the link, so you could end up with several ids on your Html. And your JS code gets kinda ugly when you have a lot of different links with different functions
pleasedontbelong
Not necessarily, pleasedontbelong. You can traverse by the index of the element within the DOM. Or you can use event delegation and handle the click based on a class name, href value, etc.
Kevin
No, there are plenty of ways to select elements other than getElementById - although they will generally involve using some kind of library function if you want to look the elements up quickly
Gareth
@pleasedontbelong Then you're doing it wrong! Remember, strictly one unique `id` per element; if you've got many functions to attach to one element, then call the functions from inside the event handler. If you need one function on multiple elements, consider using a `class` instead.
Yi Jiang
nono you didn't understood me =D i mean, let's say that i have a link that calls the download() function, another that calls the change() function, another that calls pleasekillme(), another link that calls ... and so on.. that means that each link has a UNIQUE id, but i have a lot! and my js code is getting bigger and bigger
pleasedontbelong
Either way, you'll have a lot of code, but that's outside the scope of this question. It's best to keep markup separate from behavior.
Kevin
not really, using onclick saves me a few lines actually, and since i'm workin with objects in JS is nice to call methods without having to explicitly add the "onclick" events on links in JS
pleasedontbelong
It is not necessarily the best choice. The separation of markup from behaviour that your answer provides comes at the expense of two things: first, until your script to assign the event handler runs, typically when the document has loaded, clicking on the link has no effect, whereas if the event handler is assigned via an attribute the link has the desired behaviour immediately. Second, as pleasedontbelong observes, the unobtrusive way generally involves extra code. Separation of markup from behaviour is a valid goal but don't be brainwashed into thinking it's the only goal.
Tim Down
A: 

Or alternatively, use jQuery

$(function() {
    $('[id$=myLinkID]').click(function(e) {
        myFunction();
    });
});
grimorde
that's the 3rd option =P, either using JQuery, mootools, prototype or native js
pleasedontbelong
+2  A: 

It is always good to have a link in the href attribute so as to support users who have disabled JavaScript on their browsers.

<a href="http://www.mywebsite.com/javascriptdisabled.html" onclick="myfunction(); return false;">click me</a>
Q_the_dreadlocked_ninja
+1 advantage... but it has it's downside, you need to stop the event using "return false", it's not a big deal but it a "hair in the soup"
pleasedontbelong
'return false' stops the link from firing and the page 'jumping', you cannot avoid it if you are writing inline JS(as far as i know) - Is there any particular reason it must not be used besides the fact that it is ugly
Q_the_dreadlocked_ninja
nop,there's no other reason besides that. but its good to have in mind that if you call the function from inside the href, you wont need to have the return false, but you'll have problems with browsers that does not support JS, and one day, all browsers will support JS, now in chrome it's not even possible do disable js code.. so my guess is that in the future we could use the second option that looks cleaner (at least to me)
pleasedontbelong
All major browsers support javascript *now*, but still a lot of people have javascript turned off using the NoScript Firefox plugin, for example.
Gareth
+1  A: 

None of the above. Use the click event (assigned either as an attribute or via script if you prefer) and have a real URL as a fallback:

<a href="realpage.html" onclick="myfunction(); return false;">click me</a>

or HTML:

<a href="realpage.html" id="myLink">click me</a>

Script:

document.getElementById("myLink").onclick = function() {
    myfunction();
    return false;
};

Also, don't prefix code in event handler attributes with javascript:. It's incorrect and only doesn't throw an error by coincidence (which is that in JavaScript, javascript: creates a label called javascript).

Tim Down
thanks, i've corrected the question and deleted the "javascript:" but besides that, i dont see any difference, what you proposed is basically the 1st and 3rd option. But as @Yi Jiang commented, you might have problems if there's no "mylink" id in the page (e.g. link that are generated dinamically).. in the end, it all depends on what you need to do
pleasedontbelong
There's a huge difference: mine actually does something when you click on the link with JavaScript turned off.
Tim Down
ahhh you talking about the "realpage.html" :P well yes it does something when no JS. But that wasn't my question. I wanted to explore the advantages and disadvantages of choosing one of them
pleasedontbelong
OK. Well, I discussed the relative merits of using an attribute versus using script to assign an event handler in my comment to another answer. The thing about when JavaScript is switched off is genuinely significant though, and you shouldn't ignore it.
Tim Down