Embedding JavaScript in documents
A script is embedded in HTML within a SCRIPT tag.
<SCRIPT>...</SCRIPT>
Attributes within the SCRIPT tag can be specified as follows:
<SCRIPT LANGUAGE="LiveScript">...</SCRIPT>
<SCRIPT SRC="http://myscript.ls">...</SCRIPT>
<SCRIPT LANGUAGE="language" SRC=url>...</SCRIPT>
.ls
suffix.
<!-- Begin to hide script contents from old browsers. // End the hiding here. -->
Example 1, a simple script.
<HTML> <HEAD> <SCRIPT LANGUAGE="LiveScript"> document.write("Hello net.") </SCRIPT> </HEAD> <BODY> That's all, folks. </BODY> </HTML>
Example 1 page display.
Hello net. That's all folks.
Example 2, a script with a function and comments.
<HTML> <HEAD> <SCRIPT LANGUAGE="LiveScript"> <!-- to hide script contents from old browsers function square(i) { document.write("The call passed ", i ," to the function.","<BR>") return i * i } document.write("The function returned ",square(5),".") // end hiding contents from old browsers --> </SCRIPT> </HEAD> <BODY> <BR> All done. </BODY> </HTML>
Example 2 page display.
We passed 5 to the function.
The function returned 25.
All done.
Example 3, a script with a form and an event handler attribute.
<HTML> <HEAD> <SCRIPT LANGUAGE="LiveScript"> function compute(form) { if (confirm("Are you sure?")) form.result.value = eval(form.expr.value) else alert("Please come back again.") } </SCRIPT> </HEAD> <BODY> <FORM> Enter an expression: <INPUT TYPE="text" NAME="expr" SIZE=15 > <INPUT TYPE="button" VALUE="Calculate" ONCLICK="compute(this.form)"> <BR> Result: <INPUT TYPE="text" NAME="result" SIZE=15 > <BR> </FORM> </BODY> </HTML>
Example 3 page display.
Result: 14
Example 4, a script with a form and event handler attribute within a BODY tag.
<HTML> <HEAD> <SCRIPT LANGUAGE="LiveScript"> function checkNum(str, min, max) { if (str == "") { alert("Enter a number in the field, please.") return false } for (var i = 0; i < str.length; i++) { var ch = str.substring(i, i + 1) if (ch < "0" || ch > "9") { alert("Try a number, please.") return false } } var num = 0 + str if (num < min || num > max) { alert("Try a number from 1 to 10.") return false } return true } function thanks() { alert("Thanks for your input.") } </SCRIPT> </HEAD> <BODY> <FORM> Please enter a small number: <INPUT NAME="num" ONCHANGE="if (!checkNum(this.value, 1, 10)) {this.focus();this.select();} else {thanks()}" VALUE="0"> </FORM> <SCRIPT LANGUAGE="LiveScript"> document.write("<PRE>") document.writeln("Field name: " + document.forms[0].num.name) document.writeln("Field value: " + document.forms[0].num.value) document.write("</PRE>") </SCRIPT> </BODY> </HTML>
Example 4 page display.
Please enter a small number: 7
Field name: num
Field value: 7