Click here to Skip to main content
15,891,687 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have included code which works perfectly but when I move the javascript tags and code to a external .js file the function call in the html file is not recognized "function is not defined". I believe the problem is scope, of the function call in the html file... apparently its not global and therefore it is not recognized by the js file. When I moved the javascript code to an external file within the same folder as the html file I inserted <script src="myjsfile.js"></script> into the body section...I also tried inserting it into the head section, however it still didn't work. How can I make function calls (by button clicks) within my html file without having to include the javascript code in the html file? How would you fix this simple file?


HTML
<!DOCTYPE html>
<html>
<head>
  <title>My Title</title>
  <style>
  #myDIV {
    width: 200px;
    height:100px;
    background-color: #FC20FF;
    color: #27FFF8;
  }
  </style>
  </head>
<body>
  <p>Click the button to set the backgroundColor property.</p>
  <button onclick="myFunction()">Execute myFunction</button>
  <div id="myDIV">
    <h1>How are you?</h1>
  </div>
  <script>
  function myFunction() {
    document.getElementById("myDIV").style.backgroundColor = "#291CE8";
  }
  </script>
</body>
</html>


What I have tried:

Moving the location of the javascript file reference and many of the other suggestions posted on line, but none of them worked. Most talked about local and global variables, this I believe is a local or global function problem.
Posted
Updated 13-Apr-18 6:35am
Comments
Bryian Tan 12-Apr-18 23:11pm    
maybe the path to the JavaScript file not correct? Try you absolute path and see what happen.
F-ES Sitecore 13-Apr-18 5:14am    
Either the path to the js file is wrong or you are using the function before it is defined. Showing us the code that works isn't much help, we need to see the code that doesn't work and know where the html and js files are relative to each other.

1 solution

Using the word "myFunction" for the name of the function is a problem. When I changed the name to stop or go or some other word it worked fine with the js in a separate file. Apparently the word myFunction is a protected word.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900