Home > Software engineering >  How to use an external javascript function in html
How to use an external javascript function in html

Time:05-18

I'm currently trying to build a webpage using html and an external javascript file. The javascript file is named "main.js" and is in the same directory as the html file. I'd like to call a function from the javascript file inside the html file.

The function is linked to a button as is called using the following line:

<button onclick="myFunc()">Click Me</button>

If I use the script tag and embed the javascript inside the html file it works fine, with format:

<script> 
myFunc(){

//Code here
}
</script>

When I put this function in a separate main.js file and then call it using

<script type="text/javascript" src="/main.js"></script>

the button does nothing. Is there a syntax I'm missing?

CodePudding user response:

I did this and it worked for me(the files are separate)

function myFunc() {
    alert("hello")
}
<html>
    <head>

    </head>
    <body>
        <h1> Testing... </h1>
        <button onclick="myFunc()"> Click Me </button>

        <script src="./main.js"></script>
    </body>
</html>

Its also a good idea to be running your code in a simple python server. Python Simple Server Setup

CodePudding user response:

You can try to use Window to define your custom function, see:

if (!window.myFunc) {
  window.myFunc = () => {
    console.log('click');
  }
}
<button onclick="window.myFunc()">Click Me</button>

  • Related