Javascript
Javascript
CS380
Why use client-side programming?
2
CS380
Why use client-side programming?
3
CS380
What is Javascript?
4
CS380
Linking to a JavaScript file:
5
script
<script src="filename" type="text/javascript"></script>
HTML
CS380
A JavaScript statement: alert
6
CS380
Buttons
8
CS380
Event-driven programming
9
CS380
JavaScript functions
10
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
CS380
Document Object Model (DOM)
12
function changeText() {
var span = document.getElementById("output");
var textBox = document.getElementById("textbox");
textbox.style.color = "red";
} JS
CS380
Accessing elements:
15
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
Changing element style:
16
element.style
function changeText() {
//grab or initialize text here
CS380
18 More Javascript Syntax
CS380
Variables
19
integers and real numbers are the same type (no int
vs. double)
same operators: + - * / % ++ -- = += -= *= /= %=
CS380
Comments (same as Java)
21
// single-line comment
/* multi-line comment */
JS
CS380
Math object
22
CS380
Special values: null and undefined
23
CS380
Logical operators
24
CS380
if/else statement (same as Java)
25
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
Boolean type
26
CS380
for loop (same as Java)
27
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
while loops (same as Java)
28
while (condition) {
statements;
} JS
do {
statements;
} while (condition);
JS
CS380
Popup boxes
29
alert("message"); // message
confirm("message"); // returns true or false
prompt("message"); // returns user input string
JS
CS380
Arrays
30
CS380
Array methods
31