13 IntroJavascript PDF
13 IntroJavascript PDF
CS380
Client Side Scripting
2
CS380
Why use client-side
3
programming?
PHP already allows us to create dynamic web
pages. Why also use client-side scripting?
client-side scripting (JavaScript) benefits:
CS380
Why use client-side
4
programming?
server-side programming (PHP) benefits:
security: has access to server's private data;
client can't see source code
compatibility: not subject to browser
compatibility issues
power: can write files, open connections to
servers, connect to databases, ...
CS380
What is Javascript?
5
CS380
What is Javascript?
6
CS380
Javascript vs Java
7
+ =
CS380
JavaScript vs. PHP
9
similarities:
both are interpreted, not compiled
both are relaxed about syntax, rules, and
types
both are case-sensitive
both have built-in regular expressions for
powerful text processing
CS380
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
CS380
Linking to a JavaScript file:
11
script
<script src="filename" type="text/javascript"></script>
HTML
CS380
Event-driven programming
12
CS380
Buttons
15
function name() {
statement ;
statement ;
...
statement ;
} JS
function myFunction() {
alert("Hello!");
alert("How are you?");
} JS
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
DOM element objects
19
Accessing elements:
document.getElementById
20
function changeText() {
var span = document.getElementById("output");
var textBox = document.getElementById("textbox");
textbox.style.color = "red";
} JS
CS380
Accessing elements:
document.getElementById
21
CS380
Changing element style:
element.style
22
CS380
Preetify
23
function changeText() {
//grab or initialize text here
CS380
24 More Javascript Syntax
CS380
Variables
25
// single-line comment
/* multi-line comment */
JS
Java/JS/PHP: // comment
PHP: # comment
CS380
Math object
28
CS380
Special values: null and
29
undefined
var ned = null;
var benson = 9;
// at this point in the code,
// ned is null
// benson's 9
// caroline is undefined
JS
"5.0" == 5 is true
CS380
Boolean type
32
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)
34
while (condition) {
statements;
} JS
do {
statements;
} while (condition);
JS
CS380
Popup boxes
35
alert("message"); // message
confirm("message"); // returns true or false
prompt("message"); // returns user input string
JS
CS380
Arrays
36
CS380
Array methods
37