Reputation: 52500
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..
Upvotes: 6
Views: 4038
Reputation: 4567
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.
Upvotes: 5
Reputation: 60413
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 :-)
Upvotes: 0
Reputation: 2190
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.
Upvotes: 0
Reputation:
Using jquery is an unobtrusive way to handle javascript calls. So I would say method 4. You can also just do:
$(a#linkId).click(...);
Upvotes: 0
Reputation: 27600
<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.
Upvotes: 2
Reputation: 42350
I prefer method 4, but with two differences:
Upvotes: 4