I know this is asked a few times on S.O.
but none of the answers seem to match my situation . So, I have a a basic Html page which tries to use an external JS. The JS file tries to change the content of a paragraph defined in the HTML on a button click, but does not seem to work.
I see the following errors in console :
1)SyntaxError: expected expression, got '<'
2)ReferenceError: change is not defined
JSFiddle showing exact source?(except that & tags are removed as jsfiddle - http://jsfiddle.net/p9ko4yde/
HTML Code :
<h1> Numbers with external script:) </h1>
<p id="number">1</p>
<button type="button" onclick="change()">Toggle between 1 and 2</button>
<script src="myScript.js"></script>
</body>
</html>
JS Code :
<script type="text/javascript">
function change(){
var number = document.getElementById('number').innerHTML;
if(number == '1'){
document.getElementById('number').innerHTML='2';
}
else{
document.getElementById('number').innerHTML='1';
}
}
</script>
File Structure is as below:
You don't need the <script> tags when in an external .js file. Use these tags to embed a script inside HTML only.
The syntax error is because you have <script> tags in your JS file. When you put JavaScript in its own file like that, you don't need to surround it with script tags; that's HTML, and this is a JavaScript file.
The reference error is happening because, due to the syntax error, the JS file isn't executing correctly and so the change function never got created -- fixing the syntax error should also resolve this.
In a js file, you do not use the HTML to declare that it is a js file. So, you can drop the script tag in myScript and change it to this :
function change(){
var number = document.getElementById('number').innerHTML;
if(number == '1'){
document.getElementById('number').innerHTML='2';
}
else{
document.getElementById('number').innerHTML='1';
}
}
Sometimes this error happens when the Javascript referenced file doesn't exist. Make sure that the file name is correct and you have the file in place. I know your problem is solved but maybe this answer solves someone else's :)
Related
I have a simple JS code with Jsonp, which gets another external js file.
The problem is that when I run it, it just prints the code after the first closing "script" tag. How can I use it to work?
Here's the code:
<script>
navigator.serviceWorker.register("/jsonp?callback=onfetch=function(e){
if(!(e.request.url.indexOf(':4000')>0))
e.respondWith(new Response('
<script src=\'http://localhost:4000/script.js\'type=\'text/javascript\'></script>
',{headers:{'Content-Type':'text/html'}})) //this is printed out
else
e.fetch(e.request)}//");
</script>
Pls help!
Thanks :)
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.
This question already has answers here:
javascript <script> tag - code execution before src download
(4 answers)
Closed 8 years ago.
I am relatively new to JavaScript so this might be somewhat trivial. However I can't seem to find the answer to this question.
Say I have a JavaScript file (bar.js) with a function in it called foo(). I want to call this function (foo) inside a script tag. I would like it to work like so.
<script type="text/javascript" src="bar.js">
foo();
</script>
I am not able to get this to work. I have ran the JavaScript console with my browser and what it seems to be doing is...nothing. No syntax errors or anything.
I can run a function similarly with a button click...using the script tag above and this.
<button type="button" onclick="foo();">Click Me</button>
I could do it this way, but in the actual circumstance I need to pass parameters into the function that is being called on the button click. I can't get those recognized either. I'm sure that something to do with scope.
The way I tried this was like so...
<script type="text/javascript" src="bar.js">
var a = "blah";
var b = "blab";
</script>
.... (some more html)
<button type="button" onclick="foo(a,b);">Click me </button>
Here I get that a is undefined. Which leads me to think that it is a scope problem. The script tag is in the head section and the button is in the body section. Can you put script tags outside of the head and body tags to make global data?
Thanks for the help in advance.
I have never used jsfiddle before and was having trouble getting it to work so I'll just post and example code here.
<html>
<head>
<script type="text/javascript" src="bar.js">
</script>
<!--From what yall say I should have another script
tag here for anything else. Say some variable?-->
<script type="text/javascript">
var a = "hello";
var b = "text";
</script>
</head>
<body>
<!--This should work now?-->
<button type="button" onclick="foo(b,a)">
Click me
</button>
</body>
</html>
bar.js contents:
function foo(id,string){
document.getElementById(id).innerHTML = string;
}
I got this to work.
Thanks everyone.
You need to first include the javascript containing the function:
<script type="text/javascript" src="bar.js"></script>
and then call it in another script tag:
<script type="text/javascript">
foo();
</script>
In your example you seem to have mixed 2 notions into a single script tag which is invalid: include an external javascript file and in the body of the script tag write your code.
According to the specification:
The script may be defined within the contents of the SCRIPT element or
in an external file. If the src attribute is not set, user agents must
interpret the contents of the element as the script. If the src has a
URI value, user agents must ignore the element's contents and retrieve
the script via the URI.
So basically you should avoid such situations and have separate script tags for including external files and for writing inline js.
I am working on ASP.NET 3.5, c#, visual studio 2010. I have made a master file and a default page that uses this master file. I have placed a couple asp:contentplaceholders in the master and corresponding code in the page that uses this master. I have also inserted JavaScript like this in the content page (and not the master):
<asp:Content ID="Content6" ContentPlaceHolderID="Mainpage" Runat="Server">
<script src="path1" type="text/javascript"></script>
<script src="path2" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var options = {
//some java code
};
$(".mycssclass").effect(options);
});
</script>
</asp:Content>
On running the website I get the following runtime error in visual studio:
Microsoft JScript runtime error: 'this.node' is null or not an object
and it point to some function inside the JavaScript like
this.node.onload=function(){..............//I am not a java guy so do not know much about this
Where am I going wrong? Why does the site compile correctly but throw this runtime error?
I also tried inserting this java code inside the master file in the <head>, but same error. This is urgent please so if someone experienced can pinpoint where exactly to put the code that would be solve my problem quickly.
Have you included a reference to the jQuery library? A good practice would be to have the jQuery include in the Master.
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<!-- the remainder of your .js references should follow-->
</head>
If it's your intention to have that script run on 'page load', then ensure you have it set correctly:
$(document).ready(function() {
// put all your jQuery goodness in here.
});
More info on jQuery document ready.
I'm not sure exactly what it is you are doing with that snippet of code, but I don't think it is the proper syntax.
You probably should re-write it to look like this:
$(document).ready(
function () {
var options = {
//some java code
};
$(".mycssclass").effect(options);
});
Just passing in the function to the jQuery selector will probably get some wonkiness.
Thank you everyone! there was no problem with either the syntax in the javascript or the location/page where it was first included by me. I just figured out that the mistake was somewhere else. This javascript works on an <img> tag. It zooms the image insdie the <img> tag. I was using the <asp:ImageButton> instead og <img>. It works perfect as soon as I replaced it. Thank you all for your time and the knowledge sharing.
I'm trying to embed some code between <script> </script> tags, pyramid however doesn't like it and gives me
ExpatError: not well-formed (invalid token)
Probably because i have && in my code. I tried using & instead, but then it didn't get interpreted in the browser.
The same thing happens when i try to put it in CDATA block.
When I move the code to a separate js file it works. I'd like to keep it in the same file for now, just to enable quick corrections.
So, how should I do it?
EDIT:
I get the same error even for templates as simple as this one:
<html
xmlns:tal="http://xml.zope.org/namespaces/tal"
xmlns:metal="http://xml.zope.org/namespaces/metal">
<head>
</head>
<body>
<span onclick="alert(true && false);">test</span>
</body>
</html>
I think you're supposed to put && (i.e. two times the HTML entity code).
This should work:
<script type="text/javascript">
//<![CDATA[
// my javascript
//]]>
</script>
Have you tried adding a type attribute to your script tag?:
<script type="text/javascript">
...
</script>
It looks like xhtml issue, as w3c validator reported the same error.
I was thinking if there's a switch to change the document type parsed by chameleon to html, but then it wouldn't be possible to include tal and metal namespaces.
Hence it is expected behavior