11 IntroJavascript
11 IntroJavascript
SPE 2407
SPI 2407
Client Side Scripting
2
SPI 2407
Why use client-side programming?
3
SPI 2407
Why use client-side programming?
4
SPI 2407
What is Javascript?
5
SPI 2407
What is Javascript?
6
SPI 2407
Javascript vs Java
7
+ =
SPI 2407
JavaScript vs. PHP
9
similarities:
both are interpreted, not compiled
both are relaxed about syntax, rules, and types
SPI 2407
JavaScript vs. PHP
10
differences:
JS is more object-oriented: noun.verb(), less
procedural: verb(noun)
JS focuses on user interfaces and interacting with a
document; PHP is geared toward HTML output and
file/form processing
JS code runs on the client's browser; PHP code runs
on the web server
JS <3
SPI 2407
Linking to a JavaScript file:
11
script
<script src="filename" type="text/javascript"></script>
HTML
SPI 2407
Event-driven programming
12
SPI 2407
A JavaScript statement: alert
13
SPI 2407
Buttons
15
SPI 2407
JavaScript functions
16
function name() {
statement ;
statement ;
...
statement ;
} JS
function myFunction() {
alert("Hello!");
alert("How are you?");
} JS
SPI 2407
Accessing elements:
document.getElementById
20
function changeText() {
var span = document.getElementById("output");
var textBox = document.getElementById("textbox");
textbox.style.color = "red";
} JS
SPI 2407
Accessing elements:
document.getElementById
21
SPI 2407
Changing element style:
element.style
22
function changeText() {
//grab or initialize text here
SPI 2407
24 More Javascript Syntax
SPI 2407
Variables
25
integers and real numbers are the same type (no int
vs. double)
same operators: + - * / % ++ -- = += -= *= /=
%=
similar precedence to Java
many operators auto-convert types: "2" * 3 is 6
SPI 2407
Comments (same as Java)
27
// single-line comment
/* multi-line comment */
JS
Java/JS/PHP: // comment
PHP: # comment
SPI 2407
Math object
28
SPI 2407
Special values: null and undefined
29
"5.0" == 5 is true
SPI 2407
if/else statement (same as Java)
31
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
SPI 2407
Boolean type
32
SPI 2407
for loop (same as Java)
33
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
SPI 2407
while loops (same as Java)
34
while (condition) {
statements;
} JS
do {
statements;
} while (condition);
JS
SPI 2407
Popup boxes
35
alert("message"); // message
confirm("message"); // returns true or false
prompt("message"); // returns user input string
JS
SPI 2407
Arrays
36
SPI 2407
Array methods
37
SPI 2407