-2

I'm trying to get a button written in HTML to link to a separate JavaScript file when it is clicked, the button in question is coded below

<input type="button" id="clickme" value="Submit" />

I am using the Brackets code editor, and the js file I want to be linked is in the same project as my HTML code, if that helps at all

thanks in advance

3 Answers3

1

Load the script into the page with a <script> element.

Keep your code in a function instead of simply running the whole thing with the script is loaded.

Find the button in the DOM (e.g. with getElementById) and bind the function as a click event listener with addEventListener).

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
0

If you mean link, I would use an <a> (anchor) tag which has an attribute href which is the reference. Therefore, you could use:

<a href="http://example.com/public/js/script.js">Link to JS</a>

Or perhaps you meant the onclick attribute which would be: <input type="button" id="clickme" onclick="myfunction()" value="Submit" />

However, as was pointed out, this is not best practice either.

jQuery.click() vs onClick

Provides some options and reinforces the idea that onclick is not the best way to trigger a Javascript function.

kchason
  • 2,586
  • 15
  • 22
  • Don't use `onclick` attributes. They have nasty gotchas and fail to separate concerns. – Quentin Oct 13 '17 at 14:27
  • W3Schools is not a good reference. It is frequently misleading, somethings outright wrong, and almost never an example of best practices. – Quentin Oct 13 '17 at 14:28
  • @Quentin, this is true, I would generally use eventListeners like you mentioned, but was trying to target the specific question. Personally, I'd use jQuery `.click` or `.on('click'...` since my projects nearly all utilize jQuery. – kchason Oct 13 '17 at 14:30
-1

Just link your js script to a page by:

<script src="js/button.js"></script>

and then just call action in that scripts through the class or id.

 <button id="btnShow"><h1 class="jumbotron-heading">Expand</h1></button>
 <p class="p1">Test</p1>

That's a jQuery not js, but anyway a good example as I think

$('#btnShow').click(function(){
 $('.p1').show();
});