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..
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With