JavaScript - some thoughts & notes
No relationship to Java
(except loose one that a lot languages have by coming after C)
can go in body or head tho' there are some differences as to when they get loaded
<script> ... </script>
pull code in from another file (IN THE SAME FOLDER) with
<script src='otherJavaScriptFile.js'></script>
pull code in from another file (SOMEWHERE ON THE WEB) with
<script src='http://someserver.com/otherScriptFile.js'></script>
have DOM objects listen for the code by adding to their ... attributes
<body onload="...
javascript goes here. NO script tags! but quotes reqired
...
">
<button onclick="...
javascript goes here. NO script tags! but quotes reqired
...
">
Press Here
</button>
TIAS - BUTTONS & OBJECTS
do not require trailing SEMI-COLONS however ...
Dr Dale often will "Use them out of habit!!!"
debugging is still ugly but at least the different browsers can SEE the errors
(pp.313-315 how to "turn on" the reporting in browser you are using & experiment)
control-shift-j for Firefox
Will only show JavaScript problems. No help at all with PHP issues.
Arrays use square brackets!
topRow = ['red', 'green', 'blue' ];
middleRow = ['cat', 'rat' , 'donkey'];
bottomRow = [ 1 , 2 , 3 ];
silly = [ topRow, middleRow, bottomRow ];
operators same as for PHP except CONCATENATION which is a PLUS SIGN
Variables and Scoping
- global variables
- every part of script has access to read or change
- defined outside any function (with/without keyword var) OR
inside a function without keyword var
- local variables
- only exist for the one function where it appears
- defined INSIDE a function and WITH keyword var
- function parameters same as local EXCEPT for ARRAYS
(Ask me what "pass by reference" means...)
- var, var, var! what a mess! tias ... what will be printed?
<script>
x="oh, good grief!"; // x has global scope
var y="why is that?"; // y has global scope
z = testMyPatience(); // z has global scope
// because...all outside any fcn. period.
document.write(" x is "+x);
document.write("<br>y is "+y);
document.write("<br>z is "+z);
document.write(" <p>a is "+a);
document.write("<br>b is "+b);
document.write("<br>c is "+c);
function testMyPatience(){
a=123; // a has global scope
// because...INSIDE a fcn & NO keyword 'var'
var b=123; // local scope
// because...INSIDE a fcn & keyword 'var'
if (a == 123){
var c=723; // local scope
// because...INSIDE a fcn & keyword 'var'
}
return "whatever";
}
</script>
document.write()
Dr Dale says "DO NOT USE document.write(...);
IN FUTURE
(There will be a better way that uses .innerHTML!)
DOM,
Here's another image