0% found this document useful (0 votes)
5 views

Intro&Basics.pptx

Uploaded by

Abishek
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Intro&Basics.pptx

Uploaded by

Abishek
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

JavaScript

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

<script src="filename" type="text/javascript"></script>


HTML

▪ script tag should be placed in HTML page's


head
▪ script code is stored in a separate .js file
▪ JS code can be placed directly in the HTML
file's body or head (like CSS)
▪ but this is bad style (should separate content,
presentation, and behavior

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.)

▪ Manipulating web content dynamically


▪ Change the content and style of an element
▪ Replace images on a page without page reload
▪ Hide/Show contents

▪ Generate HTML contents on the fly


▪ Form validation
A Simple Script

<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>");

▪ Use the src attribute to include JavaScript codes


from an external file.
▪ The included code is inserted in place.
Hiding JavaScript from Incompatible
Browsers
<script type="text/javascript">
<!–
document.writeln("Hello, WWW");
// -->
</script>
<noscript>
Your browser does not support JavaScript.
</noscript>
alert(), confirm(), and prompt()
<script type="text/javascript">
alert("This is an Alert method");
confirm("Are you OK?");
prompt("What is your name?");
prompt("How old are you?","20");
</script>
alert() and confirm()
alert("Text to be displayed");

▪ Display a message in a dialog box.


▪ The dialog box will block the browser.

var answer = confirm("Are you sure?");


