Using functions from other files in JavaScript - javascript

I'm making a game in JS using P5, and I came upon a problem.
In my html file I have references to .js files:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.3/p5.min.js"></script>
<script src="main.js"></script>
<script src="isKeyPressed.js"></script>
<script src="blocks.js"></script>
<script src="player.js"></script>
</head>
<body>
</body>
</html>
I have one .js file defining the function isKeyPressed():
function isKeyPressed(keyQuery) {
var did = false;
for(var i = 0; i < keysPressed; i++) {
if(keysPressed[i] === keyQuery) {
did = true;
}
}
return did;
}
I reference this in another object inside player.js:
player.motion = function() {
if(isKeyPressed('w')) {
this.velocity.add(0,-5);
}
if(isKeyPressed('s')) {
this.velocity.add(0,5);
}
if(isKeyPressed('a')) {
this.velocity.add(-5,0);
}
if(isKeyPressed('d')) {
this.velocity.add(5,0);
}
}
But when I try to call player.motion, I get the error:
Uncaught TypeError: isKeyPressed is not a function
Does anyone know why this is occurring?

For the record, I don't think the accepted answer is correct. Specifically, I don't think the accepted answer really changes anything from what you were originally doing. My guess is that you had another problem in your code (like a syntax error) that was causing this error, and you fixed that in the process of implementing the suggested solution. So while it might look like the solution fixed your problem, really it was something else.
I'm providing this alternative answer so you don't think you have to define your JavaScript in your html directly, as that is definitely not the case.
I tried testing out your setup by creating a smaller example consisting of three files:
index.html
<!DOCTYPE html>
<html>
<head>
<script src="one.js"></script>
<script src="two.js"></script>
</head>
<body onload="printObj()">
</body>
</html>
one.js
function printOne(){
console.log("one");
}
two.js
var obj = {};
obj.printTwo = function(){
console.log("two");
printOne();
}
function printObj(){
obj.printTwo();
}
This is pretty much exactly what your setup is, and it works fine. You absolutely do not need to put your JavaScript in your html. As long as the JavaScript files are correctly loaded in the proper order, then you can use functions and variables from one file in another file.
There are two main things that could cause your problem:
Are your files correctly loaded?
Are there any syntax errors you haven't noticed? (This is my guess as to what caused your original problem.) Check the JavaScript console, and try running some test code to actually run the functions you're trying to call.
Did you get all the file names correct?
Are you behind a firewall, or are there other network problems that might cause a problem with loading?
Are your files loaded in the proper order?
For file two.js to access code defined in one.js, you have to make sure one.js is loaded before two.js. It looks like you've done this correctly, but are you sure the JavaScript is where you think it is?
In other words, are you sure it was in player.js and not in main.js?
You might want to get rid of this ambiguity by placing related JavaScript in the same file. It doesn't make a ton of sense to have one file define a keysPressed array and then another file use that array to define an isKeyPressed() function. Just put them in the same file, and make sure that file is loaded before other files that use it.
The accepted answer doesn't change anything with regard to when stuff is loaded. Unless you had a syntax error, or the player.motion() function was actually in the main.js file, or you had a network loading problem, your code should have worked. So one of those things must be your actual problem. You do not have to define your JavaScript in your html for it to work.

I recommend not making a file name have capitals. So change it from
<script src="isKeyPressed.js"></script>
to
<script src="iskeypressed.js"></script>
also change the file name too.

You could try something like this
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.3/p5.min.js"></script>
<script src="main.js"></script>
<script src="isKeyPressed.js"></script>
<script src="blocks.js"></script>
<script src="player.js"></script>
<script>
player.motion = function() {
if(isKeyPressed('w')) {
this.velocity.add(0,-5);
}
if(isKeyPressed('s')) {
this.velocity.add(0,5);
}
if(isKeyPressed('a')) {
this.velocity.add(-5,0);
}
if(isKeyPressed('d')) {
this.velocity.add(5,0);
}
}
</script>
</head>
<body>
</body>
</html>
This is importing all functions from the isKeyPressed.js file and therefore you are able to reference it in the <script> tag. You were not able to use isKeyPressed.js's functions in player.js because you cannot reference it.

Related

Is there a way to make my a JavaScript file not to run in a html page?

