0

So on W3Schools they show this example:

<p id="demo">A Paragraph</p>

<button type="button" onclick="myFunction()">Try it</button>

<script>
    function myFunction() {
        document.getElementById("demo").innerHTML = "Paragraph changed.";
    }
</script>

If I had an external JS File called myJSFile.js and all it had was

 function myFunction(id) {
        document.getElementById(id).innerHTML = "Paragraph changed.";
 } 

and I wanted to pass the ID "demo" from the HTML into the .js file how would I do it? I know you start with

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

but I don't know how to call the myFunction function and pass an argument into it.

To be extra clear I want to do something like

<head>
    <script src = "myJSFile.js></script>
</head>
<body>
    ...
    <p id = "demo></demo>
    myFunction("demo")
</body>
Aire
  • 127
  • 2
  • 11
  • 1
    When you use script tags to load a javascript file they are loaded on your page. You can access any top level objects/variables from them directly, so just `myFunction(whateverID)` – Marie Feb 25 '16 at 19:55
  • The question has a duplicate, but is this the right one? The question here is actually how to call the javascript function with argument from HTML? – quasoft Feb 25 '16 at 19:58
  • I'm trying to do myFunction(whateverID) but nothing is happening. – Aire Feb 25 '16 at 20:00
  • You need to call the function either in a script tag in the body part, or in event handler that is attached to DOM element. Try – quasoft Feb 25 '16 at 20:12
  • It turns out I don't need the src when I call the function in the body and that was the entire problem. I am ashamed. – Aire Feb 25 '16 at 20:19

0 Answers0