Lecture 4
JAVASCRIPT
Javascript
• HTML to define the content of web pages
• CSS to specify the layout of web pages
• JavaScript to specify the behavior of web pages
===========================================
• JavaScript is one of the 3 languages all web developers MUST learn.
• JavaScript is the most popular programming language in the world.
• JavaScript is the language for the web, for HTML, for servers, PCs, laptops, tablets,
cell phones, and more.
What is Javascript
• JavaScript is a Scripting Language
• A scripting language is a lightweight programming language.
• JavaScript code can be inserted into any HTML page, and it can be executed by
all types of web browsers.
• JavaScript and Java are two completely different languages, in both concept
and design.
• Java (invented by Sun) is a much more complex programming than JavaScript.
JS: Where To
• JavaScripts must be inserted between <script> and </script> tags.
• JavaScripts can be put in the <body> and in the <head> section of an HTML
page.
• The <script> and </script> tells where the JavaScript starts and ends.
• The browser will interpret the code between the <script> and </script> tags as
JavaScript.
• JavaScript is the default scripting language in all modern browsers and in
HTML5.
JS in <head>
<head>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML="My First JavaScript Function";
}
</script>
</head>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button></body>
JS in <body>
<body><h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML="My First JavaScript Function";
}
</script>
</body>
External Javascript
<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
========================================
External scripts cannot contain <script> tags.
JS Output
• JavaScript does not have any print or output functions.
• JavaScript can only be used to manipulate HTML elements.
• To access an HTML element from JavaScript, you can use the
document.getElementById(id) method. The browser will find the HTML element with
• <p id="demo">My First Paragraph</p> id="demo":
elem=document.getElementById("demo");
<script> Then it will replace the element's content
elem = document.getElementById("demo"); (innerHTML) with a new content:
elem.innerHTML = "My First JavaScript"; elem.innerHTML = "My First JavaScript".
</script>
JS: Write to HTML
• <body>
<h1>My First Web Page</h1>
<script>
document.write("<p>My First JavaScript</p>");
</script>
</body>
• Use document.write for testing only. If you execute it, on a loaded HTML document, all HTML
elements will be overwritten.
JS: Write to console
• If your browser support debugging, you can use the console.log() method to display
JavaScript values in the browser.
• Activate debugging in your browser (Chrome, IE, Firefox) with F12, and select "Console"
in the debugger menu.
• <script>
a = 5;
b = 6;
c = a + b;
console.log(c);
</script>
JS Syntax
• JavaScript is a sequence of statements that can be executed by the web browser.
• JavaScript statements are "commands" to the browser.
• The purpose of the statements is to tell the browser what to do.
• Semicolon separates JavaScript statements. It is optional though.
• Each statement is executed by the browser in the sequence they are written.
• JavaScript statements can be grouped together in blocks. Blocks start with a left
curly bracket, and end with a right curly bracket.
JS: Code Block
function myFunction()
{
document.getElementById("demo").innerHTML="Hello Dolly";
document.getElementById("myDIV").innerHTML="How are you?";
}
JS Identifiers
• All programming languages must identify keywords, variables, methods, properties, and
labels, with unique names.
• In JavaScript these unique names are called identifiers.
• A JavaScript identifier must begin with a letter, or an underscore (_), or a dollar sign
($).
• The other characters in the identifier, can be letters, digits, underscores, and dollar signs.
• Some JavaScript identifiers are reserved as keywords for JavaScript itself, and cannot
be used as identifiers in a script.
JS: Some Reserved Words
abstract else instanceof super
boolean enum int switch
break export interface synchronized
byte extends let this
case false long throw
Syntax (cont’d)
• JavaScript is case sensitive.
• JavaScript uses the Unicode character set. Unicode covers (almost) all the
characters, punctuations, and symbols in the world.
• JavaScript ignores extra spaces. You can add white space to your script to make
it more readable.
• You can break up a code line within a text string with a backslash.
document.write("Hello \
World!");
JS: Comments
• Single line
// no execution
• Multi line
/*
No execution
*/
JS Variables
• JavaScript variables are "containers" for storing information.
• Example:
var x=5;
var y=6;
var answer="He is called 'Johnny'";
var person=”Goodmorning";
var z=x+y;
• JS Variables
• Variable names must begin with a letter
• Variable names can also begin with $ and _ (but we will not use it)
• Variable names are case sensitive (y and Y are different variables)
Variables Declaration
• var carname;
• carname="Volvo";
• var carname="Volvo";
• var lastname="Doe", age=30, job="carpenter";
• var lastname="Doe",
age=30,
job="carpenter";
• <p id="demo"></p>
var carname="Volvo";
document.getElementById("demo").innerHTML=carname;
JS Data Types
• Dynamic types, Strings, Numbers, Booleans, Arrays, Objects, undefined and null
• // dynamic type
var x; // Now x is undefined
var x = 5; // Now x is a Number
var x = “John"; // Now x is a String
• var x1=34.00; var y=123e5; var x=true; var y=false;
• Undefined is the value of a variable with no value. Variables can be emptied by setting the value
to null.
cars=null;
person=null;
JS Arrays
• Array indexes are zero-based, which means the first item is [0], second is [1], and so on.
• Creating an array
var cars=new Array();
cars[0]="Saab";
cars[1]="Volvo";
cars[2]="BMW";
• Condensed array
var cars=new Array("Saab","Volvo","BMW");
• Literal array
var cars=["Saab","Volvo","BMW"];
JS Objects
• Example object person
var person={firstname:"John", lastname:"Doe", id:5566};
• Or
var person={
firstname : "John",
lastname : "Doe",
id : 5566
};
• Addressing object properties
name=person.lastname;
name=person["lastname"];
Variables as Objects
var name = new String;
var x = new Number;
var y = new Boolean;
var txt = new String("Hello World");
var person = new Object();
person.firstname = "John";
person.lastname = "Doe";
person.age = 50;
person.eyecolor = "blue";
JS Functions
• A function is a block of code that will be executed when "someone" calls
it.
myFunction(argument1,argument2)
• Syntax
function functionname()
function myFunction(var1,var2)
{ {
some code to be executed some code
} }
Functions (cont’d)
• function myFunction()
{
var x=5;
return x;
}
• var myVar=myFunction();
• document.getElementById("demo").innerHTML=myFunction();
JS Numbers(1)
• JavaScript has only one type of number.
• Numbers can be written with, or without decimals.
• JavaScript Numbers are 64-bit Floating Point
• This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the
exponent in bits 52 to 62, and the sign in bit 63.
• Precision
• Integers (numbers without a period or exponent notation) are considered accurate up to 15 digits.
• The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate
JS Numbers(2)
• Precision
var x = 0.2+0.1; // result will be 0.30000000000000004
• Octal and Hexadecimal
• JavaScript interprets numeric constants as octal if they are preceded by a zero, and
as hexadecimal if they are preceded by a zero and "x".
• var y = 0377;
var z = 0xFF;
JS Numbers(3): Infinity
• If you calculate a number outside the largest number provided by
Javascript, Javascript will return the value of Infinity or -Infinity (positive
or negative overflow).
• myNumber=2;
while (myNumber!=Infinity)
{
myNumber=myNumber*myNumber; // Calculate until Infinity
}
JS Numbers(4):Number Properties
• MAX_VALUE
• MIN_VALUE
• NEGATIVE_INFINITY
• POSITIVE_INFINITY
• NaN
• Prototype
• Constructor
• Use: isNaN(x);
JS Numbers(5):Number Methods
• toExponential()
• toFixed()
• toPrecision()
• toString()
• valueOf()
• Use: myNumber.toString(8);
Strings (1)
• JavaScript strings are used for storing and manipulating text.
• A string simply stores a series of characters like "John Doe".
• A string can be any text inside quotes. You can use single or double
quotes:
• var carname="Volvo XC60";
var carname='Volvo XC60';
• var character=carname[7]; // accessing each character using index
Strings (2): Methods
• Length: carname.length
• Finding string: str.indexOf(“stringname”) //returns -1 if not found
• Matching: str.match(“matchedstring”)
• Replacing: str.replace(“string1”,”string2”)
• Case: stringvariable.toUpperCase()
• And so forth, look for more methods
Date
• Creating a date object and initiating
• new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
• var today = new Date()
var d1 = new Date("October 13, 1975 11:13:00")
var d2 = new Date(79,5,24)
var d3 = new Date(79,5,24,11,33,0)
JS Conditions
• Conditional statements are used to perform different actions based on different
conditions.
• In JavaScript we have the following conditional statements:
• if statement - use this statement to execute some code only if a specified condition is true
• if...else statement - use this statement to execute some code if the condition is true and another
code if the condition is false
• if...else if....else statement - use this statement to select one of many blocks of code to be
executed
• switch statement - use this statement to select one of many blocks of code to be executed
If statement
• if (condition)
{
code to be executed if condition is true
}
• if (time<20)
{
x="Good day";
}
If … else
• if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
If … else if … else
• if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if neither condition1 nor condition2 is true
}
Switch statement
• switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
JS Loops
• for - loops through a block of code a number of times
• for/in - loops through the properties of an object
• while - loops through a block of code while a specified condition is true
• do/while - also loops through a block of code while a specified condition is
true
For Loop
• for (statement 1; statement 2; statement 3)
{
the code block to be executed
}
• for (var i=0; i<5; i++)
{
x=x + "The number is " + i + "<br>";
}
For/In Loop
• var txt="";
var person={fname:"John",lname:"Doe",age:25};
for (var x in person)
{
txt=txt + person[x];
}
While Loop
• while (condition)
{
code block to be executed
}
• while (i<5)
{
x=x + "The number is " + i + "<br>";
i++;
}
Do/While Loop
• do
{
code block to be executed
}
while (condition);
• do
{
x=x + "The number is " + i + "<br>";
i++;
}
while (i<5);
Break and Continue
• for (i=0;i<10;i++)
{
if (i==3)
{
break;
}
x=x + "The number is " + i + "<br>";
}
• for (i=0;i<=10;i++)
{
if (i==3) continue;
x=x + "The number is " + i + "<br>";
}
Form Validation
• Form data that typically are checked by a JavaScript could be:
• has the user left required fields empty?
• has the user entered a valid e-mail address?
• has the user entered a valid date?
• has the user entered text in a numeric field?
Forms: Required Fields
• function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
• <form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
Forms: Email Validation
• function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
Alert Box
• An alert box is often used if you want to make sure information comes
through to the user.
• When an alert box pops up, the user will have to click "OK" to proceed.
• Syntax:
window.alert("sometext");
e.g. alert("I am an alert box!");
Confirm Box
• A confirm box is often used if you want the user to verify or accept something.
• When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.
• If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.
• Syntax: window.confirm("sometext");
• Example:
• var r=confirm("Press a button");
if (r==true)
{
x="You pressed OK!";
}
else
{
x="You pressed Cancel!";
}
Prompt Box
• A prompt box is often used if you want the user to input a value before
entering a page.
• When a prompt box pops up, the user will have to click either "OK" or
"Cancel" to proceed after entering an input value.
• If the user clicks "OK" the box returns the input value. If the user clicks
"Cancel" the box returns null.
• Syntax: window.prompt("sometext","defaultText");
Prompt Box
• var person=prompt("Please enter your name","Harry Potter");
if (person!=null)
{
x="Hello " + person + "! How are you today?";
document.getElementById("demo").innerHTML=x;
}
Window History
• The window.history object contains the browsers history.
• Some methods:
• history.back() - same as clicking back in the browser
• history.forward() - same as clicking forward in the browser
• The window.history object can be written without the window prefix.
Back Button
• <html>
<head>
<script>
function goBack()
{
window.history.back()
}
</script>
</head>
<body>
<input type="button" value="Back" onclick="goBack()">
</body>
• </html>
History Forward/Next
• <html>
<head>
<script>
function goForward()
{
window.history.forward()
}
</script>
</head>
<body>
<input type="button" value="Forward" onclick="goForward()">
</body>
</html>
Navigator/Browser
• <!DOCTYPE html>
• <html>
• <body>
• <div id="example"></div>
• <script>
• txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
• txt+= "<p>Browser Name: " + navigator.appName + "</p>";
• txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
• txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
• txt+= "<p>Browser Language: " + navigator.language + "</p>";
Navigator …
• txt+= "<p>Browser Online: " + navigator.onLine + "</p>";
• txt+= "<p>Platform: " + navigator.platform + "</p>";
• txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
• txt+= "<p>User-agent language: " + navigator.systemLanguage + "</p>";
• document.getElementById("example").innerHTML=txt;
• </script>
• </body>
• </html>
Cookies
• Cookies are data, stored in small text files, on your computer.
• When a web server has sent a web page to a browser, the connection is
shut down, and the server forgets everything about the user.
• Cookies were invented to solve the problem "how to remember
information about the user":
• When a user visits a web page, his name can be stored in a cookie.
• Next time the user visits the page, the cookie "remembers" his name.
Set Cookie
• function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
Get Cookie
• function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
Check Cookie
• function checkCookie()
{
var username=getCookie("username");
if (username!="")
{
alert("Welcome again " + username);
}
else
{
username = prompt("Please enter your name:","");
if (username!="" && username!=null)
{
setCookie("username",username,365);
}
}
}
End
• Queries???