I have two html files(index.html and project.html), index.html contain or needs two javascript files(main.js and index.js).
The main.js contains the functions that both html files needs. And the index.js has the functons that only index.html needs.
So am saying index.html-->(main.js,index.js) and project.html-->(main.js).
The issue is that when I open the project.html the DOM elements that I called in index.js is throwing errors saying that the element is null.
The thing is that the DOM element that is causing the error is only created in index.html and not project.html but project is not supposed to call or know that function.
index.html
<script src="asset/javaScript/javaScript_for_index/main.js" defer type="module"></script>
<script src="asset/javaScript/javaScript_for_index/index.js" defer type="module"></script>
project.html
<script src="asset/javaScript/javaScript_for_index/main.js" defer type="module"></script>
This is where i get the error in the inspector. Note that the error comes from the project.html and it is caused by the index.js
I know that this is a bit confusing but this is the best i can explain it.
Thanks in advance!
Two things:
Note that all your <script> elements should appear in your markup before the closing </body> element.
On each page, only reference the <script>(s) that you need for that page
Example:
index.html
<script src="main.js"></script>
<script src="index.js"></script>
</body>
</html>
project.html
<script src="main.js"></script>
</body>
</html>
Example:
index.html needs main.js and index.js
project.html needs A CERTAIN function in main.js ONLY
so main.js
function functionsThatIndexNeeds() {
alert('Im in index.html!!!');
}
function functionsThatProjectNeeds() {
alert('IM IN PROJECTS~~~');
}
index.html
<script>functionsThatIndexNeeds()</script>
projects.html
<script>functionsThatProjectNeeds</script>
The point is to call ONLY the functions that each HTML files need.
Tell me if this works on you!:)
Before we do anything start with clearing your cache. (Important)
If you are sure that you have done everything right, just like #Rounin answer suggest,
Then run your code again, inspect to make sure your error is coming from index.js and if it is, then you are somehow injecting index.js into the page without knowing , (maybe somewhere at the middle of your body or something else), you might have to do a more thorough debugging than just asking. And most probably you have not told us everything because you might not be aware of it.
Try searching for any occurrence of index.js on your project.html script. (Ctrl+F)
Now if all else fails and you have to move on fast, then u can try this hack on your index.html and index.js script.
Index.html
<script> var page = "index" </script>
Put this on line 1, before anything else, because I don't know what line might be caising your problem
Then on index.js wrap your codes with an if statement (i.e put if statements to check if the page = "index" to prevent unwanted codes from running on other pages
E.g:
If (typeof page !== undefined && page == "index") {
// allow code to execute
}
This is a dirty hack, but it might kept you going until you get a more experience engineer to debug your codes...
Obviously, you must have something in main.js that is referencing DOM parts that are in index.html. Stop referencing those, and you'll be okay. Note, that if I have a DIV in index.html with ID foo which project.html does not have, then you can use document.querySelectorAll() function to check if that element exists (can look at length, returned from that, as well as other options like undefined), and then react if it doesn't exist. That can help you delineate items from index.html versus project.html.

Calling javascript function from js file does not works

I have a simple javascript function on my page that works well, but I decided to move it away from index.html to a seperate js file.
The problem is that I cannot get it to execute from that seperate file.
This has been asked many many times here and the solution is always the same, but it just wont work for me. Also on google I can find lots of examples but they simply do not work for me. I tried many of them but with no luck.
So I must be missing something obvious I guess.
This is the header of my index.html
<?php session_start(); ?>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" href="test.css">
<script src="gttJSFunctions.js" type="text/javascript"></script>
</head>
<body>
...
The function in gttJSFunctions.js is called Logout()
As I said it works perfect when I put it inside my index.html, but I cant get it to execute from the seperate js file
this is the entire content of gttJSFunctions.js
<script language='JavaScript'>
function Logout()
{
conf = confirm("Are you sure you want to logout?");
if (conf)
{
window.open("logout.php", "_self");
}
}
Can someone please point out what I am doing wrong.
Your external JavaScript file should contain only JavaScript. No tags.
Just remove the <script language='JavaScript'> from your file and you are good to go.
Remove <script language='JavaScript'> from your gttJSFunctions.js file because it's already a Javascript file, you don't have to specify it.
Best practice: put <script ... /> tags at the bottom of your code, just before the </body> tag. It will improve your page speed and also, as Archer told, avoid you to deal with the DOM ready common mistake.

ReferenceError when calling function in external script from a script tag

I feel like there is something very little I'm doing wrong, but I can't find it. I can't figure out how to call an externally-defined function from within a script tag, it keeps giving me ReferenceError's.
I've reduced my code to the most minimal, so here's what I've got. This is my HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<button id="mrbutton" type="button">Mr Button</button>
<div id="barChart"></div>
<script src="d3/d3.min.js"></script>
<script src="d3/charts/bar.js"></script>
<script>
chartParams = {};
document.getElementById('mrbutton').addEventListener('click', () => {createBarChart(chartParams)});
</script>
</head>
</html>
d3/d3.min.js is D3 version 3. Here's what I have in d3/charts/bar.js:
'use strict';
const createBarChart = params => {
console.log('hello there!');
};
console.log('script loaded!');
But when I load up the page, the Javascript console spits out:
script loaded!
Uncaught ReferenceError: createBarChart is not defined
If I move the code in d3/charts/bar.js into the <script> tag in the HTML, it works fine, but I want to reuse the code so I want it external. What am I doing wrong? Why can't I call createBarChart?
Update: Using Babel to compile down to Ecmascript2015 doesn't change anything, still the same ReferenceError. Also changed the event listener to an arrow function.
Update: I removed the D3 code and am just calling a console.log(), but still no luck.
I got it to work. Not sure if this will help anyone else (hopefully it can), but I just restarted my computer. That's all; no code changes whatsoever. My original code works fine now (even the original .addEventListener()).
It wasn't a browser caching issue, since I tried several browsers in private mode, and I still really don't know what the problem is. If anyone has any idea what it was, please do comment, I'm still puzzled despite being able to move on.

Best way to access external JavaScript file and place contents in div?

So, lets say you have a page that wants to load from a javascript file and it includes
temp.html file
<script src="example.js"></script>
<p class="one"></p>
Now in the example.js file you have a function that is
function getInfo() {
var place = "foo"
$(".one").html(place);
}
//Edit currently I call the function inside the JS file
getInfo();
My question is how would you connect the two files so that the external javascript file knows that it is pointed to the paragraph with the class one?
Normally when this is in a single page, you would call the function and the info will be set.
I have seen a getScript method and a load method for Jquery. Would that be applicable here?
Any ideas on how to approach this? If you provide some code that will be super helpful.
Thanks in advance.
Looks like you want to execute getInfo() as soon as it's defined (i.e.: example.js is loaded).
You can try this approach:
<script src="example.js" onload="getInfo();"></script>
In your example.js, change getInfo() to something like this:
function getInfo() {
$(document).ready(function() {
var place = "foo"
$(".one").html(place);
});
}
Your language is confusing, but you could use jQuery's $(document).ready function which would suffice. Generally speaking, an externally loaded file should execute where the tag is in the script.
A hack could be to place a tag before the end of your document body, give it an id, and then use $('#id').ready() there. In general though, you could just try coding the transclusion concept (I'm guessing you're used to this) from scratch using intervals and timeouts.
<div id="rdy">
</div>
</body>
Then in your file:
$('#rdy').ready(getInfo);
Just my added opinion, you should consider that Google is up to some not-so-nice things these days, they are long-gone from the "do no evil" mantra.
If we assume you have a JavaScript file that contains this content:
function getInfo() {
var place = "foo"
$(".one").html(place);
}
then your markup will look something like this:
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="example.js"></script>
<script>
$(function(){
getInfo();
});
</script>
</head>
<body>
<p class="one"></p>
</body>
</html>
$(function(){ ... }); is just the simplified version of $(document).ready(function(){ ... });. They both more or less handle the onload event, which fires when page has finished loading.

Using $ or the JQuery keyword in external JS File

Below is the content in my external js file.
Please i only have one function in my js file and i am calling this function
from one of .cshtml file during onload event.
function startJs()
{
$("#tabs").tabs();
getImages();
var imgCount = 0;
var imgArray = new Array();
}
Running this code i get the error saying "$ is not referenced". I get the same "not referenced error if i use the keyword JQuery.
I also tried declaring the function like this but still getting the same message.
$(function () {
$("#tabs").tabs();
});
How can i make the Jquery symbols work in external js files. I feel that i am missing something very simple here but i just can't figure out what i am missing.
Please note i am making a call to this code from a file that has a reference to Jquery.
Anybody has any solution to this? Thanks in advance.
Your HTML should look like this, note the order of the JS files:
<html>
<head>
...
<script src="jquery.js"></script>
<script src="yourCustomFile.js"></script>
</head>
<body>
...
</body>
</html>

Categories