Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way for links to execute javascript code

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..

like image 329
at. Avatar asked Sep 08 '10 14:09

at.


People also ask

How do you execute a JavaScript?

To execute JavaScript in a browser you have two options — either put it inside a script element anywhere inside an HTML document, or put it inside an external JavaScript file (with a . js extension) and then reference that file inside the HTML document using an empty script element with a src attribute.

How do I run JavaScript from a website?

Create a JavaScript shortcutIn the shortcut editor, tap at the top of the action list, begin typing “Run JavaScript…” in the search field, then tap the Run JavaScript on Webpage action to add it to the shortcut editor. Write your script in the text field in the Run JavaScript on Webpage action.

Is it possible to use a hyperlink to call a JavaScript function?

1. Call JavaScript on Hyperlink Click. Add below HREF html code in body section and access on web browser. Now just click link, It will execute JavaScript's myFunction which will show current date as per used above.


1 Answers

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.

like image 167
Dave Aaron Smith Avatar answered Nov 14 '22 23:11

Dave Aaron Smith