▪ Display a message in a dialog box with two buttons:
"OK" or "Cancel".
▪ confirm() returns true if the user click "OK".
Otherwise it returns false.
prompt()
prompt("What is your student id number?");
prompt("What is your name?”, "No name");

▪ Display a message and allow the user to enter a value


▪ The second argument is the "default value" to be
displayed in the input textfield.
▪ Without the default value, "undefined" is shown in the
input textfield.

▪ If the user click the "OK" button, prompt() returns the


value in the input textfield as a string.
▪ If the user click the "Cancel" button, prompt() returns
null.
Identifier
▪ Same as Java/C++ except that it allows an
additional character – '$'.

▪ 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"

{ // Introduce a block to creat a local scope


x = 0; // Same as "window.x = 0"
var y = 1;// This is a local variable y
}

alert("x=" + x + ", y=" + y); // Print x=0, y=4

</script></head>

▪ Local variable is declared using the keyword 'var'.


▪ Dynamic binding – a variable can hold any type of value
▪ If a variable is used without being declared, the variable is created
automatically.
▪ If you misspell a variable name, program will still run (but works incorrectly)
Data Types
▪ Primitive data types
▪ Number: integer & floating-point numbers
▪ Boolean: true or false
▪ String: a sequence of alphanumeric characters

▪ Composite data types (or Complex data types)


▪ Object: a named collection of data
▪ Array: a sequence of values (an array is actually a predefined
object)

▪ Special data types


▪ Null: the only value is "null" – to represent nothing.
▪ Undefined: the only value is "undefined" – to represent the value of
an unintialized variable
Strings
▪ A string variable can store a sequence of alphanumeric
characters, spaces and special characters.

▪ Each character is represented using 16 bit

▪ A string can be enclosed by a pair of single quotes (') or


double quote (").

▪ Use escaped character sequence to represent special


character (e.g.: \", \n, \t)
typeof operator
var x = "hello", y;
alert("Variable x value is " + typeof x );
alert("Variable y value is " + typeof y );
alert("Variable x value is " + typeof z );

▪ An unary operator that tells the type of its operand.


▪ Returns a string which can be "number", "string",
"boolean", "object", "function", "undefined", and "null"

▪ An array is internally represented as an object.


Object
▪ An object is a collection of properties.

▪ Properties can be variables (Fields) or Functions


(Methods)

▪ There is no "Class" in JavaScript.


Array
▪ An array is represented by the Array object. To
create an array of N elements, you can write
var myArray = new Array(N);

▪ Index of array runs from 0 to N-1.

▪ Can store values of different types

▪ Property "length" tells the # of elements in the


array.

▪ Consists of various methods to manipulate its


elements. e.g., reverse(), push(),
concat(), etc
Array Examples
var Car = new Array(3);
Car[0] = "Ford";
Car[1] = "Toyota";
Car[2] = "Honda";

// Create an array of three elements with initial


// values
var Car2 = new Array("Ford", "Toyota", "Honda");

// Create an array of three elements with initial


// values
var Car3 = ["Ford", "Toyota", "Honda"];
// An array of 3 elements, each element is undefined
var tmp1 = new Array(3);

// An array of 3 elements with initial values


var tmp2 = new Array(10, 100, -3);

// An array of 3 elements with initial values


// of different types
var tmp3 = new Array(1, "a", true);

// Makes tmp3 an array of 10 elements


tmp3.length = 10; // tmp[3] to tmp[9] are undefined.

// Makes tmp3 an array of 100 elements


tmp3[99] = "Something";
// tmp[3] to tmp[98] are undefined.
Operators
▪ Arithmetic operators
▪ +, -, *, /, %

▪ 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

// No implicit type conversion.


// True if only if both types and values are equal
var v2 = ("5" === 5);// false

var v3 = (5 === 5.0); // true

var v4 = (true == 1); // true (true is converted to 1)

var v5 = (true == 2); // false (true is converted to 1)

var v6 = (true == "1") // true


Logical Operators
▪ ! – Logical NOT

▪ && – Logical AND


▪ OP1 && OP2
▪ If OP1 is true, expression evaluates to the value of OP2.
Otherwise the expression evaluates to the value of OP1.
▪ Results may not be a boolean value.

▪ || – 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

var tmp2 = 1000 && 500; // tmp2 is 500

var tmp3 = false || 500;// tmp3 is 500

var tmp4 = "" || null; // tmp4 is null

var tmp5 = 1000 || false; // tmp5 is 1000

// If foo is null, undefined, false, zero, NaN,


// or an empty string, then set foo to 100.
foo = foo || 100;
Operators (continue)
▪ String concatenation operator
▪ +
▪ If one of the operand is a string, the other operand is
automatically converted to its equivalent string value.

▪ Assignment operators
▪ =, +=, -=, *=, /=, %=
Conditional Statements
▪ “if” statement
▪ “if … else” statement
▪ "? :" ternary conditional statement
▪ “switch” statement

▪ The syntax of these statements are similar to


those found in C and Java.
Looping Statement
▪ “for” Loops
▪ “for/in” Loops
▪ “while” Loops
▪ “do … while” Loops
▪ “break” statement
▪ “continue” statement

▪ All except "for/in" loop statements have the


same syntax as those found in C
“for/in” statement
for (var variable in object) {
statements;
}

▪ To iterate through all the properties in "object".

▪ "variable" takes the name of each property in "object"

▪ Can be used to iterate all the elements in an Array


object.
var keys = "", values = "";
var mylist = new Array("Chinese", "English", "Jap");
mylist.newField1 = "Something";

for (var key in booklist) {


keys += key + " ";
values += booklist[counter] + " ";
}

// keys becomes "0 1 2 newField1"


// values becomes "Chinese English Jap Something"
var obj = new Object(); // Creating an object

// Adding three properties to obj


obj.prop1 = 123;
obj.prop2 = "456";
obj["prop3"] = true; // same as obj.prop3 = true

var keys = "", values = "";


for (var p in obj) {
keys += p + " ";
values += obj[p] + " ";
}

alert(keys);
// Show "prop1 prop2 pro3 "

alert(values);
// Show "123 456 true "

Example: Using for … in loop with object


Functions (Return Values)
// A function can return value of any type using the
// keyword "return".

// The same function can possibly return values


// of different types
function foo (p1) {
if (typeof(p1) == "number")
return 0;// Return a number
else
if (typeof(p1) == "string")
return "zero"; // Return a string

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;
}

sum(1, 2, 3); // returns 6


sum(1, 2, 3, 4, 5); // returns 15
Creating objects using new Object()
var person = new Object();

// Assign fields to object "person"


person.firstName = "John";
person.lastName = "Doe";

// Assign a method to object "person"


person.sayHi = function() {
alert("Hi! " + this.firstName + " " + this.lastName);
}

person.sayHi(); // Call the method in "person"


Creating objects using Literal Notation
var person = {
// Declare fields
// (Note: Use comma to separate fields)
firstName : "John",
lastName : "Doe",

// Assign a method to object "person"


sayHi : function() {
alert("Hi! " + this.firstName + " " +
this.lastName);
}
}

person.sayHi(); // Call the method in "person"


Creating objects using Literal Notation
(Nested notation is possible)
var triangle = {
// Declare fields (each as an object of two fields)
p1 : { x : 0, y : 3 },
p2 : { x : 1, y : 4 },
p3 : { x : 2, y : 5 }
}

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);
}
}

var p1 = new Person("John", "Doe");


var p2 = new Person("Jane", "Dow");

p1.sayHi(); // Show "Hi! John Doe"


p2.sayHi(); // Show "Hi! Jane Dow"
Event-driven programming

◻ split breaks apart a string into an array


using a delimiter
can also be used with regular expressions
(seen later)
◻ join merges an array into a single string,
placing a delimiter between them
CS380 39
Events
▪ An event occurs as a result of some activity
▪ e.g.:
▪ A user clicks on a link in a page
▪ Page finished loaded
▪ Mouse cursor enter an area
▪ A preset amount of time elapses
▪ A form is being submitted
Event Handlers
▪ Event Handler – a segment of codes (usually a
function) to be executed when an event occurs

▪ We can specify event handlers as attributes in


the HTML tags.

▪ The attribute names typically take the form


"onXXX" where XXX is the event name.
▪ e.g.:
<a href="…" onClick="alert('Bye')">Other
Website</a>
A JavaScript statement: alert

alert("IE6 detected. Suck-mode enabled.");


JS

▪ a JS command that pops up a dialog box with a


message
CS380 42
JavaScript functions

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

<element attributes onclick="function();">...


HTML

<button onclick="myFunction();">Click me!</button>


HTML

▪ JavaScript functions can be set as event


handlers
▪ when you interact with the element, the function will
execute
▪ onclick is just one of many event HTML
attributes we'll use
▪ but popping up an alert window is disruptive and
annoying CS380 44
Document Object Model (DOM)

▪ 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

<button onclick="changeText();">Click me!</button>


<span id="output">replace me</span>
<input id="textbox" type="text" /> HTML

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

Attribute Property or style object


color color
padding padding
background-color backgroundColor
border-top-width borderTopWidth
Font size fontSize
Font famiy fontFamily
CS380 49
Preetify

function changeText() {
//grab or initialize text here

// font styles added by JS:


text.style.fontSize = "13pt";
text.style.fontFamily = "Comic Sans MS";
text.style.color = "red"; // or pink?
} JS

CS380 50
MORE JAVASCRIPT SYNTAX

51 CS380
Variables

var name = expression; JS

var clientName = "Connie Client";


var age = 32;
var weight = 127.4; JS

▪ variables are declared with the var keyword


(case sensitive)
▪ types are not specified, but JS does have types
("loosely typed")
▪ Number, Boolean, String, Array, Object,
Function, Null, Undefined
▪ can find out a variable's type by calling typeof
CS380 52
Number type

var enrollment = 99;


var medianGrade = 2.8;
var credits = 5 + 4 + (2 * 3);
JS

▪ 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

CS380 53
Comments (same as Java)

// single-line comment
/* multi-line comment */
JS

▪ identical to Java's comment syntax


▪ recall: 4 comment syntaxes
▪ HTML: <!-- comment -->
▪ CSS/JS/PHP: /* comment */
▪ Java/JS/PHP: // comment
▪ PHP: # comment

CS380 54
Math object

var rand1to10 = Math.floor(Math.random() * 10 + 1);


var three = Math.floor(Math.PI);
JS

◻ methods: abs, ceil, cos, floor, log,


max, min, pow, random, round, sin,
sqrt, tan
◻ properties: E, PI

CS380 55
Logical operators

◻ > < >= <= && || ! == != === !==


◻ most logical operators automatically
convert types:
5 < "7" is true
42 == 42.0 is true
"5.0" == 5 is true
◻ === and !== are strict equality tests; checks
both type and value
"5.0" === 5 is false
CS380 56
if/else statement (same as Java)

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 iLike190M = true;


var ieIsGood = "IE6" > 0; // false
if ("web devevelopment is great") { /* true */ }
if (0) { /* false */ }
JS

◻ any value can be used as a Boolean


"falsey" values: 0, 0.0, NaN, "", null, and
undefined
"truthy" values: anything else
◻ converting a value into a Boolean
explicitly:
var boolValue = Boolean(otherValue);
CS380 58
var boolValue = !!(otherValue);
for loop (same as Java)

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

◻ break and continue keywords also behave


as in Java

CS380 60
Popup boxes

alert("message"); // message
confirm("message"); // returns true or false
prompt("message"); // returns user input string
JS

CS380 61
Arrays

var name = []; // empty array


var name = [value, value, ..., value]; // pre-filled
name[index] = value; // store element
JS

var ducks = ["Huey", "Dewey", "Louie"];


var stooges = []; // stooges.length is 0
stooges[0] = "Larry"; // stooges.length is 1
stooges[1] = "Moe"; // stooges.length is 2
stooges[4] = "Curly"; // stooges.length is 5
stooges[4] = "Shemp"; // stooges.length is 5
JS

CS380 62
Array methods

var a = ["Stef", "Jason"]; // Stef, Jason


a.push("Brian"); // Stef, Jason, Brian
a.unshift("Kelly"); // Kelly, Stef, Jason, Brian
a.pop(); // Kelly, Stef, Jason
a.shift(); // Stef, Jason
a.sort(); // Jason, Stef
JS
◻ array serves as many data structures: list,
queue, stack, ...
◻ methods: concat, join, pop, push, reverse,
shift, slice, sort, splice, toString, unshift
push and pop add / remove from back
unshift and shift add / remove from front
shift and pop return the element that is removed 63
String type

var s = "Connie Client";


var fName = s.substring(0, s.indexOf(" ")); // "Connie"
var len = s.length; // 13
var s2 = 'Melvin Merchant';
JS
▪ methods: charAt, charCodeAt, fromCharCode,
indexOf, lastIndexOf, replace, split,
substring, toLowerCase, toUpperCase
▪ charAt returns a one-letter String (there is no char
type)
▪ length property (not a method as in Java)
▪ Strings can be specified with "" or ''
▪ concatenation with + : 64

▪ 1 + 1 is 2, but "1" + 1 is "11"


More about String

◻ escape sequences behave as in Java: \' \"


\& \n \t \\
◻ converting between numbers and Strings:
var count = 10;
var s1 = "" + count; // "10"
var s2 = count + " bananas, ah ah ah!"; // "10 bananas, ah
ah ah!"
var n1 = parseInt("42 is the answer"); // 42
var n2 = parseFloat("booyah"); // NaN JS

▪ accessing the letters of a String:


var firstLetter = s[0]; // fails in IE
var firstLetter = s.charAt(0); // does work in IE
var lastLetter = s.charAt(s.length - 1); JS
CS380 65
Splitting strings: split and join

var s = "the quick brown fox";


var a = s.split(" "); // ["the", "quick", "brown", "fox"]
a.reverse(); // ["fox", "brown", "quick", "the"]
s = a.join("!"); // "fox!brown!quick!the"
JS

◻ split breaks apart a string into an array


using a delimiter
can also be used with regular expressions
(seen later)
◻ join merges an array into a single string,
placing a delimiter between them
66
Event Handlers
Event Handlers Triggered when
onChange The value of the text field, textarea, or a drop down list
is modified
onClick A link, an image or a form element is clicked once
onDblClick The element is double-clicked
onMouseDown The user presses the mouse button
onLoad A document or an image is loaded
onSubmit A user submits a form
onReset The form is reset
onUnLoad The user closes a document or a frame
onResize A form is resized by the user

For a complete list, see http://www.w3schools.com/htmldom/dom_obj_event.asp


onClick Event Handler Example
<html>
<head>
<title>onClick Event Handler Example</title>
<script type="text/javascript">
function warnUser() {
return confirm("Are you a student?”);
}
</script>
</head>
<body>
<a href="ref.html" onClick="return warnUser()">
<!--
If onClick event handler returns false, the link
is not followed.
-->
Students access only</a>
</body>
</html>
onLoad Event Handler Example
<html><head>
<title>onLoad and onUnload Event Handler Example</title>
</head>
<body
onLoad="alert('Welcome to this page')"
onUnload="alert('Thanks for visiting this page')"
>
Load and UnLoad event test.
</body>
</html>
onMouseOver & onMouseOut Event Handler

<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>

• If onSubmit event handler returns false, data is not submitted.


• If onReset event handler returns false, form is not reset
Build-In JavaScript Objects
Object Description
Array Creates new array objects
Boolean Creates new Boolean objects
Date Retrieves and manipulates dates and times
Error Returns run-time error information
Function Creates new function objects
Math Contains methods and properties for performing mathematical
calculations
Number Contains methods and properties for manipulating numbers.
String Contains methods and properties for manipulating text strings

• See online references for complete list of available methods in these


objects: http://javascript-reference.info/
String Object (Some useful methods)
▪ length
▪A string property that tells the number of character in the string
▪ charAt(idx)
▪Returns the character at location "idx"
▪ toUpperCase(), toLowerCase()
▪Returns the same string with all uppercase/lowercase letters
▪ substring(beginIdx)
▪Returns a substring started at location "beginIdx"
▪ substring(beginIdx, endIdx)
▪Returns a substring started at "beginIdx" until "endIdx" (but
not including "endIdx"
▪ indexOf(str)
▪Returns the position where "str" first occurs in the string

You might also like