Javascript functions not working in external .js file

I used an external .js file for my JavaScript, but I had a problem with my HTML being unable to find any of my JavaScript functions. I know that functions work, because if I transfer it from an external file to my html file, it works fine. The error I get in the JavaScript console in Chrome is that my functions are not defined. I also know that my path to my external page works, because I have canvas tags that read JavaScript perfectly.

To repeat, this works:

HTML:

<canvas id="Canvas7"></canvas> 

JavaScript:

 window.onload = function() { var g=document.getElementById("Canvas7"); var ctx=g.getContext("2d"); var grd=ctx.createRadialGradient(75,50,5,90,60,100); grd.addColorStop(0,"red"); grd.addColorStop(1,"white"); ctx.fillStyle=grd; ctx.fillRect(10,10,150,80); // ... }; 

But the following gives me the error "Uncaught ReferenceError: getLocation not defined":

HTML:

 <button onclick="getLocation()">Click here</button> 

JavaScript:

 window.onload = function() { var x=document.getElementById("location"); function getLocation(){ if (navigator.getlocation){ navigator.getlocation.getCurrentPosition(showPosition,showError); } else{ x.innerHTML="GeoLocation is not supported by this browser."; } } // ... } 

This is not a huge problem, since I can just save the JavaScript in my HTML file, but it takes up a lot of space, and I would prefer that everything be organized. If anyone knows how I can solve this problem, it will be very appreciated.

+6
source share
1 answer

As you defined your functions in the window.onload getLocation , getLocation not a global function, so it is not known to the code provided by the onclick attribute. This is why your browser has returned undefined . An easy fix is ​​to make it a global function. For instance:

 window.getLocation = function() { ... } 

However, requiring variables and functions to be defined globally is what you want to avoid long-term projects.

You can achieve this by dropping the use of onclick HTML attributes and linking (non-global) callbacks from your main code:

HTML:

 <button id="getloc">Click here</button> 

JavaScript:

 document.addEventListener("DOMContentLoaded", function() { var x = document.getElementById("location"); getloc.addEventListener("click", function() { if (navigator.getlocation){ navigator.getlocation.getCurrentPosition(showPosition,showError); } else{ x.textContent = "GeoLocation is not supported by this browser."; } }); // ... } 
+1
source

Source: https://habr.com/ru/post/944257/


All Articles