I'm learning JavaScript on Khan Academy and on Codecademy. I have just started learning. I really like the way that Khan teaches JS, however, I'm not finding any way of being able to apply what I am learning anywhere else except on Khan's engine. Khan is focusing on graphics and not on console based commands.
What I'm really looking for is a way that I can take what I am learning on Khan (graphics) and Codecademy (console) and 'run' these offline on my PC. So for example, that I will be able to 'run' all of these functions, etc:
confirm(), prompt(), rect(), triangle(), ellipse(), console.log(), etc., etc.
So, can anyone explain to me how to write, save and run such JavaScript programs offline on my PC?
Programming on Khan Academy uses the JavaScript language along with the library ProcessingJS.
Here is a stand-alone program example derived from Processing.js Quick Start. This performs a very simple animation.
The graphics functions will match the the documentation at khanacademy.org and also here.
To run this, you need to download the file "processing.js" from here and save the following as "hello.html" (or whatever you want to call it), then open "hello.html" with a browser.
<script src="processing.js"></script>
<script type="application/processing" data-processing-target="pjs">
void setup() {
size(200, 200);
stroke(0), strokeWeight(2);
println('hello web!');
}
void draw() {
background(100); // clear the frame
ellipse(abs(frameCount%400-200), 50, 25, 25);
}
</script>
<canvas id="pjs"> </canvas>
Alternative: Advanced JavaScript programming style
Here is a stand-alone JavaScript program example based on snippets from Processing.js Quick Start -- this draws (and animates) a small analog clock.
The available graphics functions are the same as above, but here they require the prefix processing -- the parameter to sketchProc() below. Notice, in particular, the call to processing.line().
The instructions for running this are the same as above -- just put the following .html file in a folder along with the file processing.js...
<!DOCTYPE html>
<html>
<head>
<title>Hello Web - Processing.js Test</title>
<script src="processing.js"></script>
</head>
<body>
<h1>Processing.js Test</h1>
<p>This is my first Processing.js web-based sketch:</p>
<canvas id="canvas"></canvas>
<script>
function sketchProc(processing) {
processing.draw = function() {
var centerX = processing.width / 2, centerY = processing.height / 2;
var maxArmLength = Math.min(centerX, centerY);
function drawArm(position, lengthScale, weight) {
processing.strokeWeight(weight);
processing.line(centerX, centerY,
centerX + Math.sin(position * 2 * Math.PI) * lengthScale * maxArmLength,
centerY - Math.cos(position * 2 * Math.PI) * lengthScale * maxArmLength);
}
processing.background(224);
var now = new Date();
var hoursPosition = (now.getHours() % 12 + now.getMinutes() / 60) / 12;
drawArm(hoursPosition, 0.5, 5);
var minutesPosition = (now.getMinutes() + now.getSeconds() / 60) / 60;
drawArm(minutesPosition, 0.80, 3);
var secondsPosition = now.getSeconds() / 60;
drawArm(secondsPosition, 0.90, 1);
};
}
var canvas = document.getElementById("canvas");
var processingInstance = new Processing(canvas, sketchProc);
</script>
</body>
</html>
You don't have to be online to run JavaScript. JavaScript is a client-side language, meaning it runs in your web browser. Since you're at the JavaScript stage, I'm going to assume you know at least the basics of HTML and hopefully CSS.
You can include a JavaScript file in your HTML document by placing this tag in the section.
<html>
<head>
<script src="/path/relavite/to/htmlpage/your.js"></script>
</head>
...
</html>
Then, you can either open your browser, then File > Open your html page, which now has the JavaScript linked to it, or you can right click the .html file in your file browser, and Open With > Chrome, FireFox, etc. to view the page locally.
Again, a connection to the web is not needed to run these files, since they are stored locally on your computer.
EDIT
Might as well include the file structure. It may be easier to visualize that way.
Locally on your computer, you create a folder named "myjavascripttest". Inside this folder, you create three files: index.html, style.css and script.js
The content of the HTML file is:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="/path/relavite/to/htmlpage/your.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<p>This is a paragraph</p>
</body>
</html>
The content of the CSS file is:
p {
background-color: blue;
}
The content of the JavaScript file is: (Note: this is jQuery, an extension of JavaScript)
$(document).ready(function() {
$(this).css('background-color', 'red');
});
Now, loading the HTML file in your browser will display a paragraph with a red background, though clearly the CSS says it should be blue. The JavaScript thus must be running!
The obvious solution would be to create an HTML file on disk with a tag containing the code you want to run. Open in a browser to run, refresh page to rerun.
You can also use nodejs, if you want to create command-line programs, or not use a browser.
confirm and prompt are native browser calls, but will need specific implementations in the case of nodejs. rect, triangle, and ellipse will need to be specifically implemented in both cases. console.log works natively in both nodejs and browsers.
Related
I am trying to call the Math.matrix() function, and I am quite certain I am not importing the file correctly into my javascript code. I have read through the StackOverflow question "how to include and use math.js": and given that advice, I have the following :
<HTML >
<!DOCTYPE html>
<head>
<script src=https://cdnjs.cloudflare.com/ajax/libs/mathjs/5.1.1/math.js>
</script>
<script type="text/javascript" >
function rotate_clockwise(){
/* code skipped */
matrix = Math.matrix(matrix, rotationmatrix);
}
</script>
</head>
<body>
</body>
</HTML>
where the cdns reference I have taken from this link
But on run when rotate_clockwise is called via slider the chrome 68 debugger states Uncaught type error : Math.matrix is not a function, so I do believe I am not including this file correctly.
My base assumption is that including a file once, in one set of script tags, is enough for any javascript function to use this library, which resides within a different set of script tags.
Thanks so much for any assistance you can provide.
I think you need math.matrix(...)--lower case math since Math is a standard JS library.
I will start by saying I am far from a JavaScript guy. I work more with HTML and CSS, and "dabble" with JavaScript, as in tweak some code to make JQuery code do what I'd like it to on the front-end.
I am having a bit of an issue with a task I am trying to complete, which has led me to using NW.js (Node Webkit) for the first time.
I am trying to create a 4 button user interface that allows for the following 4 events to occur on click:
1. Load a website in a new window
2. Open windows explorer to a specific directory and allow the user to browse
3. Extend Windows Display on a Dual Monitor Setup
4. Clone Windows Display on a Dual Monitor Setup
I was originally pretty much finished and achieved my results easily with an HTML Application file - I know, outdated, but it allowed me to work within my skill set and achieve the tasks I needed fairly easily. Problem wa, it wouldn't allow for CSS3 and the website being opened used it, and it pretty much ruined the look of it as a whole. Sooo I needed something new.
I stumbled across NW.js and have started away on that. I've got my package loaded up, my "app" is now launch-able, but the old script isn't working and I am back to square one. I have no idea how to launch executables in Windows using NW.js - it's driving me bonkers!
Below is the code that worked in the HTML Application file (minus the file explorer, which I had yet to get to before realizing it wouldn't work):
<!DOCTYPE html>
<html>
<head>
<title>My HTML App</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" language="javascript">
function RunPad() {
WshShell = new ActiveXObject("WScript.Shell");
WshShell.Run("c:/windows/system32/notepad.exe", 1, false);
}
function RunExtend() {
WshShell = new ActiveXObject("WScript.Shell");
WshShell.Run("c:/windows/System32/DisplaySwitch.exe /extend", 1, false);
}
function RunClone() {
WshShell = new ActiveXObject("WScript.Shell");
WshShell.Run("c:/windows/System32/DisplaySwitch.exe /clone", 1, false);
}
function RunWebsite() {
WshShell = new ActiveXObject("WScript.Shell");
WshShell.Run("c:/Program Files/Internet Explorer/iexplore.exe", 1, false);
}
</script>
</head>
<body>
<div class="container">
<div class="col-1-2"><img src="website.jpg" onclick="RunWebsite();"></div>
<div class="col-1-2"><img src="resources.jpg"></a></div>
<div class="col-1-2"><img src="single_screen.jpg" onclick="RunExtend();"></div>
<div class="col-1-2"><img src="dual_screen.jpg" onclick="RunClone();"></div></div>
</div>
</body>
</html>
I'm really stuck on this and am not sure which route to take to complete this with NW.js
Any help would be appreciated.
ActiveXObject is for IE/Edge only so it won't work under Chromium (used by NW).
What you can do though is create individual Vbs scripts for each of your ActiveXObject functions and call/execute them as required with node.js (supported by NW) in this way...
function RunExtProgram(ProgName){
require('child_process').exec(ProgName,function(error,stdout,stderr){if(error!==null){alert('Unable to launch process:<br><br>'+stderr+'<br><br>'+ProgName);}});
}
Usage example:
RunExtProgram('C:/test/abc.vbs');
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>
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm working on creating a basic web based game using the HTML5 canvas and JavaScript. Although I have done some work with the HTML5 canvas before, it hasn't been too extensive and so it hasn't required too much JavaScript- meaning I wrote the JavaScript in script tags in my .html file.
With the file I'm currently working on, I'm now getting to the point where I need to separate the JavaScript from the HTML, since when I view the page in a browser, and click the 'start' button on the canvas, although it does perform the function it's meant to, it takes an age to do it... I assume because of the size of my .html file (most of which is JavaScript).
I have moved all of the JavaScript into separate files, with just one or two functions in each file, but I'm not sure how I then use those functions in my HTML page?
My HTML file currently looks like this:
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<section hidden>
<img id="StartButton" src="StartButton.png" alt="Start Button" width="179" height="180" href="javascript:drawLevelOneElements();"/>
</section>
<script src = "drawLevelOneElements.js" type = "text/javascript"></script>
<script src = "layers&analytics.js" type = "text/javascript"></script>
<script src = "startGameDrawGameElementsDrawStartButton.js" type = "text/javascript"></script>
<script src = "variables&preloadingImages.js" type = "text/javascript"></script>
</head>
<body onLoad="startGame()">
<h1>Home</h1>
<p1>The purpose of this website is to teach users the basic principles of running a business by playing the game below. <br /><br /></p1>
<p2>
<canvas id="gameCanvas" width="1000" height="500" style="border:1px solid">
Your browser does not support the canvas element.
</canvas>
<br /><br /></p2>
<p3>Use this paragraph to enter text that provides the user with instructions for how to play the game. <br />
Update the instructions so that they're appropriate to whatever level the user is currently playing.</p3>
</body>
The script src lines are referencing the JS files I want to use, but when I view the page in a browser, I just get a blank canvas. Could someone point out to me what I'm doing wrong here? I'm not sure how I 'attach' the JS to the HTML when writing it in a separate file.
Edit 21/11/2012 at 12:00
Having made the changes suggested, I tried viewing the page in Firefox again, and in the Firebug console, when the page loaded, it said that there was an "unterminated regular expression literal in one of my JS files. The file it was complaining about contains this JS code:
/* Create a canvas layer to display text */
function displayText(textLayer, message){
var textLayerContext = textLayer.getContext();
textLayer.clear();
textLayerContext.font = "18pt Calibri";
textLayerContext.fillStyle = "black";
textLayerContext.fillText(message, 10, 10);
}
/* Create a canvas layer to display the button */
window.onload = function(){
var stage = new Kinetic.Stage({
container: "container",
width: 179,
height: 180
});
var buttonLayer = new Kinetic.Layer();
var textLayer = new Kinetic.Layer();
}
</script>
<script type="text/javascript">
/*Google analytics code for tracking website. */
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-31216545-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
and the line it was complaining about was the </script>
It does now work, but making this change doesn't seem to have improved performance much in terms of the time it takes to load an image after clicking the start button... any suggestions?
You're doing it right as is, it could be that your scripts are so big that it takes a while before it renders. The browser interprets the HTML top to down and when it encounters a javascript file it starts rendering that.
In your case I would try to move the javascript files to the bottom of your page and try it again. Also, you have to make sure that the script files are loaded in the correct order.
Also, you should place the <section></section> inside the body and not in the <head> and the <p> should have an id="#n" and last but not least a href on your image when wanting to use a javascript is invalid, use the onClick attribute instead :)
Use the W3C validator service here to validate your HTML.
To then use the functions that you want you "simply" put them either in your onLoad() or if you're keen on using jQuery you can do
$(document).ready(function(){ //perform your functions as normal here });
Have you tried debug your application in Firebug?
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.