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.
Related
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.
I'm new to web development, and was having issues with two plug-ins. I already found a workaround to solve it, but I'm not convinced at all about what I did, so I ask you guys if you can enlighten me on what is this about.
The page in question uses SlimScroll and DataTables plugins. At first, I had an HTML file like this one.
<body>
<!-- STUFF -->
<!-- SCRIPTS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="plugins/slimScroll/jquery.slimscroll.min.js" type="text/javascript"></script>
<script src="plugins/DataTables/datatables.min.js" type="text/javascript"></script>
<script src="assets/scripts/tablas.js" type="text/javascript"></script>
<script src="assets/scripts/general.js" type="text/javascript"></script>
At the bottom, general.js is used to handle click events and other stuff, and tablas.js has the code that picks up a file with data and displays it in DataTables. The relevant code from general.js:
$(document).ready(function() {
$('#contenedor-menu').slimScroll({
height: '100%'
});});
And the code for tablas.js:
$(document).ready(function() {
$('#tablita').DataTable( {
"ajax": 'data/COut2.txt',
} );});
With this structure, when I load the page, SlimScroll fails with the message in the console: "TypeError: $(...).slimScroll is not a function"
Then after touching around, I switched the order of the scripts in the HTML file. I put datatables first and then slimscroll.
<script src="plugins/DataTables/datatables.min.js" type="text/javascript"></script>
<script src="plugins/slimScroll/jquery.slimscroll.min.js" type="text/javascript"></script>
And now it works ok, with no errors.
Could somebody please explain to me what's going on?
Thanks in advance!
The use of multiple $(document).ready(function() { } is the main cause of this issue. There should be only one Document Ready event handler.
You may try using the pageLoad() function or onLoad() events
Not positive but it is usually best practice to put the scripts you absolutely need before everything else in the head. This is so that the content of the page does not finish loading until all the dependencies have been loaded first.
By reordering your scripts you may have a solution that will only work some of the time.
Put all the scripts you need to load in the head and your general.js script at the end of your body element.
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.
I'm learning jQuery, and I'm running into a small problem. jQuery code works when I put it directly in my tags in my HTML, but when I import it from a different file, nothing happens. These are my script tags in HTML:
<script type="text/javascript" src="scripts/jquery-1.10.2.js"></script>
<script type="text/javascript" src="scripts/test.js"></script> <!--This is my jQuery code-->
test.js contains the following code:
$(document).ready(function(){
console.log("Hello");
});
When the page loads, the console is empty. However, when I paste the following code as so, in my html document, everything works fine.
<script>
$(document).ready(function(){
console.log("Hello");
});
</script>
Do you really have a folder named scripts in the folder where your HTML files exist? Otherwise try changing this src="scripts/jquery-1.10.2.js" to probably this: src="/scripts/jquery-1.10.2.js"
You can check by browsing to http://yoururl/scripts/jquery-1.10.2.js, the Jquery code should show up. If it's not there, you have to make sure that you include the right folder/file.
Yes.You will be able to push your scripts in 2 ways::
1-push your scripts in tag like>>
<script>$(document).ready(function(){alert("Welcome Dear");});</script>
2-push your inline scripts with attributes like>>
<button type='button' onclick="$(this).hide()">Hide Me</button>
make sure that the scripts folder contain test.js make sure that the extension is correct ..sometimes I make the same same mistake, instead of test.js i save it as test.js.txt
Try putting
<script type="text/javascript" src="scripts/jquery-1.10.2.js"></script>
in the body rather than the head.
Credits to this answer for giving the idea
I'm very new to JavaScript (just started a few hours ago and trying to get a script working). I went through a few tutorials on W3 and the 'hello world' code works when I paste it directly into my HTML but I'm having a problem with a script (I've had problems with other scripts as well but I am not sure what I'm doing wrong).
I have this code that I want to test in my HTML, I copied the HTML in and it looks the same then I made a file in my static folder called edit.js and copied the JavaScript into it (exactly as shown). It didn't work no errors on the page but when I click it nothing happens. I tried to paste a W3 'hello world' code in and that worked but this script does not.
I tried to inspect the code in Chrome and that's where I see the above error (under the resources tab). I can open the js file using Chrome which makes me think the js file is accessible and pointing correctly but I'm not sure how to get it working. I'm using Jinja2 as my template engine to render the HTML and in my header I have:
<script language="JavaScript" type="text/javascript" src="static/edit.js"></script>
and in my main template (the one that gets rendered on all pages) I have:
<script language="JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
edit.js:
(even putting it within the script tag directly on the page I want to use it on doesn't work)
$('#editvalue').click(function(e){$('#storedvalue').hide();$('#altervalue').show();});
$('#savevalue').click(function(e){
var showNew = $('#changevalue').val();
$('#altervalue').hide();
$('#storedvalue').show();
$('#storedvalue span').text(showNew);
});
HTML:
(it's embedded in a larger page)
<head>
<script language="JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript" src="static/edit.js"></script>
</head>
... my html code..
<div id="wrapper">
<div id="container">
<div id="storedvalue"><span>Hello</span> [edit]</div>
<div id="altervalue" style="display:none;"><input type="text" name="changevalue" id="changevalue" value="Hello"> [save]</div>
</div>
</div>
I have never been able to successfully run a JavaScript that wasn't on W3 yet. I get the same problem with other scripts even though I see people online saying they work fine for them. Do I need to do anything extra to make this work?
My two questions are:
What am I doing wrong?
Because Javascript seems to just not work when there's a problem, is there a way to get errors or information on what's actually wrong?
I read Uncaught ReferenceError: $ is not defined? and have been trying to figure this out for the last hour and can't see my problem.
First you need to place the jQuery script tag first.
Second, you need to do one of the following things:
Put your code within this function:
$(document).ready(function(){/*CODE HERE*/});
Or like this:
$(function(){
/*CODE HERE*/
});
The DOM needs to be ready before you can use it. Placing your code within anonymous functions that are executed on the ready event of the DOM is how you can do this.
Edit:
$(function(){
$('#editvalue').click(function(e){$('#storedvalue').hide();$('#altervalue').show();});
$('#savevalue').click(function(e){
var showNew = $('#changevalue').val();
$('#altervalue').hide();
$('#storedvalue').show();
$('#storedvalue span').text(showNew);
});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
Script tag for jQuery should come before your custom javascript.
Follow by edit.js
<script type="text/javascript" src="static/edit.js"></script>
Try removing the language attribute..sometimes work for me. It's obsolete now .. i think
You need to include jquery before you can use it.