Intro&Basics.pptx
Intro&Basics.pptx
The Basics
What is Javascript?
▪ a lightweight programming language ("scripting
language")
▪ used to make web pages interactive
▪ insert dynamic text into HTML (ex: user name)
▪ react to events (ex: page load user click)
▪ get information about a user's computer (ex: browser
type)
▪ perform calculations on user's computer (ex: form
validation)
CS380 2
What is Javascript?
▪ a web standard (but not supported identically by
all browsers)
▪ NOT related to Java other than by name and
some syntactic similarities
CS380 3
Linking to a JavaScript file: script
CS380 4
▪ The JavaScript supported in the browsers typically
support additional objects.
▪ e.g., Window, Frame, Form, DOM object
JavaScript / JScript
▪ Different brands or/and different versions of
browsers may support different implementation of
JavaScript.
▪ They are not fully compatible
What can we do with JavaScript?
▪ To create interactive user interface in a web
page (e.g., menu, pop-up alert, windows, etc.)
<html>
<head><title>First JavaScript Page</title></head>
<body>
<h1>First JavaScript Page</h1>
<script type="text/javascript">
document.write("<hr>");
document.write("Hello World Wide Web");
document.write("<hr>");
</script>
</body>
</html>
Embedding JavaScript
<html>
<head><title>First JavaScript Program</title></head>
<body>
<script type="text/javascript"
src="your_source_file.js"></script>
</body>
</html> Inside your_source_file.js
document.write("<hr>");
document.write("Hello World Wide Web");
document.write("<hr>");
▪ Contains only 'A' – 'Z', 'a' – 'z', '0' – '9', '_', '$'
▪ First character cannot be a digit
▪ Case-sensitive
▪ Cannot be reserved words or keywords
Variable and Variable Declaration
<head><script type="text/javascript">
// We are in the default scope – the "window" object.
x = 3; // same as "window.x = 3"
var y = 4; // same as "y = 4" or "window.y = 4"
</script></head>
▪ Post/pre increment/decrement
▪ ++, --
▪ Comparison operators
▪ ==, !=, >, >=, <, <=
▪ ===, !== (Strictly equals and strictly not equals)
▪ i.e., Type and value of operand must match / must not match
== vs ===
// Type conversion is performed before comparison
var v1 = ("5" == 5); // true
▪ || – Logical OR
▪ OP1 || OP2
▪ If OP1 is true, expression evaluates to the value of OP1.
Otherwise the expression evaluates to the value of OP2.
var tmp1 = null && 1000;// tmp1 is null
▪ Assignment operators
▪ =, +=, -=, *=, /=, %=
Conditional Statements
▪ “if” statement
▪ “if … else” statement
▪ "? :" ternary conditional statement
▪ “switch” statement
alert(keys);
// Show "prop1 prop2 pro3 "
alert(values);
// Show "123 456 true "
foo(1); // returns 0
foo("abc"); // returns "zero"
Variable Arguments
// "arguments" is a local variable (an array) available
// in every function
// You can either access the arguments through parameters
// or through the "arguments" array.
function sum ()
{
var s = 0;
for (var i = 0; i < arguments.length; i++)
s += arguments[i];
return s;
}
alert(triangle.p1.y); // Show 3
Object Constructor
function Person(fname, lname) {
// Define and initialize fields
this.firstName = fname;
this.lastName = lname;
// Define a method
this.sayHi = function() {
alert("Hi! " + this.firstName + " " +
this.lastName);
}
}
function name() {
statement ;
statement ;
...
statement ;
} JS
function myFunction() {
alert("Hello!");
alert("How are you?");
} JS
◻ the above could be the contents of
example.js linked to our HTML page
◻ statements placed into functions can be
evaluated in response to user events
CS380 43
Event handlers
▪ most JS code
manipulates elements on
an HTML page
▪ we can examine
elements' state
▪ e.g. see whether a box is
checked
▪ we can change state
▪ e.g. insert some new text
into a div
▪ we can change styles 45
DOM element objects
46
Accessing elements:
document.getElementById
var name = document.getElementById("id");
JS
function changeText() {
var span = document.getElementById("output");
var textBox = document.getElementById("textbox");
textbox.style.color = "red";
} JS
CS380 47
Accessing elements:
document.getElementById
◻ document.getElementById returns the DOM
object for an element with a given id
◻ can change the text inside most elements
by setting the innerHTML property
◻ can change the text in form controls by
setting the value property
CS380 48
Changing element style:
element.style
function changeText() {
//grab or initialize text here
CS380 50
MORE JAVASCRIPT SYNTAX
51 CS380
Variables
CS380 53
Comments (same as Java)
// single-line comment
/* multi-line comment */
JS
CS380 54
Math object
CS380 55
Logical operators
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
JS
◻ identical structure to Java's if/else
statement
◻ JavaScript allows almost anything as a
condition
CS380 57
Boolean type
var sum = 0;
for (var i = 0; i < 100; i++) {
sum = sum + i;
} JS
var s1 = "hello";
var s2 = "";
for (var i = 0; i < s.length; i++) {
s2 += s1.charAt(i) + s1.charAt(i);
}
// s2 stores "hheelllloo" JS
CS380 59
while loops (same as Java)
while (condition) {
statements;
} JS
do {
statements;
} while (condition);
JS
CS380 60
Popup boxes
alert("message"); // message
confirm("message"); // returns true or false
prompt("message"); // returns user input string
JS
CS380 61
Arrays
CS380 62
Array methods
<html>
<head>
<title>onMouseOver / onMouseOut Event Handler Demo</title>
</head>
<body>
<a href="http://www.cuhk.edu.hk"
onMouseOver="window.status='CUHK Home'; return true;"
onMouseOut="status=''"
>CUHK</a>
</body>
</html>
• When the mouse cursor is over the link, the browser displays the text
"CUHK Home" instead of the URL.
• The "return true;" of onMouseOver forces browser not to display the URL.
• window.status and window.defaultStatus are disabled in Firefox.
onSubmit Event Handler Example
<html><head>
<title>onSubmit Event Handler Example</title>
<script type="text/javascript">
function validate() {
// If everything is ok, return true
// Otherwise return false
}
</script>
</head>
<body>
<form action="MessageBoard" method="POST"
onSubmit="return validate();"
>
…
</form></body></html>