Javascript anatomy: Difference between revisions
No edit summary |
|||
(9 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
Javascript is used in a variety of places.<br> | |||
Here are some common entrypoints, and some sample code to get a feel for it. | |||
__TOC__ | __TOC__ | ||
Line 4: | Line 6: | ||
= NodeJS CLI = | = NodeJS CLI = | ||
<blockquote> | <blockquote> | ||
{{ expand | |||
| ${PROJECT}/main.mjs | |||
| | |||
<syntaxhighlight lang="javascript"> | |||
#!/usr/bin/env node | |||
import * as Process from 'node:process' | |||
import * as Path from 'node:path' | |||
const EXECUTABLE = Path.basename(Process.argv[1]); | |||
class CliCommand { | |||
help = false; | |||
verbose = false; | |||
static fromArgs() { | |||
var cmd = new CliCommand(); | |||
var argv = Process.argv.slice(2); | |||
while (argv.length) { | |||
var item = argv.shift(); | |||
switch (item) { | |||
case "-h": case "--help": | |||
cmd.help = true; | |||
break; | |||
case "-v": case "--verbose": | |||
cmd.verbose = true; | |||
break; | |||
default: | |||
console.error(`Invalid Param: '${item}'. See --help`); | |||
Process.exit(1); | |||
} | |||
} | |||
return cmd; | |||
} | |||
exec() { | |||
if (this.help) { | |||
showHelp(); | |||
Process.exit(0); | |||
} | |||
if (this.verbose) { | |||
console.debug("loggers set to stun"); | |||
} | |||
console.log(".. your program starts here"); | |||
} | |||
} | |||
function showHelp() { | |||
var msg = `${EXECUTABLE} [-h] [-v] | |||
ARGS: | |||
-h --help | |||
show this help message. | |||
EXAMPLE: | |||
${EXECUTABLE} -h # show help | |||
`.trim() | |||
console.log(msg); | |||
} | |||
function main() { | |||
var cmd = CliCommand.fromArgs(); | |||
cmd.exec(); | |||
} | |||
main(); | |||
</syntaxhighlight> | |||
}} | |||
<syntaxhighlight lang="bash"> | |||
./main.mjs -h # run | |||
</syntaxhighlight> | |||
</blockquote><!-- NodeJS Cli --> | </blockquote><!-- NodeJS Cli --> | ||
= Web Browser = | = Web Browser = | ||
<blockquote> | <blockquote> | ||
== Script Tags == | |||
<blockquote> | |||
One way that javascript can added to HTML within a <code><script></code> tag.<br> | |||
You can enter it directly, or set the <code>src=</code> parameter.<br> | |||
All HTML elements defined above the <code><nowiki><script</nowiki></code> is accessible within it (and not items below). | |||
<source lang="html4strict"> | |||
<script> | |||
function myFunction() { | |||
document.getElementById("demo").innerHTML = "Paragraph changed."; | |||
} | |||
</script> | |||
</source> | |||
<source lang="html4strict"> | |||
<script src="myscript.js"></script> | |||
<script src="https://foo.com/js/foo.js"></script> | |||
</source> | |||
You can use script tags anywhere, but this is discouraged in the [[Http content security policy]]. | |||
<syntaxhighlight lang="html5"> | |||
<div> | |||
<script> | |||
document.getElementById("foo").innerHTMLL = "BAR"; | |||
</script> | |||
</div> | |||
</syntaxhighlight> | |||
</blockquote><!-- Script Tags --> | |||
== ES6 Modules == | |||
<blockquote> | |||
ES6 modules let you import your code from other files (ex <code>import * as Math from './modules/math.js'</code>). | |||
Note for testing: [[javascript modules|ES6 modules]]) do not work when loading webpages directly from the filesystem.<br> | |||
You can use a tiny toy web-server like [[python http]] or [[golang simple-go-web-server]] to load your javascript instead. | You can use a tiny toy web-server like [[python http]] or [[golang simple-go-web-server]] to load your javascript instead. | ||
Line 85: | Line 200: | ||
# reload to get changes | # reload to get changes | ||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- ES6 Modules --> | |||
== On Event Hooks == | |||
<blockquote> | |||
You can register callbacks to events on matching items. | |||
<syntaxhighlight lang="javascript"> | |||
document | |||
.getElementById('button') | |||
.addEventListener('click', () => { /* do something when clicked */ }) | |||
</syntaxhighlight> | |||
You also can trigger javascript from [[Html_events |HTML DOM events]], with the <code>on${Event}</code> syntax.<br> | |||
This is now discouraged for security reasons (See [[Http content security policy]]) | |||
<syntaxhighlight lang="html5"> | |||
<button onClick="console.log('hello');">Log Hi</button> | |||
</syntaxhighlight> | |||
</blockquote><!-- On Event Hooks --> | |||
== Javascript Console == | |||
<blockquote> | |||
Most browsers have a javascript console where you can execute arbitrary javascript commands on a loaded webpage.<br> | |||
While you cannot evaluate files directly from your filesystem, but you can use a toy webserver like [[golang simple-go-web-server]]<br> | |||
to host your files, and then source them within the JS console. | |||
<syntaxhighlight lang="javascript"> | |||
// dir-with-js/foo.js | |||
console.log("HI"); | |||
</syntaxhighlight> | |||
<syntaxhighlight lang="bash"> | |||
cd dir-with-js | |||
open 'http://localhost:3000' | |||
simple-go-web-server --hot | |||
# reload to get changes | |||
</syntaxhighlight> | |||
<syntaxhighlight lang="javascript"> | |||
// javascript console | |||
$.getScript("http://127.0.0.1:3000/foo.js") | |||
</syntaxhighlight> | |||
</blockquote><!-- Loaded into Javascript Console --> | |||
</blockquote><!-- Web Browser --> | </blockquote><!-- Web Browser --> | ||
Latest revision as of 12:54, 5 February 2023
Javascript is used in a variety of places.
Here are some common entrypoints, and some sample code to get a feel for it.
NodeJS CLI
${PROJECT}/main.mjs
#!/usr/bin/env node import * as Process from 'node:process' import * as Path from 'node:path' const EXECUTABLE = Path.basename(Process.argv[1]); class CliCommand { help = false; verbose = false; static fromArgs() { var cmd = new CliCommand(); var argv = Process.argv.slice(2); while (argv.length) { var item = argv.shift(); switch (item) { case "-h": case "--help": cmd.help = true; break; case "-v": case "--verbose": cmd.verbose = true; break; default: console.error(`Invalid Param: '${item}'. See --help`); Process.exit(1); } } return cmd; } exec() { if (this.help) { showHelp(); Process.exit(0); } if (this.verbose) { console.debug("loggers set to stun"); } console.log(".. your program starts here"); } } function showHelp() { var msg = `${EXECUTABLE} [-h] [-v] ARGS: -h --help show this help message. EXAMPLE: ${EXECUTABLE} -h # show help `.trim() console.log(msg); } function main() { var cmd = CliCommand.fromArgs(); cmd.exec(); } main();./main.mjs -h # run
Web Browser
Script Tags
One way that javascript can added to HTML within a
<script>
tag.
You can enter it directly, or set thesrc=
parameter.
All HTML elements defined above the<script
is accessible within it (and not items below).<script> function myFunction() { document.getElementById("demo").innerHTML = "Paragraph changed."; } </script><script src="myscript.js"></script> <script src="https://foo.com/js/foo.js"></script>You can use script tags anywhere, but this is discouraged in the Http content security policy.
<div> <script> document.getElementById("foo").innerHTMLL = "BAR"; </script> </div>ES6 Modules
ES6 modules let you import your code from other files (ex
import * as Math from './modules/math.js'
).Note for testing: ES6 modules) do not work when loading webpages directly from the filesystem.
You can use a tiny toy web-server like python http or golang simple-go-web-server to load your javascript instead.${PROJECT}/index.html
<!doctype html public "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd"> <html lang="en"> <head> <title>My Website</title> <script type="module" src="main.js"></script> <!-- <link rel="stylesheet" href="stylesheet.css" /> --> </head> <body> <h1>My Title</h1> <p>Some paragraph</p> <div id="sum-div"> <button id="sum-btn">Add</button> <input class="addend" type="text" placeholder="1"> <input class="addend" type="text" placeholder="2"> <span>=</span> <input class="result" type="text" readonly="1"> </div> </body> </html>${PROJECT}/main.js
import * as Math from './modules/math.js' function sumClicked() { var sum_btn = document.getElementById("sum-div"); var addend_inputs = Array.from(sum_btn.querySelectorAll(".addend")); var addend_values = addend_inputs.map((input) => { return Number(input.value) }); var sum = Math.sum(...addend_values); var result_input = sum_btn.querySelector(".result"); result_input.setAttribute("value", String(sum)); } document.getElementById("sum-btn").addEventListener("click", sumClicked);${PROJECT}/modules/math.js
export function sum(a, b) { return a + b; } export function multiply(a, b) { return a * b; }
open 'http://localhost:3000' simple-go-web-server --hot # reload to get changesOn Event Hooks
You can register callbacks to events on matching items.
document .getElementById('button') .addEventListener('click', () => { /* do something when clicked */ })You also can trigger javascript from HTML DOM events, with the
on${Event}
syntax.
This is now discouraged for security reasons (See Http content security policy)<button onClick="console.log('hello');">Log Hi</button>Javascript Console
Most browsers have a javascript console where you can execute arbitrary javascript commands on a loaded webpage.
While you cannot evaluate files directly from your filesystem, but you can use a toy webserver like golang simple-go-web-server
to host your files, and then source them within the JS console.// dir-with-js/foo.js console.log("HI");cd dir-with-js open 'http://localhost:3000' simple-go-web-server --hot # reload to get changes// javascript console $.getScript("http://127.0.0.1:3000/foo.js")