I'm trying to make a simple webpage with javascript. The html works fine, but I can't get the javascript to run. I wanted to know if anyone could give me an idea what was wrong with it?
The html and javascript file and are both in the same folder and I made sure I didn't do anything careless
Here's the code:
var intOne;
var intTwo;
var sec;
window.alert("Testing")
function checkAnswer()
{
if(quiz.outer.answerbox.value === intOne+intTwo)
{
alert("You smart. You loyal.");
alert("Answer is " + parseInt(intOne+intTwo));
} else {
alert("Another One.");
quiz.outer.answerbox.value="";
}
}
function displayQuestion()
{
intOne = Math.floor((Math.random() * 100) + 1);
intTwo = Math.floor((Math.random() * 100) + 1);
document.getElementById('quiz.outer.question').innerText= "What is " + intOne + " + " + intTwo + "?";
quiz.answerbox.value="";
startTimer();
}
function startTimer()
{
sec = 0;
window.setInterval(updateTime(), 1000);
}
function updateTime()
{
sec++
timer.innerText=sec;
}
<!Doctype html>
<html>
<head>
<title>Adding Quiz</title>
<script type="text/javascript" src="addingNumbers"></script>
</head>
<body onload="displayQuestion()">
<h1>Adding Quiz<h1>
<div style="color:blue">
<form name="quiz" action="#">
<p id="outer">
<p id="question">something</p>
<input type="output" id="answerbox" value=""><br>
<input type="button" value="Check" onClick="checkAnswer()">
</p>
</div>
<br>
<p>Time spent on this question so far: <strong id="timer">0</strong> seconds </p>
</body>
</html>
Oddly enough, the javascript appeared to work when i was posting the snippet, as I received an alert when I ran the code.
Other possible answer if it's is a correct path but won't load anyway could be
That you have something blocking javascript file from loading like NoScript, adblock or that you have blocked scripts from loading in your browsers preference/settings
Your resources could have been cached by the browser/server and any attempt at changing the code don't make any different until you clear the browsers cache
Script won't execute the code if the server adds content-type: text/plain header to the script file that are beeing requested. Even if you try to add type="text/javascript".
The page you loaded could also have some Content Security Policy (CSP) header blocking any script file from loading
If it's inside a iframe then you could have problem with the sandbox attribute
<base> tag could possible change the place it looks for loading any resources (but it looks like you don't have that problem judging by your html code)
You might even have a proxy somewhere that strips out <script> tags...
A good thumb rule is to always use lowercase letters and use - instead adding-numbers.js instead of addingNumbers.js (maybe some servers, filesystem, browser can have problem distinguish lowercase/uppercase and treat them them differently) I have had problem with that when using git...
What happens if you try to open the script url in the browser directly?
Try using absolute path if that helps...
And of course use the console/network tab to look for what the problem could be
My guess is that it's just simply not found and that the src="addingNumbers" is a wrong path
Are both the html and javascript file even in the same folder?
You have a bug in your code, but this would not keep it from running.
You are calling the method updateTime and assigning what it returns to the Interval
window.setInterval(updateTime(), 1000);
You need to drop the ()
window.setInterval(updateTime, 1000);
Side note, intervals are not accurate for keeping time. If you're wondering why using setInterval() is not accurate, please read this answer.
Now you need to figure out why the file is not loading. To do that you need to look at the console and the network tab. The console will show any JavaScript errors and the network tab will show if any files did not load (404 not found). As others have pointed out, you are not including a file extension in the script tag.
<script type="text/javascript" src="addingNumbers.js"></script>
Related
I am trying to load an external HTML page (common navigation) into my current HTML page. I tried the load function but it is deprecated. Can you tell me another way to include it? I am not using any server.
Here's my code
<!DOCTYPE html>
<html>
<head>
<script src="ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#content').load(" nav.html ");
});
</script>
</head>
<body>
<div id="content "></div>
</body>
</html>
Try this
<script>
function loadPage(href) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", href, false);
xmlhttp.send();
return xmlhttp.responseText;
};
document.getElementById('content').innerHTML =
loadPage('your_html_file.html');
</script>
<div id="content">
</div>
Take both file pages in same directory then you can use simple button on link to use external file. for example
<button> External file </button>
Button is your choice it's just example for understanding you can simple use html link.
You should use the SSI-function.
There is several ways but this can solve your problem.
<!--#include virtual="PathToYourFile/YourFile.html" -->
This can be inserted into a <div> for further styling in CSS.
REMEMBER! Due to some limitations in html-doctypes you cannot inlude a .html-file into an .html-file. You have to use another format as .shtml where you can inlude your .html-files. You can include .html into your .shtmlfile. This was also what .shtml was originally created for.
This is because it is part of the XHTML (Dynamic XML HTML)...
To change a file
Your approach on the HTML is correct and also your JS. I include a lot of html-files containing texts there.
My approach is that when a page is loaded some text will be loaded with the <!--#include virtual="" --> inside a <div>. Below JS is used to change the content in the <div>. As Daniel Beck stated below: "...at least in Apache the server needs to be configured to check particular file extensions...".
You configure your file in your .htaccess-file. But ONLY do this if you know what you are doing.
Some (newer?) servers have a default setup of which you don't need to alter the .htaccess-file if you want to be able to include .html-files. At least you are able to include .html-files into .shtml-files.
I have included a Mimetype converter which tells the browser how it should read the file. For txt/html I have told the script that it should use the character encoding ISO-8859-1. Others as UTF-8 could also be used. This depends on your and your receivers native language.
Take into consideration to use the e.preventDefault();. With this i tells the browser NOT to see this as navigation link and will therefore only load the content in the <div>.
$(function() {
$('#ButtonsID').click(function(e) {
$('.DivClass').load('PathToFile/File.shtml');
e.preventDefault();
});
});
$.ajaxSetup({
'beforeSend': function(xhr) {
xhr.overrideMimeType('text/html; charset=ISO-8859-1');
}
});
I am trying to work on a keydown event in javascript and I am currently stuck on something that never happened to me before :
var maxL = $("#myField").attr("maxLength")
console.log("Maximum Length : " + maxL);
if (e.key.length === 1 && str.length >= parseInt(maxL)) {
console.log(">>>> in if");
console.log(">>>> e.char == \"" + e.key + "\"");
e.preventDefault();
}
When I load the page, it fails. On debug, my server console logs this error :
Error Parsing /folder/myPage.xhtml: Error Traced[line: 384] The entity name
must immediately follow the '&' in the entity reference.
where 384 is the line where the if is
I tried both conditions individually and they work just fine, which leads me to think there is something wrong with the "&&" operator.
If this is of any importance, I work on a WebSphere server in JSF with PrimeFaces and I try to run it in Chrome. The javascript is embedded inside a div in order to delete it after the page is loaded :
<div id="deleteScript">
<SCRIPT>
//my script code
$("#deleteScript").remove();
</SCRIPT>
</div>
I actually had to use the following syntax :
<div id="deleteScript">
<SCRIPT>
<!--//--><![CDATA[//><!--
//my script code
$("#deleteScript").remove();
//--><!]]>
</SCRIPT>
</div>
Which I could find on this other answer. BalusC seems to think that we should only use this solution if we work for older web browsers, but it appears that it becomes necessary when we work on older JSF servers as well.
Looks like the jsf is interpreting parts of your js as if it was xhtml.
Wrap your script (after the <script> tag) with <![CDATA[ and ]]> to make it interpret the content literally:
<script>
<![CDATA[
//your code
]]>
</script>
The <![CDATA[ ... ]]> tags are used in XML files to allow the use of characters that usually are reserved such as '&', '>' etc. You can read more on this answer and here.
This is not a problem with the browser; It looks like your server is attempting to operate on the "&&". Maybe you have to escape it in your code.
The problem comes from the fact that you have your JS written in the html script tag. What I would do if I were you is:
<div id="deleteScript">
<script src="path/to/script.js"></script>
</div>
Since the script tag is within the div with ID "deleteScript", the element will exist when the script loads and you can delete it.
I have a site that show ads.
These ads are JavaScript snippets given by the ads provider.
I'd like to know whether it's possible to automatically replace the JavaScript snippet of these ads in my page by another JavaScript snippet to show ads from other ad provider after some time user is browsing the page (say 1 minute).
I looked for a solution but I failed to find one.
So a practical example:
How to change the code below
<div id="myAd">
<div id="headbanner"><script type="text/javascript"><!--
google_ad_client = "ca-pub-2874724721134868";
/* girlsgamesalon-468x60 */
google_ad_slot = "4183777947";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>
</div>
by
<div id="myAd">
<script type="text/javascript">document.write("<scr" + "ipt type='text/javascript' src='http://advertising.youraddprovider.com/ad/getoffers/?instanceID=xx18fdbb471&" + Math.random() + "'></scri" + "pt>");</script>
</div>
after 1 minute that user is browsing the page.
Is impossible to change the javascript code. You have to haldle that with server side code, like php, c#.net, etc, etc.
Example in php:
if(someconditionismet)
{
echo "<script src='thejsfileforthiscase.js'></script>";
}
else
{
echo "<script src='theotherjsfile.js'></script>";
}
Update asked for the user:
You could use
document.write("<script src='javascriptfile.sj'></script>")
But it will delete the whole content of you page which mean that if you a html tag, document.write will delete and will write just the tags. There is a work around but as i told you, DO NOT USE IT.
And with server side, you have to learn php, or c#.net, asp.net, etc, etc. I already answered you. If you want i can give you some good toturials to start.
i am trying to dynamically include js (and css) files into a webpage like this:
index.html -> loader_a.js -> a_foo.js, a_bar.js, a_foo.css and so on.
While this works without a problem in FF (using appendChild) i cant get it to run in IE6.
I've tried various available solutions (adding to dom node, ajax call and eval and more from (http://ntt.cc/2008/02/10/4-ways-to-dynamically-load-external-javascriptwith-source.html) here and there and others like post #2013676) but it's not doing what its supposed to do.
When i check with DebugBar i see that my include files (eg a_foo.js) is actually loaded, but its content is empty - on other included files (1 Level/directly) this content is show so i assume there is the problem ...
The "error" i get is alway undefined object which is o/c b/c the function i call is not loaded properly so not much of a help. I dont get any errors on the includes.
I've validated the javascripts so those whould be ok.
Does anyone have the ultimate solution for this?
I can recreate my tests and post some code if it helps.
Thanks,
regards,
Thomas
Sample HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<HTML lang=en><HEAD><TITLE>Test</TITLE>
<script type="text/javascript" src="mmtest_files/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="mmtest_files/multiload.js"></script>
<script type="text/javascript" >
function init2() {
// using the data from the loaded js files
var a= mmf("a");
document.getElementById('status').innerHTML = "Variable set:" + a;
}
// magic...
include(['mmt.js'],init2);
</script>
<BODY >
<H2>Test me!</H2>
<SPAN id=status>status old</SPAN>
</BODY></HTML>
JS 1 is multiload from answer 1
JS2 is a test include:
function mmf(param)
{
return "Called with" + param;
}
You need to use document.write in ie, in order to load scripts in parallel.
See: Loading Scripts Without Blocking
I have such a script btw: Loading Multiple Javascript Files In Order Asynchronously
(it may need some enchancements in Chrome)
UPDATE
There is a callback function, it is optional. It can be used to couple dependent script to the files. EG:
function myjQueryCode() {
// ...
}
include(['jquery.js','jquery-ui.js'], myjQueryCode);
So that your jquery dependent code will run after the files has been loaded.
EDIT: I have discovered that this is a 405 error. So there is something going on with the webserver and handling POST methods.
I am having a strange occurrence. I have identical javascript code on both my test environment and production environment.
The test environment functions, and the production does not. Here is my identical code.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jquerytools.org/1.1.2/jquery.tools.min.js"></script>
<script type="text/javascript" src="./js/jquery.scrollTo-min.js"></script>
</head>
<body>
<div class="content" id="content">
<a id="changeText" href="test.html">Change</a>
</div>
<script>
$(document).ready(function() {
$("#changeText").live('click', function(){
var url = $(this).attr("href");
$("#content").load(url, {var1:Math.random()*99999},function(){
alert(url + " loaded");
});
$.scrollTo("0%", 400);
return false;
});
});
</script>
</body>
</html>
Both environments report that
alert(url + " loaded");
is happening. But only my test environment actually displays the change.
The production webserver has "test.html" available in the correct location.
Are you sure the scrollTo script is being included on the production server ( or am I misinterpreting what you mean by change ) ? Perhaps try a root relative path instead of './js'? I would check Firebug's script tab to ensure it is being included.
405 errors mean that the URL you're sending to isn't expecting you to send the data in that manner. For example, if you're sending a POST request to a URL that's only designed to handle a GET request, you'll get this error.
My guess is whatever server you're running on is set up to not allow POST data to be sent to a page with a .html extension, causing the error you're seeing. Try changing the extension to a .php, .aspx, etc, and see if that helps.