Javascript - e

Download Report

Transcript Javascript - e

JAVASCRIPT
Dr Mohd Soperi Mohd Zahid
Semester 2 2015/16
Overview
• JavaScript
• jQuery
• jQuery Mobile
• AJAX
JavaScript Brief History
• Not Java programming language
• Focus on simulating and creating interactivity on the
•
•
•
•
•
WWW
From a language called LiveScript, developed by Brendan
Erich at Netscape sometime in 1995 – 1996
Not a compiled language
Browser implement JavaScript based on ECMAScript, a
language specification standard
ECMAScript first version released in 1997, latest 2009
Early JavaScript concentrated on client-side form
validation and working with images
Activity 1
• Open a web browser
• In the address bar, type
javascript:alert(“Hello World”);
Placing JavaScript in HTML
<!doctype html>
<html>
<head>
<title> … </title>
<script type=“text/javascript”>
// here
</script>
</head>
<body>
<script type=“text/javascript”>
// and, or here too!
</script>
</body>
</html>
External or
embedded scripts
• Preferred practice: JavaScript appears just before
</body> tag
How Browsers handle Scripts
• As a page loads, browsers download external scripts,
parses, and execute each script in the order in which they
appear in html document
• Blocking behavior – content appears after a script
element is downloaded or rendered only after browser
has completely processed the script element
Data types
• Numbers
• Strings
• Booleans
• Null
• Undefined
• Objects
Activity 2
<!DOCTYPE html>
<html>
<head>
<title> Hexadecimal Numbers </title>
<script type="text/javascript">
var h = 0xe;
var i = 0x2;
Integers and floating point do not
var j = h * i;
have special or separate types in
var k = 4;
JavaScript
var m = 51.50;
window.alert(j);
</script>
</head>
Variables in JavaScript is not
<body>
strongly typed
<script type="text/javascript">
window.alert(k + m);
</script>
<p> Greetings/ Assalamualaykum! </p>
<script type="text/javascript">
document.write("j + k + m = ", j, " + ", k, " + ", m, "= ", j + k + m);
</script>
</body>
</html>
Some valid strings
• “Hello world”
• “B”
• “This is ‘another string’.”
• ‘The cow says “moo”.’
• ‘Assalamualaykum dunia, damailah pada kamu semua’
• ‘Escape char needed in string\’s with single quotations’
• “\”hello\” and goodbye!”
Null, Undefined
• Null is simply nothing and represents or evaluates to false
• Different than empty
• var myvar = ‘’;
sets myvar to empty but is not null
• Undefined is used in variable that does not have a value
yet
Objects and Arrays
• JavaScript is an object-based language
• A collection of properties where each can have a value
• Each property can have a value, an object, or even a
function that returns a value
• Built-in objects are available like Date() etc. or you can
define your own objects
• Array is a collection of elements accessible by numbered
index values // create empty object
var myObj = {};
var carCatalog = {
“id”: “1”,
“model”: “Honda Freed”
};
window.alert(carCatalog.model);
var star = new Array();
star[0] = “Polaris”;
star[1] = “Deneb”;
star[2] = “Vega”;
star[3] = “Altair”;
var star = [“Polaris”, “Deneb”];
Activity 3
<!DOCTYPE html>
<html>
<head>
<title> Calculating render time </title>
<script type="text/javascript">
var started = new Date();
var now = started.getTime();
</script>
</head>
<body>
<p> <img src="helping.jpg"> </p>
<p id="dateField">&nbsp; </p>
<script type="text/javascript">
var bottom = new Date();
var diff = (bottom.getTime() - now)/1000;
var finaltime = diff.toPrecision(5);
var dateLoc = document.getElementById("dateField");
dateLoc.innerHTML = "Page rendered in " + finaltime + " seconds.";
</script>
</body>
</html>
Activity 4
Type and launch the
code in a web browser.
What output do you
get?
Change the equality
test with x === y (using
the strict test). Launch
the code in a web
browser. What output
do you get now?
<!DOCTYPE html>
<html>
<head>
<title> Javascript Operators </title>
<script type="text/javascript">
var x = Number("42");
var y = "42";
if (x == y) {
alert('x is equal to y'); // using simple test
} else {
alert("x is not equal to y");
}
</script>
</head>
<body>
</body>
</html>
Activity 5
What is the operator
name being used in
the if statement?
Explain how the
operator is used in the
if statement.
<!DOCTYPE html>
<html>
<head>
<title> Javascript Operators </title>
<script type="text/javascript">
var myObj = {
star: "Algol",
constellation: "Perseus"
};
// check a property is in an object
if ("star" in myObj) {
alert("The property called star in this object");
}
</script>
</head>
<body>
</body>
</html>
Activity 6 (The prompt() function)
Change the
program so that
message is
displayed when a
number outside
the range from 51
to 99 inclusive is
entered.
Change the
program using
NaN function and
else if to validate
that user has
entered a number.
<!DOCTYPE html>
<html>
<head>
<title> Using prompt() function </title>
<script type="text/javascript">
var inputNum = prompt("Please enter a number below 100:");
if (inputNum > 99) {
alert("That number, " + inputNum + ", is not below 100.");
} else {
alert(“Good! You entered ” + inputNum);
}
</script>
</head>
<body>
</body>
</html>
Activity 7
<!DOCTYPE html>
<html>
<head>
<title> A Basic Form </title>
<script type="text/javascript">
function alertName() {
var name = document.forms[0].nametext.value;
if (name == "Amanah") {
alert("Hello " + name + ". Welcome! Blessings for all");
}
else if (name == "DAP") {
alert("Hello DAP!");
} else {
alert("Hello " + name +"!");
}
return true;
}
</script>
</head>
<body>
<form id="myform" action="#" onsubmit="return alertName();">
<p>Username: <input id="nametext" name="username" type="text" /></p>
<p><input type="submit" /></p>
</form>
</body>
</html>
Looping through object properties
<head>
<title> Properties </title>
<script type=“text/javascript”>
var star = {};
function Star(constell, type, specclass, magnitude) { // create object
this.constellation = constell;
// adding properties
this.type = type;
this.spectralClass = specclass;
this.mag = magnitude;
this.show = function() {
// adding method
alert(“hello, an object is created as the value for a property.”); }
}
star[“Polaris”] = new Star(“Ursa Minor”, “Dauble/Cepheid”, “F7”, 2.0);
star[“Vega”] = new Star(“Lyra”, “White Dwarf”, “A0 V”, 0.03);
star[“Altair”] = new Star(“Aquila”, “White Dwarf”, “A7 V”, 0.77);
</script></head>
<body>
<script type=“text/javascript”>
for (var element in star) { star[element].show(); // call a method
for (var propt in star[element]) {
alert(element + “: “ + propt + “ = “ + star[element][propt]); }}
</script></body>
Array methods
<script type="text/javascript">
var myArray1 = new Array();
myArray1[0] = "first";
myArray1[1] = "second";
var newArray = myArray1.concat("third"); // myArray is now [first,second,third]
alert(newArray);
var myArray2 = [51,67];
newArray = newArray.concat(myArray2);
newArray.push("bye");
for (var i = 0; i < newArray.length; i++) {
alert(newArray[i]);
}
var arrayString = newArray.join("**");
alert(arrayString);
newArray.pop();
alert(newArray);
var sortednewArray = newArray.sort();
alert(newArray);
</script>
The Browser Object Model
• Browser itself is represented by one object, called the
window object, a parent of several child objects:
BOM objects
• Each object has several properties, methods, and child
objects
• Methods for Window object – alert(), prompt(), etc
• Navigator object provides several properties to detect
various elements of the browser and its environment
• Location object gives us access to information about the
currently loaded Uniform Resource Identifier (URI)
Activity 10
<!DOCTYPE html>
<head>
<title> Browser Object Model </title>
<script type="text/javascript">
if (navigator.javaEnabled()) {
alert("Java is enabled");
} else {
alert("Java is not enabled");
}
</script>
</head>
<body>
<script type="text/javascript">
var body = document.getElementsByTagName("body")[0];
for (var prop in navigator) {
var elem = document.createElement("p");
var text = document.createTextNode(prop + ": " + navigator[prop]);
elem.appendChild(text);
body.appendChild(elem);
}
</script>
</body>
</html>
JavaScript Libraries and frameworks
• Library – grouping of code that provides common or
additional functionality
• Libraries consist of files that expose objects and functions
• To use the objects and functions, developer includes or
call the library
Creating a library
• Type the following code and save in a file called library.js
var MyLibrary = {};
MyLibrary.sendAlert = function(mesg, elm) {
alert(mesg);
};
• Create an html document that use the library as follows:
<!doctype html>
<html>
<head>
<title> A Basic Example </title>
<script type=“text/javascript” src=“library.js”></script>
<head>
<body>
<script type=“text/javascript”>
MyLibrary.sendAlert(“hello, this is the message”);
</script>
</body>
</html>
Public JavaScript libraries & frameworks
• jQuery – add effects to web pages, enhance usability, and
•
•
•
•
•
make processing of data with Asynchronuous JavaScript
and XML (AJAX) easier
http://jquery.com
Modernizr – uses feature detection to determine whether
a given browser supports a certain widget or effect and
provides alternative means of accomplishing the task
http://modernizr.com
Yahoo! User Interface (YUI) – like jQuery but with
excellent documentation
http://developer.yahoo.com/yui/