views:

66

answers:

6

So there are 4 main methods I'm aware of to execute javascript code from a link. For my requirements, I need to do so without moving the screen anywhere (linking to # and not returning false is bad). SEO for the executed javascript code, if possible, is important too. So what's the right way to do this?

method 1 (need to make sure myCode() returns false always):

<a href="#" onclick="return myCode();">execute</a>

method 2 (seems to make the most sense?):

<a href="javascript:myCode();">execute</a>

method 3:

<a href="javascript:void(0);" onclick="myCode();">execute</a>

method 4 (not as pleasant semantically as the others I think):

<span id="executeMyCodeLink" class="link">execute</a>
<script>
$('#executeMyCodeLink').click(myCode);
</script>

with method 4, you can use onclick as well of course..

+4  A: 

I prefer method 4, but with two differences:

  • Move the script to a separate file. Unobtrusive JavaScript is happy JavaScript.
  • Use the a tag, link to # and return false.
GSto
+1 for unobtrusive JavaScript.
Matt Ball
Is it better to do `<a href='#'>` or `<a href="javascript:void(0);">`?
Rocket
Definitely #4 - it's just the most comfortable one IMHO @Rocket: I'd say `href="#"`
ApoY2k
Why use the 'a' tag?
patrick dw
+1  A: 

<a href="#_"> works too, that way you don't need a return false. (Any non-existent anchor will work really).

Also, method 4 only works if you use jQuery. Most of my websites only have one or two small javascript effects, I'm not loading jQuery for that.

Litso
Interesting, I did not know that. This also helps since if you are using jQuery, returning false would prevent further chaining.
GSto
A: 

Using jquery is an unobtrusive way to handle javascript calls. So I would say method 4. You can also just do:

$(a#linkId).click(...);
mjw06d
A: 

I prefer method 4, too.

Binding events to dom objects seperately is a more elegant way and I think that's a good programming habit.

Zafer
A: 

I like method 4 as well. Whenever possible i try to not put anything directly in the even attributes or to write js directly into the href. I do this because in most cases ill actually put a non-js url as the href so it degrades for non-js enabled browsers. The second reson is i dont like to pollute elements with cruft :-)

prodigitalson
A: 

You make the page not jump and use an "a" tag with an href and method 4 using preventDefault.

<a id="executeMyCodeLink" href="#">execute</a>
<script>
  $('#executeMyCodeLink').click(function(event) {
    event.preventDefault();
    myCode();
  });
</script>

It's important to include an href because links won't style properly and your html won't validate otherwise.

Dave Aaron Smith
This seems to make the most sense, I like that jQuery has a mechanism for this without relying on return false which has other consequences.
at