Reputation: 3215
I am having a "duh" moment in which I am trying to execute a JavaScript function via an a
href
.
<a href="javascript:test()">Open New Form</a>
The function is stored in an external JavaScript file. If I have it inline with my function within <script>
tags and the a href
after it, it works.
What is the best method to execute a JavaScript function stored in another file?
Upvotes: 0
Views: 1562
Reputation: 115
You can use:
<a href="javascript:" onclick="test()">Open New Form</a>
Upvotes: 0
Reputation: 3215
The issue was tied to caching as I had made updates to my JavaScript file but it wasn't showing. I resolved this, and then my core issue by using the following jQuery in my JavaScript file to call the function on click:
$('#commentlink').click(function () {
addComment();
});
This is called in the HTML like this:
<a class="pointer" id="commentlink" onclick="javascript:OpenPopUpPage();">Add Comment</a>
Upvotes: 0
Reputation: 3735
If you use
<a href="javascript:test()">Open New Form</a>
and keep "test" function outside the page then also it will work as long as you are giving the reference of that javascript in your page like <script src="path"></script>
As you wanted the onclick function of the element so its good/best to use
<a onclick="test()"></a>
Upvotes: 1
Reputation: 535
If you're not linking to another page, try using the <button>
element:
<button onclick="test()">Open a New Form</button>
Also, make sure your JavaScript file is properly loading on the page.
Upvotes: 1