SlideShare a Scribd company logo
Diploma in Web Engineering
Module V: Programming with
JavaScript
Rasan Samarasinghe
ESOFT Computer Studies (pvt) Ltd.
No 68/1, Main Street, Pallegama, Embilipitiya.
Contents
1. Introduction to JavaScript
2. What JavaScript Can Do?
3. Script tag in HTML
4. Noscript tag in HTML
5. Your First JavaScript Program
6. JavaScript Placement in HTML File
7. JavaScript Syntax
8. JavaScript Data Types
9. JavaScript Variables
10. JavaScript Identifiers
11. Arithmetic Operators
12. String Concatenation Operators
13. Assignment Operators
14. Comparison Operators
15. Logical Operators
16. Bitwise Operators
17. If Statement
18. If… Else Statement
19. If… Else if… Else Statement
20. Switch Statement
21. The ? Operator
22. While Loop
23. Do While Loop
24. For Loop
25. For…in Loop
26. break Statement
27. continue Statement
28. Arrays
29. Functions
30. JavaScript Objects
31. JavaScript Scope
32. Strings
33. Regular Expressions
34. JavaScript Numbers
35. Math Object
36. Date and Time
37. JavaScript Events
38. Dialog Boxes
39. Error Handling in JavaScript
40. JavaScript Forms Validation
41. JavaScript HTML DOM
42. JavaScript BOM
Introduction to JavaScript
• A dynamic programming
language widely used to create
interactive web pages.
• Originally developed by Brendan
Eich at Netscape Corporation.
• Open and cross platform.
What JavaScript Can Do?
• JavaScript Can Change HTML Content
• JavaScript Can Change HTML Attributes
• JavaScript Can Change HTML Styles (CSS)
• JavaScript Can Validate Data
Script tag in HTML
<script language="javascript" type="text/javascript">
JavaScript code
</script>
Noscript tag in HTML
<noscript>
If you see this message means your browser does
not support with JavaScript
</noscript>
Your First JavaScript Program
<html>
<body>
<script language="javascript“ type="text/javascript">
document.write("Hello World!");
</script>
</body>
</html>
JavaScript Placement in HTML File
• JavaScript in <head>
• JavaScript in <body>
• External JavaScript
JavaScript in <head>
<html>
<head>
<script language="javascript" type="text/javascript">
document.write("Hello World!");
</script>
</head>
<body>
</body>
</html>
JavaScript in <body>
<html>
<head>
</head>
<body>
<script language="javascript" type="text/javascript">
document.write("Hello World!");
</script>
</body>
</html>
External JavaScript
<html>
<head>
</head>
<body>
<script src="myScript.js"></script>
</body>
</html>
JavaScript Syntax
Whitespaces
JavaScript ignores spaces, tabs, and newlines that
appear between tokens in JavaScript programs.
JavaScript Syntax
Semicolons are Optional
var1 = 10
var2 = 20
But when formatted in a single line as follows, the
semicolons are required
var1 = 10; var2 = 20;
JavaScript Syntax
Case Sensitivity
JavaScript is a case-sensitive language
Identifiers Time, TIme and TIME will have different
meanings in JavaScript.
JavaScript Syntax
Comments in JavaScript
// this is a single line comment
/* this is a multiline comment */
<!-- this is also a multiline comment //-->
JavaScript Data Types
There are three primitive data types:
• Numbers
• Strings of text
• Boolean
JavaScript Variables
Variables are temporary memory locations and they
can hold values.
JavaScript Variables
var score = 234;
var city = ”Colombo”;
var validity = true;
Declaring (Creating) JavaScript Variables
var firstName;
After the declaration, the variable is empty
Assign a value to the variable, use the equal sign
firstName = “Roshan”;
You can also assign a value to the variable when you declare
it
var lastName = “Ranasinghe”;
Re-Declaring JavaScript Variables
If you re-declare a JavaScript variable, it will not
lose its value.
var firstName = “Nuwan”;
var firstName;
JavaScript Identifiers
Identifiers are unique names given for naming
variables, functions and other user defined items
• Identifiers can contain letters, digits, underscores,
and dollar signs.
• Identifiers must begin with a letter.
• Identifiers cannot begin with a number.
• Identifiers are case sensitive.
• Keywords cannot be used as Identifiers.
Keywords in JavaScript
Keywords cannot be used as variables, functions or any
object names.
Arithmetic Operators
Operator Description Example
+ Addition A + B will give 30
- Subtraction A - B will give -10
* Multiplication A * B will give 200
/ Division B / A will give 2
% Modulus B % A will give 0
++ Increment B++ gives 21
-- Decrement B-- gives 19
A = 10, B = 20
String Concatenation Operators
Operator Name Example
+ Concatenation
$str1 = "Hello"
$str2 = $txt1 + " world!"
+=
Concatenation
assignment
$str1 = "Hello"
$str1 += " world!"
Assignment Operators
Operator Example
= C = A + B will assign value of A + B into C
+= C += A is equivalent to C = C + A
-= C -= A is equivalent to C = C - A
*= C *= A is equivalent to C = C * A
/= C /= A is equivalent to C = C / A
%= C %= A is equivalent to C = C % A
Comparison Operators
Operator Name Example
== Equal (A == B) is false.
!= Not equal (A != B) is true.
> Greater than (A > B) is false.
< Less than (A < B) is true.
>= Greater than or equal (A >= B) is false.
<= Less than or equal (A <= B) is true.
A = 10, B = 20
Logical Operators
Operator Name Example
&& And (A && B) is False
|| Or (A || B) is True
! Not !(A && B) is True
A = True, B = False
Bitwise Operators
Operator Name Example
& Bitwise AND (A & B) is 2
| Bitwise OR (A | B) is 3
^ Bitwise XOR (A ^ B) is 1
~ Bitwise NOT (~B) is -4
<< Bitwise Shift Left (A << 1) is 4
>> Bitwise Shift Right (A >> 1) is 1
>>> Bitwise Shift Right with Sign (A >>> 1) is 1
A = 2, B = 3
If Statement
if(Boolean_expression){
//Statements will execute if the
Boolean expression is true
}
Boolean
Expression
Statements
True
False
If… Else Statement
if(Boolean_expression){
//Executes when the Boolean expression
is true
}else{
//Executes when the Boolean
expression is false
}
Boolean
Expression
Statements
True
False
Statements
If… Else if… Else Statement
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
}else {
//Executes when the none of the above condition is
true.
}
If… Else if… Else Statement
Boolean
expression 1
False
Statements
Boolean
expression 2
Boolean
expression 3
Statements
Statements
False
False
Statements
True
True
True
Switch Statement
switch (value){
case constant:
//statements
break;
case constant:
//statements
break;
default:
//statements
}
The ? Operator
If condition is true ? Then Value one : Otherwise Value two
var h = 10;
var x = h<12 ? "morning" : "afternoon";
While Loop
while(Boolean_expression){
//Statements
}
Boolean
Expression
Statements
True
False
Do While Loop
do{
//Statements
}while(Boolean_expression);
Boolean
Expression
Statements
True
False
For Loop
for(initialization; Boolean_expression; update){
//Statements
}
Boolean
Expression
Statements
True
False
Update
Initialization
For…in Loop
for(Variablename in Object){
//Statements
}
break Statement
Boolean
Expression
Statements
True
False
break
continue Statement
Boolean
Expression
Statements
True
False
continue
Arrays
An Array object allowing you to store multiple
values in a single location.
10 30 20 50 15 35
0 1 2 3 4 5
Size = 6
Element Index No
A single dimensional array
Creating An Array
Using keyword new
var fruits = new Array( "apple", "orange", "mango" );
var points = new Array();
Using an array literal
var fruits = ["apple", "orange", "mango"];
var points = [];
Access the Elements of an Array
Accesses the value of the first element in fruits
var name = fruits[0];
Modifies the first element in cars
fruits[0] = “Pineapple";
(You can have objects, functions and arrays in an array)
Array Properties and Methods
The length property returns the number of
elements in array
var x = fruits.length;
The sort() method sort array in alphabetical order
var y = fruits.sort();
Functions
• A function is a block of code designed to perform
a particular task.
• A function is executed when "something" invokes
it (calls it).
Function Syntax
function functionname(parameter-list) {
statements
}
Function Invocation
The code inside the function will execute when
"something" invokes (calls) the function
• When an event occurs (when a user clicks a
button)
• When it is invoked (called) from JavaScript code
• Automatically (self invoked)
Function Return
When JavaScript reaches a return statement, the
function will stop executing and the return value is
"returned" back to the "caller“
function getSum(a, b) {
return a + b;
}
var sum = getSum(100,200);
Invoking the Function Definition
function getSum(x, y, z) {
return x+y+z;
}
var def = getSum;
JavaScript Objects
An object has properties and methods.
Ex:
• A car has properties like model and color, and
methods like drive and stop.
• All cars have the same properties, but the property
values differ from car to car.
• All cars have the same methods, but the methods are
performed at different times.
Object Properties
var car = { VID:4565, model:”Toyota”, color:”white”};
var student = {
ID : 4435,
name : “Nuwan”,
city : “Kandy”
};
Accessing Object Properties
objectName.propertyName
or
objectName[“propertyName”]
car.model;
car[“model”];
Object Methods
var car = {
VID: 4565,
model : “Toyota”,
color : “Red”,
drive : function() {
document.write(“car is driving”);
}
};
Invoking an Object Method
car.drive();
Object Methods with return value
var student = {
ID: 4565,
name : “Roshan”,
city : “colombo”,
getName : function() {
return this.name;
}
};
Invoking an Object return value
var name = student.getName();
JavaScript Scope
• Global Scope
• Local Scope
Global Scope
• A variable declared outside a function, becomes
global.
• Global variables are visible to everywhere in the
program.
• If you assign a value to a variable that has not been
declared, it will automatically become a global
variable.
Local Scope
• Variables declared within a function, become local
to the function.
• They can only be accessed within the function.
• Function parameters work as local variables inside
functions.
Strings
Strings are used for storing and manipulating text.
Ex:
“Hello World!”
‘No 25, Main Street, Embilipitiya’
‘It’s Alright’
“He said “hello world!””
"i'm Rasan"
String Methods
Method Description
indexOf(str) returns the index of (the position of) the first occurrence of a specified text in a
string
lastIndexOf(str) returns the index of the last occurrence of a specified text in a string
search(str) searches a string for a specified value and returns the position of the match
slice(start, end) extracts a part of a string and returns the extracted part in a new string
substring(start, end) similar to slice(). The difference is that substring() cannot accept negative
indexes
substr(start, end) similar to slice(). The difference is that the second parameter specifies the
length of the extracted part.
replace(str, str) replaces a specified value with another value in a string
toUpperCase() string is converted to upper case
toLowerCase() string is converted to lower case
concat(str) joins two or more strings
charAt(i) returns the character at a specified index (position) in a string
split(str) string can be converted to an array
trim() Removes whitespace from both ends of a string
Regular Expressions
A regular expression is a sequence of characters
that forms a search pattern.
Syntax
/pattern/modifiers;
Example:
var patt = /hello/i
Regular Expression Modifiers
Modifier Description
i Perform case-insensitive matching
g
Perform a global match (find all matches rather than
stopping after the first match)
m Perform multiline matching
Regular Expression Patterns
Pattern Description
[abc] Find any of the characters between the brackets
[0-9] Find any of the digits between the brackets
[^abc] Find any character NOT between the brackets
(ab|xyz) Find any of the alternatives separated with |
d Find a digit
s Find a whitespace character
b Find a match at the beginning or at the end of a word
. Find a single character, except newline or line terminator
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
^n Matches any string with n at the beginning of it
n$ Matches any string with n at the end of it
JavaScript Numbers
• JavaScript Numbers are Always 64-bit Floating
Point
• JavaScript numbers can be written with, or
without decimals
Value (Fraction/Mantissa) Exponent Sign
52 bits (0 - 51) 11 bits (52 - 62) 1 bit (63)
JavaScript Numbers
var a = 34.00; // A number with decimals
var b = 34; // A number without decimals
var c = 123e5; // 12300000
var d = 123e-5; // 0.00123
var x = 0xFF; // x will be 255 (hexadecimal)
JavaScript Numbers
Infinity
Infinity (or -Infinity) is the value JavaScript will
return if you calculate a number outside the largest
possible number.
NaN - Not a Number
NaN is a JavaScript reserved word indicating that a
value is not a number.
Number Methods
Method Description
Number(arg) Returns a number, converted from its argument.
parseFloat(arg) Parses its argument and returns a floating point number
parseInt(arg) Parses its argument and returns an integer
Method Description
toString() Returns a number as a string
toExponential()
Returns a string, with a number rounded and written using exponential
notation.
toFixed(n)
Returns a string, with a number rounded and written with a specified
number of decimals.
toPrecision(n) Returns a string, with a number written with a specified length
valueOf() Returns a number as a number
Global Methods
Number Methods
Math Object
Method Description
ceil(x) Returns x, rounded upwards to the nearest integer
cos(x) Returns the cosine of x (x is in radians)
floor(x) Returns x, rounded downwards to the nearest integer
log(x) Returns the natural logarithm (base E) of x
max(x,y,z,...,n) Returns the number with the highest value
min(x,y,z,...,n) Returns the number with the lowest value
pow(x,y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Rounds x to the nearest integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle
Date and Time
The Date object lets you work with dates (years,
months, days, hours, minutes, seconds, and
milliseconds)
To display current date:
document.write(Date());
Creating Date Objects
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes,
seconds, milliseconds)
Date Get Methods
Method Description
getDate() Get the day as a number (1-31)
getDay() Get the weekday as a number (0-6)
getFullYear() Get the four digit year (yyyy)
getHours() Get the hour (0-23)
getMilliseconds() Get the milliseconds (0-999)
getMinutes() Get the minutes (0-59)
getMonth() Get the month (0-11)
getSeconds() Get the seconds (0-59)
getTime() Get the time (milliseconds since January 1, 1970)
toLocaleDateString() Returns the "date" portion of the Date as a string
toLocaleTimeString() Returns the "time" portion of the Date as a string
Date Set Methods
Method Description
setDate() Set the day as a number (1-31)
setFullYear() Set the year (optionally month and day)
setHours() Set the hour (0-23)
setMilliseconds() Set the milliseconds (0-999)
setMinutes() Set the minutes (0-59)
setMonth() Set the month (0-11)
setSeconds() Set the seconds (0-59)
setTime() Set the time (milliseconds since January 1, 1970)
JavaScript Events
• HTML events are things that happen to HTML
elements.
• When JavaScript is used in HTML pages, JavaScript
can react on these events.
HTML Events
An HTML event can be something the browser
does, or something a user does.
• An HTML web page has finished loading
• An HTML button was clicked
• An HTML input field was changed
and many more…
HTML event handler attributes
<element event=“some JavaScript”>
Single quotes also works fine
<element event=‘some JavaScript’>
Common HTML Events
Event Description
onchange
occurs when the content of a form element, the selection, or
the checked state have changed
onclick occurs when the user clicks on an element
onmouseover
occurs when the pointer is moved onto an element, or onto
one of its children
onmouseout
occurs when a user moves the mouse pointer out of an
element, or out of one of its children
onkeydown occurs when the user is pressing a key
onload occurs when an object has loaded
Dialog Boxes
• Alert Dialog Box
• Confirmation Dialog Box
• Prompt Dialog Box
Alert Dialog Box
alert("Warning Message");
Confirmation Dialog Box
var retVal = confirm("Do you want to continue ?");
Prompt Dialog Box
var retVal = prompt("Enter your name : ", "your
name here");
Error Handling in JavaScript
• onerror() Method
• try...catch...finally Statement
The onerror() Method
Whenever an exception occurs on the page the
onerror event is fired.
window.onerror = function () {
alert("An error occurred.");
}
testFunc(); //a function which not existing
The try...catch...finally Statement
You can catch runtime exceptions by try...catch...finally
Statement.
try {
alert("Value of variable a is : " + a );
}catch ( e ) {
alert("Error: " + e.description );
}finally {
alert("Finally block will always execute!" );
}
JavaScript Forms Validation
• Data validation is the process of ensuring that
computer input is clean, correct, and useful.
• HTML form validation can be done by JavaScript.
• JavaScript validation is a client side validation
which is performed by a web browser before
input is sent to the web server.
JavaScript Function
If fname is empty, this function alerts a message and
returns false, to prevent the form from being
submitted.
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
return true;
}
HTML Form
<form name="myForm" action="demo_form.php"
onsubmit="return validateForm()"
method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
Validating a ZIP Code
function validateZIP() {
if( document.myForm.Zip.value == "" ||
isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 )
{
alert( "Please provide a zip in the format #####." );
document.myForm.Zip.focus() ;
return false;
}
return true;
}
Validating an Email Field
function validateEmail()
{
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return true;
}
JavaScript HTML DOM
A. JavaScript HTML DOM
B. Finding HTML Elements
C. Changing HTML Elements
D. Adding and Deleting Elements
E. Adding Events Handlers
F. HTML DOM Level 3
JavaScript HTML DOM
With the HTML DOM (Document Object Model),
JavaScript can access and change all the elements
of an HTML document.
Finding HTML Elements
Method Description
document.getElementById() Find an element by element id
document.getElementsByTagName() Find elements by tag name
document.getElementsByClassName() Find elements by class name
Changing HTML Elements
Method Description
element.innerHTML=
Change the inner HTML of an
element
element.attribute=
Change the attribute of an HTML
element
element.setAttribute(attribute,value)
Change the attribute of an HTML
element
element.style.property= Change the style of an HTML element
Adding and Deleting Elements
Method Description
document.createElement(“elem”) Create an HTML element
parent.appendChild(obj) Add an HTML element
parent.removeChild(obj) Remove an HTML element
parent.replaceChild(ob1, ob2) Replace an HTML element (ob2 with ob1)
document.write(text) Write into the HTML output stream
Adding Events Handlers
Method Description
document.getElementById(id).onclick
=function(){code}
Adding event handler code to an
onclick event
Finding HTML Objects in HTML (DOM Level 3)
Property Description
document.anchors Returns all <a> elements that have a name attribute
document.body Returns the <body> element
document.doctype Returns the document's doctype
document.documentElement Returns the <html> element
document.domain Returns the domain name of the document server
document.forms Returns all <form> elements
document.head Returns the <head> element
document.images Returns all <img> elements
document.links
Returns all <area> and <a> elements that have a href
attribute
document.title Returns the <title> element
document.URL Returns the complete URL of the document
JavaScript BOM
A. JavaScript BOM
B. Window Object
C. Window Screen
D. Window Location
E. History
F. Window Navigator
G. Timing Events
H. Cookies
JavaScript BOM (Browser Object Model)
The Browser Object Model allows JavaScript to "talk
to" the browser.
Window Object
Property Description
window.innerHeight the inner height of the browser window
window.innerWidth the inner width of the browser window
Method Description
window.open() open a new window
window.close() close the current window
window.moveTo() move the current window
window.resizeTo() resize the current window
Window Screen
Property Description
screen.width returns the width of the visitor's screen in pixels.
screen.height returns the height of the visitor's screen in pixels.
screen.availWidth returns the width of the visitor's screen, in pixels, minus
interface features like the Windows Taskbar.
screen.availHeight returns the height of the visitor's screen, in pixels, minus
interface features like the Windows Taskbar.
screen.colorDepth returns the number of bits used to display one color.
screen.pixelDepth returns the pixel depth of the screen.
Window Location
Property Description
window.location.href returns the href (URL) of the current page
window.location.hostname returns the domain name of the web host
window.location.pathname returns the path and filename of the current
page
window.location.protocol returns the web protocol used (http:// or
https://)
Method Description
window.location.assign() loads a new document
History
Method Description
history.back() same as clicking back in the browser
history.forward() same as clicking forward in the browser
Window Navigator
Property Description
navigator.cookieEnabled returns true if cookies are enabled, otherwise false
navigator.appName return the name of the browser
navigator.appCodeName return the name of the browser
navigator.product returns the engine name of the browser
navigator.appVersion returns version information about the browser
navigator.userAgent returns version information about the browser
navigator.platform returns the browser platform (operating system)
navigator.language returns the browser's language
navigator.javaEnabled() returns true if Java is enabled
Timing Events
Method Description
window.setInterval("javascript
function", milliseconds)
executes a function, over and over
again at specified time intervals
window.clearInterval(timeoutVariable) stop further executions of the
function specified in the
setInterval() method
window.setTimeout("javascript
function", milliseconds)
executes a function, once, after
waiting a specified number of
milliseconds
window.clearTimeout(timeoutVariable) stop further executions of the
function specified in the
setTimeout() method
Cookies
Create a Cookie with JavaScript
document.cookie="username=Nuwan Perera";
document.cookie="username=Nuwan Perera;
expires=Thu, 18 Dec 2015 12:00:00 UTC"; //with an
expiry date
Cookies
Read a Cookie with JavaScript
var x = document.cookie;
document.cookie will return all cookies in one
string much like:
cookie1=value; cookie2=value; cookie3=value;
Cookies
Delete a Cookie with JavaScript
document.cookie = "username=; expires=Thu, 01
Jan 1970 00:00:00 UTC";
The End
http://twitter.com/rasansmn
Ad

More Related Content

What's hot (19)

Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
Michael Stal
 
Qcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpQcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharp
Michael Stal
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Walid Ashraf
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
Bala Narayanan
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi
 
Scala functions
Scala functionsScala functions
Scala functions
Knoldus Inc.
 
Object-Oriented Programming Using C++
Object-Oriented Programming Using C++Object-Oriented Programming Using C++
Object-Oriented Programming Using C++
Salahaddin University-Erbil
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
Rasan Samarasinghe
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
Knoldus Inc.
 
Oops presentation
Oops presentationOops presentation
Oops presentation
sushamaGavarskar1
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
Pranali Chaudhari
 
Java script
Java scriptJava script
Java script
Prarthan P
 
Java Performance MythBusters
Java Performance MythBustersJava Performance MythBusters
Java Performance MythBusters
Sebastian Zarnekow
 
Javascript
JavascriptJavascript
Javascript
Aditya Gaur
 
Javascript - Tutorial
Javascript - TutorialJavascript - Tutorial
Javascript - Tutorial
adelaticleanu
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic Javascript
Bunlong Van
 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphism
rattaj
 
Introduction to JavaScript Basics.
Introduction to JavaScript Basics.Introduction to JavaScript Basics.
Introduction to JavaScript Basics.
Hassan Ahmed Baig - Web Developer
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
RichardWarburton
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
Michael Stal
 
Qcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpQcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharp
Michael Stal
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Walid Ashraf
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
Rasan Samarasinghe
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
Knoldus Inc.
 
Javascript - Tutorial
Javascript - TutorialJavascript - Tutorial
Javascript - Tutorial
adelaticleanu
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic Javascript
Bunlong Van
 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphism
rattaj
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
RichardWarburton
 

Viewers also liked (20)

DIWE - Coding HTML for Basic Web Designing
DIWE - Coding HTML for Basic Web DesigningDIWE - Coding HTML for Basic Web Designing
DIWE - Coding HTML for Basic Web Designing
Rasan Samarasinghe
 
DIWE - Multimedia Technologies
DIWE - Multimedia TechnologiesDIWE - Multimedia Technologies
DIWE - Multimedia Technologies
Rasan Samarasinghe
 
DIWE - Fundamentals of PHP
DIWE - Fundamentals of PHPDIWE - Fundamentals of PHP
DIWE - Fundamentals of PHP
Rasan Samarasinghe
 
DIWE - File handling with PHP
DIWE - File handling with PHPDIWE - File handling with PHP
DIWE - File handling with PHP
Rasan Samarasinghe
 
DITEC - Expose yourself to Internet & E-mail (updated)
DITEC - Expose yourself to Internet & E-mail (updated)DITEC - Expose yourself to Internet & E-mail (updated)
DITEC - Expose yourself to Internet & E-mail (updated)
Rasan Samarasinghe
 
DITEC - Expose yourself to Internet & E-mail
DITEC - Expose yourself to Internet & E-mailDITEC - Expose yourself to Internet & E-mail
DITEC - Expose yourself to Internet & E-mail
Rasan Samarasinghe
 
JavaScript for Beginners
JavaScript for BeginnersJavaScript for Beginners
JavaScript for Beginners
Edward Gilligan III.
 
Powershell Certificate
Powershell CertificatePowershell Certificate
Powershell Certificate
Edward Gilligan III.
 
Java script for web developer
Java script for web developerJava script for web developer
Java script for web developer
Chalermpon Areepong
 
The JavaScript Programming Primer
The JavaScript  Programming PrimerThe JavaScript  Programming Primer
The JavaScript Programming Primer
Mike Wilcox
 
Fabrication and Performance Analysis of Downdraft Biomass Gasifier Using Suga...
Fabrication and Performance Analysis of Downdraft Biomass Gasifier Using Suga...Fabrication and Performance Analysis of Downdraft Biomass Gasifier Using Suga...
Fabrication and Performance Analysis of Downdraft Biomass Gasifier Using Suga...
IJSRD
 
JavaScript
JavaScriptJavaScript
JavaScript
tutorialsruby
 
Dom API In Java Script
Dom API In Java ScriptDom API In Java Script
Dom API In Java Script
Rajat Pandit
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
T11 Sessions
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
Mindy McAdams
 
Ahmad sameer types of computer
Ahmad sameer types of computerAhmad sameer types of computer
Ahmad sameer types of computer
Sameer Nawab
 
Paris Web - Javascript as a programming language
Paris Web - Javascript as a programming languageParis Web - Javascript as a programming language
Paris Web - Javascript as a programming language
Marco Cedaro
 
Reactive Programming with JavaScript
Reactive Programming with JavaScriptReactive Programming with JavaScript
Reactive Programming with JavaScript
Codemotion
 
Javascript Tutorial
Javascript TutorialJavascript Tutorial
Javascript Tutorial
Kang-min Liu
 
Yaazli International Hibernate Training
Yaazli International Hibernate TrainingYaazli International Hibernate Training
Yaazli International Hibernate Training
Arjun Sridhar U R
 
DIWE - Coding HTML for Basic Web Designing
DIWE - Coding HTML for Basic Web DesigningDIWE - Coding HTML for Basic Web Designing
DIWE - Coding HTML for Basic Web Designing
Rasan Samarasinghe
 
DIWE - Multimedia Technologies
DIWE - Multimedia TechnologiesDIWE - Multimedia Technologies
DIWE - Multimedia Technologies
Rasan Samarasinghe
 
DITEC - Expose yourself to Internet & E-mail (updated)
DITEC - Expose yourself to Internet & E-mail (updated)DITEC - Expose yourself to Internet & E-mail (updated)
DITEC - Expose yourself to Internet & E-mail (updated)
Rasan Samarasinghe
 
DITEC - Expose yourself to Internet & E-mail
DITEC - Expose yourself to Internet & E-mailDITEC - Expose yourself to Internet & E-mail
DITEC - Expose yourself to Internet & E-mail
Rasan Samarasinghe
 
The JavaScript Programming Primer
The JavaScript  Programming PrimerThe JavaScript  Programming Primer
The JavaScript Programming Primer
Mike Wilcox
 
Fabrication and Performance Analysis of Downdraft Biomass Gasifier Using Suga...
Fabrication and Performance Analysis of Downdraft Biomass Gasifier Using Suga...Fabrication and Performance Analysis of Downdraft Biomass Gasifier Using Suga...
Fabrication and Performance Analysis of Downdraft Biomass Gasifier Using Suga...
IJSRD
 
Dom API In Java Script
Dom API In Java ScriptDom API In Java Script
Dom API In Java Script
Rajat Pandit
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
T11 Sessions
 
Ahmad sameer types of computer
Ahmad sameer types of computerAhmad sameer types of computer
Ahmad sameer types of computer
Sameer Nawab
 
Paris Web - Javascript as a programming language
Paris Web - Javascript as a programming languageParis Web - Javascript as a programming language
Paris Web - Javascript as a programming language
Marco Cedaro
 
Reactive Programming with JavaScript
Reactive Programming with JavaScriptReactive Programming with JavaScript
Reactive Programming with JavaScript
Codemotion
 
Javascript Tutorial
Javascript TutorialJavascript Tutorial
Javascript Tutorial
Kang-min Liu
 
Yaazli International Hibernate Training
Yaazli International Hibernate TrainingYaazli International Hibernate Training
Yaazli International Hibernate Training
Arjun Sridhar U R
 
Ad

Similar to DIWE - Programming with JavaScript (20)

DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaDISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in Java
Rasan Samarasinghe
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
David Furber
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
Julie Iskander
 
DITEC - Programming with Java
DITEC - Programming with JavaDITEC - Programming with Java
DITEC - Programming with Java
Rasan Samarasinghe
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
ch samaram
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
Doug Jones
 
Journey of a C# developer into Javascript
Journey of a C# developer into JavascriptJourney of a C# developer into Javascript
Journey of a C# developer into Javascript
Massimo Franciosa
 
Introduction to java script
Introduction to java scriptIntroduction to java script
Introduction to java script
DivyaKS12
 
Javascript
JavascriptJavascript
Javascript
Gita Kriz
 
Vb script final pari
Vb script final pariVb script final pari
Vb script final pari
Kamesh Shekhar Prasad
 
Weird Javascript Weekends first session presentaion
Weird Javascript Weekends first session presentaionWeird Javascript Weekends first session presentaion
Weird Javascript Weekends first session presentaion
SrishtyMangutte
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentation
Adhoura Academy
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
shreesenthil
 
data-types-operators-datatypes-operators.ppt
data-types-operators-datatypes-operators.pptdata-types-operators-datatypes-operators.ppt
data-types-operators-datatypes-operators.ppt
Gagan Rana
 
Java script.pptx v
Java script.pptx                                     vJava script.pptx                                     v
Java script.pptx v
22x026
 
On Scala Slides - OSDC 2009
On Scala Slides - OSDC 2009On Scala Slides - OSDC 2009
On Scala Slides - OSDC 2009
Michael Neale
 
Unit 2.5
Unit 2.5Unit 2.5
Unit 2.5
Abhishek Kesharwani
 
Java Script Language Tutorial
Java Script Language TutorialJava Script Language Tutorial
Java Script Language Tutorial
vikram singh
 
JAVASCRIPT - LinkedIn
JAVASCRIPT - LinkedInJAVASCRIPT - LinkedIn
JAVASCRIPT - LinkedIn
Gino Louie Peña, ITIL®,MOS®
 
Unit 2.5
Unit 2.5Unit 2.5
Unit 2.5
Abhishek Kesharwani
 
DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaDISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in Java
Rasan Samarasinghe
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
David Furber
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
Julie Iskander
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
ch samaram
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
Doug Jones
 
Journey of a C# developer into Javascript
Journey of a C# developer into JavascriptJourney of a C# developer into Javascript
Journey of a C# developer into Javascript
Massimo Franciosa
 
Introduction to java script
Introduction to java scriptIntroduction to java script
Introduction to java script
DivyaKS12
 
Weird Javascript Weekends first session presentaion
Weird Javascript Weekends first session presentaionWeird Javascript Weekends first session presentaion
Weird Javascript Weekends first session presentaion
SrishtyMangutte
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentation
Adhoura Academy
 
data-types-operators-datatypes-operators.ppt
data-types-operators-datatypes-operators.pptdata-types-operators-datatypes-operators.ppt
data-types-operators-datatypes-operators.ppt
Gagan Rana
 
Java script.pptx v
Java script.pptx                                     vJava script.pptx                                     v
Java script.pptx v
22x026
 
On Scala Slides - OSDC 2009
On Scala Slides - OSDC 2009On Scala Slides - OSDC 2009
On Scala Slides - OSDC 2009
Michael Neale
 
Java Script Language Tutorial
Java Script Language TutorialJava Script Language Tutorial
Java Script Language Tutorial
vikram singh
 
Ad

More from Rasan Samarasinghe (20)

Managing the under performance in projects.pptx
Managing the under performance in projects.pptxManaging the under performance in projects.pptx
Managing the under performance in projects.pptx
Rasan Samarasinghe
 
Agile project management with scrum
Agile project management with scrumAgile project management with scrum
Agile project management with scrum
Rasan Samarasinghe
 
Introduction to Agile
Introduction to AgileIntroduction to Agile
Introduction to Agile
Rasan Samarasinghe
 
IT Introduction (en)
IT Introduction (en)IT Introduction (en)
IT Introduction (en)
Rasan Samarasinghe
 
Application of Unified Modelling Language
Application of Unified Modelling LanguageApplication of Unified Modelling Language
Application of Unified Modelling Language
Rasan Samarasinghe
 
Advanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST APIAdvanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST API
Rasan Samarasinghe
 
Advanced Web Development in PHP - Understanding Project Development Methodolo...
Advanced Web Development in PHP - Understanding Project Development Methodolo...Advanced Web Development in PHP - Understanding Project Development Methodolo...
Advanced Web Development in PHP - Understanding Project Development Methodolo...
Rasan Samarasinghe
 
Advanced Web Development in PHP - Code Versioning and Branching with Git
Advanced Web Development in PHP - Code Versioning and Branching with GitAdvanced Web Development in PHP - Code Versioning and Branching with Git
Advanced Web Development in PHP - Code Versioning and Branching with Git
Rasan Samarasinghe
 
DIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image ManipulationDIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image Manipulation
Rasan Samarasinghe
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
Rasan Samarasinghe
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
Rasan Samarasinghe
 
DISE - Software Testing and Quality Management
DISE - Software Testing and Quality ManagementDISE - Software Testing and Quality Management
DISE - Software Testing and Quality Management
Rasan Samarasinghe
 
DISE - Introduction to Project Management
DISE - Introduction to Project ManagementDISE - Introduction to Project Management
DISE - Introduction to Project Management
Rasan Samarasinghe
 
DISE - Database Concepts
DISE - Database ConceptsDISE - Database Concepts
DISE - Database Concepts
Rasan Samarasinghe
 
DISE - OOAD Using UML
DISE - OOAD Using UMLDISE - OOAD Using UML
DISE - OOAD Using UML
Rasan Samarasinghe
 
DISE - Programming Concepts
DISE - Programming ConceptsDISE - Programming Concepts
DISE - Programming Concepts
Rasan Samarasinghe
 
DISE - Introduction to Software Engineering
DISE - Introduction to Software EngineeringDISE - Introduction to Software Engineering
DISE - Introduction to Software Engineering
Rasan Samarasinghe
 
DITEC - Expose yourself to Internet & E-mail (second update)
DITEC - Expose yourself to Internet & E-mail (second update) DITEC - Expose yourself to Internet & E-mail (second update)
DITEC - Expose yourself to Internet & E-mail (second update)
Rasan Samarasinghe
 
DITEC - E-Commerce & ASP.NET
DITEC - E-Commerce & ASP.NETDITEC - E-Commerce & ASP.NET
DITEC - E-Commerce & ASP.NET
Rasan Samarasinghe
 
DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NET
Rasan Samarasinghe
 
Managing the under performance in projects.pptx
Managing the under performance in projects.pptxManaging the under performance in projects.pptx
Managing the under performance in projects.pptx
Rasan Samarasinghe
 
Agile project management with scrum
Agile project management with scrumAgile project management with scrum
Agile project management with scrum
Rasan Samarasinghe
 
Application of Unified Modelling Language
Application of Unified Modelling LanguageApplication of Unified Modelling Language
Application of Unified Modelling Language
Rasan Samarasinghe
 
Advanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST APIAdvanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST API
Rasan Samarasinghe
 
Advanced Web Development in PHP - Understanding Project Development Methodolo...
Advanced Web Development in PHP - Understanding Project Development Methodolo...Advanced Web Development in PHP - Understanding Project Development Methodolo...
Advanced Web Development in PHP - Understanding Project Development Methodolo...
Rasan Samarasinghe
 
Advanced Web Development in PHP - Code Versioning and Branching with Git
Advanced Web Development in PHP - Code Versioning and Branching with GitAdvanced Web Development in PHP - Code Versioning and Branching with Git
Advanced Web Development in PHP - Code Versioning and Branching with Git
Rasan Samarasinghe
 
DIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image ManipulationDIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image Manipulation
Rasan Samarasinghe
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
Rasan Samarasinghe
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
Rasan Samarasinghe
 
DISE - Software Testing and Quality Management
DISE - Software Testing and Quality ManagementDISE - Software Testing and Quality Management
DISE - Software Testing and Quality Management
Rasan Samarasinghe
 
DISE - Introduction to Project Management
DISE - Introduction to Project ManagementDISE - Introduction to Project Management
DISE - Introduction to Project Management
Rasan Samarasinghe
 
DISE - Introduction to Software Engineering
DISE - Introduction to Software EngineeringDISE - Introduction to Software Engineering
DISE - Introduction to Software Engineering
Rasan Samarasinghe
 
DITEC - Expose yourself to Internet & E-mail (second update)
DITEC - Expose yourself to Internet & E-mail (second update) DITEC - Expose yourself to Internet & E-mail (second update)
DITEC - Expose yourself to Internet & E-mail (second update)
Rasan Samarasinghe
 
DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NET
Rasan Samarasinghe
 

Recently uploaded (20)

"Heaters in Power Plants: Types, Functions, and Performance Analysis"
"Heaters in Power Plants: Types, Functions, and Performance Analysis""Heaters in Power Plants: Types, Functions, and Performance Analysis"
"Heaters in Power Plants: Types, Functions, and Performance Analysis"
Infopitaara
 
Unit III.pptx IT3401 web essentials presentatio
Unit III.pptx IT3401 web essentials presentatioUnit III.pptx IT3401 web essentials presentatio
Unit III.pptx IT3401 web essentials presentatio
lakshitakumar291
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
vlsi digital circuits full power point presentation
vlsi digital circuits full power point presentationvlsi digital circuits full power point presentation
vlsi digital circuits full power point presentation
DrSunitaPatilUgaleKK
 
How to Make Material Space Qu___ (1).pptx
How to Make Material Space Qu___ (1).pptxHow to Make Material Space Qu___ (1).pptx
How to Make Material Space Qu___ (1).pptx
engaash9
 
Lecture 13 (Air and Noise Pollution and their Control) (1).pptx
Lecture 13 (Air and Noise Pollution and their Control) (1).pptxLecture 13 (Air and Noise Pollution and their Control) (1).pptx
Lecture 13 (Air and Noise Pollution and their Control) (1).pptx
huzaifabilalshams
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
Taking AI Welfare Seriously, In this report, we argue that there is a realist...
Taking AI Welfare Seriously, In this report, we argue that there is a realist...Taking AI Welfare Seriously, In this report, we argue that there is a realist...
Taking AI Welfare Seriously, In this report, we argue that there is a realist...
MiguelMarques372250
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
BTech_CSE_LPU_Presentation.pptx.........
BTech_CSE_LPU_Presentation.pptx.........BTech_CSE_LPU_Presentation.pptx.........
BTech_CSE_LPU_Presentation.pptx.........
jinny kaur
 
"Heaters in Power Plants: Types, Functions, and Performance Analysis"
"Heaters in Power Plants: Types, Functions, and Performance Analysis""Heaters in Power Plants: Types, Functions, and Performance Analysis"
"Heaters in Power Plants: Types, Functions, and Performance Analysis"
Infopitaara
 
Unit III.pptx IT3401 web essentials presentatio
Unit III.pptx IT3401 web essentials presentatioUnit III.pptx IT3401 web essentials presentatio
Unit III.pptx IT3401 web essentials presentatio
lakshitakumar291
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
vlsi digital circuits full power point presentation
vlsi digital circuits full power point presentationvlsi digital circuits full power point presentation
vlsi digital circuits full power point presentation
DrSunitaPatilUgaleKK
 
How to Make Material Space Qu___ (1).pptx
How to Make Material Space Qu___ (1).pptxHow to Make Material Space Qu___ (1).pptx
How to Make Material Space Qu___ (1).pptx
engaash9
 
Lecture 13 (Air and Noise Pollution and their Control) (1).pptx
Lecture 13 (Air and Noise Pollution and their Control) (1).pptxLecture 13 (Air and Noise Pollution and their Control) (1).pptx
Lecture 13 (Air and Noise Pollution and their Control) (1).pptx
huzaifabilalshams
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
Taking AI Welfare Seriously, In this report, we argue that there is a realist...
Taking AI Welfare Seriously, In this report, we argue that there is a realist...Taking AI Welfare Seriously, In this report, we argue that there is a realist...
Taking AI Welfare Seriously, In this report, we argue that there is a realist...
MiguelMarques372250
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
BTech_CSE_LPU_Presentation.pptx.........
BTech_CSE_LPU_Presentation.pptx.........BTech_CSE_LPU_Presentation.pptx.........
BTech_CSE_LPU_Presentation.pptx.........
jinny kaur
 

DIWE - Programming with JavaScript

  • 1. Diploma in Web Engineering Module V: Programming with JavaScript Rasan Samarasinghe ESOFT Computer Studies (pvt) Ltd. No 68/1, Main Street, Pallegama, Embilipitiya.
  • 2. Contents 1. Introduction to JavaScript 2. What JavaScript Can Do? 3. Script tag in HTML 4. Noscript tag in HTML 5. Your First JavaScript Program 6. JavaScript Placement in HTML File 7. JavaScript Syntax 8. JavaScript Data Types 9. JavaScript Variables 10. JavaScript Identifiers 11. Arithmetic Operators 12. String Concatenation Operators 13. Assignment Operators 14. Comparison Operators 15. Logical Operators 16. Bitwise Operators 17. If Statement 18. If… Else Statement 19. If… Else if… Else Statement 20. Switch Statement 21. The ? Operator 22. While Loop 23. Do While Loop 24. For Loop 25. For…in Loop 26. break Statement 27. continue Statement 28. Arrays 29. Functions 30. JavaScript Objects 31. JavaScript Scope 32. Strings 33. Regular Expressions 34. JavaScript Numbers 35. Math Object 36. Date and Time 37. JavaScript Events 38. Dialog Boxes 39. Error Handling in JavaScript 40. JavaScript Forms Validation 41. JavaScript HTML DOM 42. JavaScript BOM
  • 3. Introduction to JavaScript • A dynamic programming language widely used to create interactive web pages. • Originally developed by Brendan Eich at Netscape Corporation. • Open and cross platform.
  • 4. What JavaScript Can Do? • JavaScript Can Change HTML Content • JavaScript Can Change HTML Attributes • JavaScript Can Change HTML Styles (CSS) • JavaScript Can Validate Data
  • 5. Script tag in HTML <script language="javascript" type="text/javascript"> JavaScript code </script>
  • 6. Noscript tag in HTML <noscript> If you see this message means your browser does not support with JavaScript </noscript>
  • 7. Your First JavaScript Program <html> <body> <script language="javascript“ type="text/javascript"> document.write("Hello World!"); </script> </body> </html>
  • 8. JavaScript Placement in HTML File • JavaScript in <head> • JavaScript in <body> • External JavaScript
  • 9. JavaScript in <head> <html> <head> <script language="javascript" type="text/javascript"> document.write("Hello World!"); </script> </head> <body> </body> </html>
  • 10. JavaScript in <body> <html> <head> </head> <body> <script language="javascript" type="text/javascript"> document.write("Hello World!"); </script> </body> </html>
  • 12. JavaScript Syntax Whitespaces JavaScript ignores spaces, tabs, and newlines that appear between tokens in JavaScript programs.
  • 13. JavaScript Syntax Semicolons are Optional var1 = 10 var2 = 20 But when formatted in a single line as follows, the semicolons are required var1 = 10; var2 = 20;
  • 14. JavaScript Syntax Case Sensitivity JavaScript is a case-sensitive language Identifiers Time, TIme and TIME will have different meanings in JavaScript.
  • 15. JavaScript Syntax Comments in JavaScript // this is a single line comment /* this is a multiline comment */ <!-- this is also a multiline comment //-->
  • 16. JavaScript Data Types There are three primitive data types: • Numbers • Strings of text • Boolean
  • 17. JavaScript Variables Variables are temporary memory locations and they can hold values.
  • 18. JavaScript Variables var score = 234; var city = ”Colombo”; var validity = true;
  • 19. Declaring (Creating) JavaScript Variables var firstName; After the declaration, the variable is empty Assign a value to the variable, use the equal sign firstName = “Roshan”; You can also assign a value to the variable when you declare it var lastName = “Ranasinghe”;
  • 20. Re-Declaring JavaScript Variables If you re-declare a JavaScript variable, it will not lose its value. var firstName = “Nuwan”; var firstName;
  • 21. JavaScript Identifiers Identifiers are unique names given for naming variables, functions and other user defined items • Identifiers can contain letters, digits, underscores, and dollar signs. • Identifiers must begin with a letter. • Identifiers cannot begin with a number. • Identifiers are case sensitive. • Keywords cannot be used as Identifiers.
  • 22. Keywords in JavaScript Keywords cannot be used as variables, functions or any object names.
  • 23. Arithmetic Operators Operator Description Example + Addition A + B will give 30 - Subtraction A - B will give -10 * Multiplication A * B will give 200 / Division B / A will give 2 % Modulus B % A will give 0 ++ Increment B++ gives 21 -- Decrement B-- gives 19 A = 10, B = 20
  • 24. String Concatenation Operators Operator Name Example + Concatenation $str1 = "Hello" $str2 = $txt1 + " world!" += Concatenation assignment $str1 = "Hello" $str1 += " world!"
  • 25. Assignment Operators Operator Example = C = A + B will assign value of A + B into C += C += A is equivalent to C = C + A -= C -= A is equivalent to C = C - A *= C *= A is equivalent to C = C * A /= C /= A is equivalent to C = C / A %= C %= A is equivalent to C = C % A
  • 26. Comparison Operators Operator Name Example == Equal (A == B) is false. != Not equal (A != B) is true. > Greater than (A > B) is false. < Less than (A < B) is true. >= Greater than or equal (A >= B) is false. <= Less than or equal (A <= B) is true. A = 10, B = 20
  • 27. Logical Operators Operator Name Example && And (A && B) is False || Or (A || B) is True ! Not !(A && B) is True A = True, B = False
  • 28. Bitwise Operators Operator Name Example & Bitwise AND (A & B) is 2 | Bitwise OR (A | B) is 3 ^ Bitwise XOR (A ^ B) is 1 ~ Bitwise NOT (~B) is -4 << Bitwise Shift Left (A << 1) is 4 >> Bitwise Shift Right (A >> 1) is 1 >>> Bitwise Shift Right with Sign (A >>> 1) is 1 A = 2, B = 3
  • 29. If Statement if(Boolean_expression){ //Statements will execute if the Boolean expression is true } Boolean Expression Statements True False
  • 30. If… Else Statement if(Boolean_expression){ //Executes when the Boolean expression is true }else{ //Executes when the Boolean expression is false } Boolean Expression Statements True False Statements
  • 31. If… Else if… Else Statement if(Boolean_expression 1){ //Executes when the Boolean expression 1 is true }else if(Boolean_expression 2){ //Executes when the Boolean expression 2 is true }else if(Boolean_expression 3){ //Executes when the Boolean expression 3 is true }else { //Executes when the none of the above condition is true. }
  • 32. If… Else if… Else Statement Boolean expression 1 False Statements Boolean expression 2 Boolean expression 3 Statements Statements False False Statements True True True
  • 33. Switch Statement switch (value){ case constant: //statements break; case constant: //statements break; default: //statements }
  • 34. The ? Operator If condition is true ? Then Value one : Otherwise Value two var h = 10; var x = h<12 ? "morning" : "afternoon";
  • 37. For Loop for(initialization; Boolean_expression; update){ //Statements } Boolean Expression Statements True False Update Initialization
  • 38. For…in Loop for(Variablename in Object){ //Statements }
  • 41. Arrays An Array object allowing you to store multiple values in a single location. 10 30 20 50 15 35 0 1 2 3 4 5 Size = 6 Element Index No A single dimensional array
  • 42. Creating An Array Using keyword new var fruits = new Array( "apple", "orange", "mango" ); var points = new Array(); Using an array literal var fruits = ["apple", "orange", "mango"]; var points = [];
  • 43. Access the Elements of an Array Accesses the value of the first element in fruits var name = fruits[0]; Modifies the first element in cars fruits[0] = “Pineapple"; (You can have objects, functions and arrays in an array)
  • 44. Array Properties and Methods The length property returns the number of elements in array var x = fruits.length; The sort() method sort array in alphabetical order var y = fruits.sort();
  • 45. Functions • A function is a block of code designed to perform a particular task. • A function is executed when "something" invokes it (calls it).
  • 47. Function Invocation The code inside the function will execute when "something" invokes (calls) the function • When an event occurs (when a user clicks a button) • When it is invoked (called) from JavaScript code • Automatically (self invoked)
  • 48. Function Return When JavaScript reaches a return statement, the function will stop executing and the return value is "returned" back to the "caller“ function getSum(a, b) { return a + b; } var sum = getSum(100,200);
  • 49. Invoking the Function Definition function getSum(x, y, z) { return x+y+z; } var def = getSum;
  • 50. JavaScript Objects An object has properties and methods. Ex: • A car has properties like model and color, and methods like drive and stop. • All cars have the same properties, but the property values differ from car to car. • All cars have the same methods, but the methods are performed at different times.
  • 51. Object Properties var car = { VID:4565, model:”Toyota”, color:”white”}; var student = { ID : 4435, name : “Nuwan”, city : “Kandy” };
  • 53. Object Methods var car = { VID: 4565, model : “Toyota”, color : “Red”, drive : function() { document.write(“car is driving”); } };
  • 54. Invoking an Object Method car.drive();
  • 55. Object Methods with return value var student = { ID: 4565, name : “Roshan”, city : “colombo”, getName : function() { return this.name; } };
  • 56. Invoking an Object return value var name = student.getName();
  • 57. JavaScript Scope • Global Scope • Local Scope
  • 58. Global Scope • A variable declared outside a function, becomes global. • Global variables are visible to everywhere in the program. • If you assign a value to a variable that has not been declared, it will automatically become a global variable.
  • 59. Local Scope • Variables declared within a function, become local to the function. • They can only be accessed within the function. • Function parameters work as local variables inside functions.
  • 60. Strings Strings are used for storing and manipulating text. Ex: “Hello World!” ‘No 25, Main Street, Embilipitiya’ ‘It’s Alright’ “He said “hello world!”” "i'm Rasan"
  • 61. String Methods Method Description indexOf(str) returns the index of (the position of) the first occurrence of a specified text in a string lastIndexOf(str) returns the index of the last occurrence of a specified text in a string search(str) searches a string for a specified value and returns the position of the match slice(start, end) extracts a part of a string and returns the extracted part in a new string substring(start, end) similar to slice(). The difference is that substring() cannot accept negative indexes substr(start, end) similar to slice(). The difference is that the second parameter specifies the length of the extracted part. replace(str, str) replaces a specified value with another value in a string toUpperCase() string is converted to upper case toLowerCase() string is converted to lower case concat(str) joins two or more strings charAt(i) returns the character at a specified index (position) in a string split(str) string can be converted to an array trim() Removes whitespace from both ends of a string
  • 62. Regular Expressions A regular expression is a sequence of characters that forms a search pattern. Syntax /pattern/modifiers; Example: var patt = /hello/i
  • 63. Regular Expression Modifiers Modifier Description i Perform case-insensitive matching g Perform a global match (find all matches rather than stopping after the first match) m Perform multiline matching
  • 64. Regular Expression Patterns Pattern Description [abc] Find any of the characters between the brackets [0-9] Find any of the digits between the brackets [^abc] Find any character NOT between the brackets (ab|xyz) Find any of the alternatives separated with | d Find a digit s Find a whitespace character b Find a match at the beginning or at the end of a word . Find a single character, except newline or line terminator n+ Matches any string that contains at least one n n* Matches any string that contains zero or more occurrences of n n? Matches any string that contains zero or one occurrences of n ^n Matches any string with n at the beginning of it n$ Matches any string with n at the end of it
  • 65. JavaScript Numbers • JavaScript Numbers are Always 64-bit Floating Point • JavaScript numbers can be written with, or without decimals Value (Fraction/Mantissa) Exponent Sign 52 bits (0 - 51) 11 bits (52 - 62) 1 bit (63)
  • 66. JavaScript Numbers var a = 34.00; // A number with decimals var b = 34; // A number without decimals var c = 123e5; // 12300000 var d = 123e-5; // 0.00123 var x = 0xFF; // x will be 255 (hexadecimal)
  • 67. JavaScript Numbers Infinity Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number. NaN - Not a Number NaN is a JavaScript reserved word indicating that a value is not a number.
  • 68. Number Methods Method Description Number(arg) Returns a number, converted from its argument. parseFloat(arg) Parses its argument and returns a floating point number parseInt(arg) Parses its argument and returns an integer Method Description toString() Returns a number as a string toExponential() Returns a string, with a number rounded and written using exponential notation. toFixed(n) Returns a string, with a number rounded and written with a specified number of decimals. toPrecision(n) Returns a string, with a number written with a specified length valueOf() Returns a number as a number Global Methods Number Methods
  • 69. Math Object Method Description ceil(x) Returns x, rounded upwards to the nearest integer cos(x) Returns the cosine of x (x is in radians) floor(x) Returns x, rounded downwards to the nearest integer log(x) Returns the natural logarithm (base E) of x max(x,y,z,...,n) Returns the number with the highest value min(x,y,z,...,n) Returns the number with the lowest value pow(x,y) Returns the value of x to the power of y random() Returns a random number between 0 and 1 round(x) Rounds x to the nearest integer sin(x) Returns the sine of x (x is in radians) sqrt(x) Returns the square root of x tan(x) Returns the tangent of an angle
  • 70. Date and Time The Date object lets you work with dates (years, months, days, hours, minutes, seconds, and milliseconds) To display current date: document.write(Date());
  • 71. Creating Date Objects new Date() new Date(milliseconds) new Date(dateString) new Date(year, month, day, hours, minutes, seconds, milliseconds)
  • 72. Date Get Methods Method Description getDate() Get the day as a number (1-31) getDay() Get the weekday as a number (0-6) getFullYear() Get the four digit year (yyyy) getHours() Get the hour (0-23) getMilliseconds() Get the milliseconds (0-999) getMinutes() Get the minutes (0-59) getMonth() Get the month (0-11) getSeconds() Get the seconds (0-59) getTime() Get the time (milliseconds since January 1, 1970) toLocaleDateString() Returns the "date" portion of the Date as a string toLocaleTimeString() Returns the "time" portion of the Date as a string
  • 73. Date Set Methods Method Description setDate() Set the day as a number (1-31) setFullYear() Set the year (optionally month and day) setHours() Set the hour (0-23) setMilliseconds() Set the milliseconds (0-999) setMinutes() Set the minutes (0-59) setMonth() Set the month (0-11) setSeconds() Set the seconds (0-59) setTime() Set the time (milliseconds since January 1, 1970)
  • 74. JavaScript Events • HTML events are things that happen to HTML elements. • When JavaScript is used in HTML pages, JavaScript can react on these events.
  • 75. HTML Events An HTML event can be something the browser does, or something a user does. • An HTML web page has finished loading • An HTML button was clicked • An HTML input field was changed and many more…
  • 76. HTML event handler attributes <element event=“some JavaScript”> Single quotes also works fine <element event=‘some JavaScript’>
  • 77. Common HTML Events Event Description onchange occurs when the content of a form element, the selection, or the checked state have changed onclick occurs when the user clicks on an element onmouseover occurs when the pointer is moved onto an element, or onto one of its children onmouseout occurs when a user moves the mouse pointer out of an element, or out of one of its children onkeydown occurs when the user is pressing a key onload occurs when an object has loaded
  • 78. Dialog Boxes • Alert Dialog Box • Confirmation Dialog Box • Prompt Dialog Box
  • 80. Confirmation Dialog Box var retVal = confirm("Do you want to continue ?");
  • 81. Prompt Dialog Box var retVal = prompt("Enter your name : ", "your name here");
  • 82. Error Handling in JavaScript • onerror() Method • try...catch...finally Statement
  • 83. The onerror() Method Whenever an exception occurs on the page the onerror event is fired. window.onerror = function () { alert("An error occurred."); } testFunc(); //a function which not existing
  • 84. The try...catch...finally Statement You can catch runtime exceptions by try...catch...finally Statement. try { alert("Value of variable a is : " + a ); }catch ( e ) { alert("Error: " + e.description ); }finally { alert("Finally block will always execute!" ); }
  • 85. JavaScript Forms Validation • Data validation is the process of ensuring that computer input is clean, correct, and useful. • HTML form validation can be done by JavaScript. • JavaScript validation is a client side validation which is performed by a web browser before input is sent to the web server.
  • 86. JavaScript Function If fname is empty, this function alerts a message and returns false, to prevent the form from being submitted. function validateForm() { var x = document.forms["myForm"]["fname"].value; if (x == null || x == "") { alert("Name must be filled out"); return false; } return true; }
  • 87. HTML Form <form name="myForm" action="demo_form.php" onsubmit="return validateForm()" method="post"> Name: <input type="text" name="fname"> <input type="submit" value="Submit"> </form>
  • 88. Validating a ZIP Code function validateZIP() { if( document.myForm.Zip.value == "" || isNaN( document.myForm.Zip.value ) || document.myForm.Zip.value.length != 5 ) { alert( "Please provide a zip in the format #####." ); document.myForm.Zip.focus() ; return false; } return true; }
  • 89. Validating an Email Field function validateEmail() { var emailID = document.myForm.EMail.value; atpos = emailID.indexOf("@"); dotpos = emailID.lastIndexOf("."); if (atpos < 1 || ( dotpos - atpos < 2 )) { alert("Please enter correct email ID") document.myForm.EMail.focus() ; return false; } return true; }
  • 90. JavaScript HTML DOM A. JavaScript HTML DOM B. Finding HTML Elements C. Changing HTML Elements D. Adding and Deleting Elements E. Adding Events Handlers F. HTML DOM Level 3
  • 91. JavaScript HTML DOM With the HTML DOM (Document Object Model), JavaScript can access and change all the elements of an HTML document.
  • 92. Finding HTML Elements Method Description document.getElementById() Find an element by element id document.getElementsByTagName() Find elements by tag name document.getElementsByClassName() Find elements by class name
  • 93. Changing HTML Elements Method Description element.innerHTML= Change the inner HTML of an element element.attribute= Change the attribute of an HTML element element.setAttribute(attribute,value) Change the attribute of an HTML element element.style.property= Change the style of an HTML element
  • 94. Adding and Deleting Elements Method Description document.createElement(“elem”) Create an HTML element parent.appendChild(obj) Add an HTML element parent.removeChild(obj) Remove an HTML element parent.replaceChild(ob1, ob2) Replace an HTML element (ob2 with ob1) document.write(text) Write into the HTML output stream
  • 95. Adding Events Handlers Method Description document.getElementById(id).onclick =function(){code} Adding event handler code to an onclick event
  • 96. Finding HTML Objects in HTML (DOM Level 3) Property Description document.anchors Returns all <a> elements that have a name attribute document.body Returns the <body> element document.doctype Returns the document's doctype document.documentElement Returns the <html> element document.domain Returns the domain name of the document server document.forms Returns all <form> elements document.head Returns the <head> element document.images Returns all <img> elements document.links Returns all <area> and <a> elements that have a href attribute document.title Returns the <title> element document.URL Returns the complete URL of the document
  • 97. JavaScript BOM A. JavaScript BOM B. Window Object C. Window Screen D. Window Location E. History F. Window Navigator G. Timing Events H. Cookies
  • 98. JavaScript BOM (Browser Object Model) The Browser Object Model allows JavaScript to "talk to" the browser.
  • 99. Window Object Property Description window.innerHeight the inner height of the browser window window.innerWidth the inner width of the browser window Method Description window.open() open a new window window.close() close the current window window.moveTo() move the current window window.resizeTo() resize the current window
  • 100. Window Screen Property Description screen.width returns the width of the visitor's screen in pixels. screen.height returns the height of the visitor's screen in pixels. screen.availWidth returns the width of the visitor's screen, in pixels, minus interface features like the Windows Taskbar. screen.availHeight returns the height of the visitor's screen, in pixels, minus interface features like the Windows Taskbar. screen.colorDepth returns the number of bits used to display one color. screen.pixelDepth returns the pixel depth of the screen.
  • 101. Window Location Property Description window.location.href returns the href (URL) of the current page window.location.hostname returns the domain name of the web host window.location.pathname returns the path and filename of the current page window.location.protocol returns the web protocol used (http:// or https://) Method Description window.location.assign() loads a new document
  • 102. History Method Description history.back() same as clicking back in the browser history.forward() same as clicking forward in the browser
  • 103. Window Navigator Property Description navigator.cookieEnabled returns true if cookies are enabled, otherwise false navigator.appName return the name of the browser navigator.appCodeName return the name of the browser navigator.product returns the engine name of the browser navigator.appVersion returns version information about the browser navigator.userAgent returns version information about the browser navigator.platform returns the browser platform (operating system) navigator.language returns the browser's language navigator.javaEnabled() returns true if Java is enabled
  • 104. Timing Events Method Description window.setInterval("javascript function", milliseconds) executes a function, over and over again at specified time intervals window.clearInterval(timeoutVariable) stop further executions of the function specified in the setInterval() method window.setTimeout("javascript function", milliseconds) executes a function, once, after waiting a specified number of milliseconds window.clearTimeout(timeoutVariable) stop further executions of the function specified in the setTimeout() method
  • 105. Cookies Create a Cookie with JavaScript document.cookie="username=Nuwan Perera"; document.cookie="username=Nuwan Perera; expires=Thu, 18 Dec 2015 12:00:00 UTC"; //with an expiry date
  • 106. Cookies Read a Cookie with JavaScript var x = document.cookie; document.cookie will return all cookies in one string much like: cookie1=value; cookie2=value; cookie3=value;
  • 107. Cookies Delete a Cookie with JavaScript document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC";

Editor's Notes

  • #5: <!DOCTYPE html> <html> <body> <h1>JavaScript Can Change Images</h1> <img id="myImage" onclick="changeImage()" src="pic_bulboff.gif" width="100" height="180"> <p>Click the light bulb to turn on/off the light.</p> <script> function changeImage() { var image = document.getElementById('myImage'); //since image.src = http://www.w3schools.com/jsref/pic_bulboff.gif if (image.src.search("pic_bulbon.gif")>=0) { // or image.src.match("pic_bulbon") image.src = "pic_bulboff.gif"; } else { image.src = "pic_bulbon.gif"; } } </script> </body> </html>
  • #44: When to Use Arrays? When to use Objects? JavaScript does not support associative arrays. You should use objects when you want the element names to be strings (text). You should use arrays when you want the element names to be numbers. Avoid new Array() There is no need to use the JavaScript's built-in array constructor new Array(). Use [] instead. These two different statements both create a new empty array named points: var points = new Array();         // Bad var points = [];                  // Good 
  • #62: var str = "hello world"; //negative indexes are starts from end to beginning of the array (supports for slice method) document.write(str.slice(-5) + "<br/>"); // last 5 letters (world) document.write(str.slice(2, -2) + "<br/>"); // utill last 2 charators begins from 2 (llo wor)
  • #64: i var str = "Hello world"; var result = str.replace(/hello/i, "Hi"); document.write(result); g var str = "hello world hello world"; var result = str.replace(/world/g , "sri lanka"); document.write(result); m var str = "hello world \nhello hello sri lanka"; var result = str.replace(/^hello/mg,"x"); //put g to find all matches, otherwise it stop by first match document.write(str + "<br/>"); document.write(result);
  • #65: var str = "my name is hello world"; var result = str.replace(/(hello|world)/g,"xxx"); document.write(result); var str = "hellooo world this is my school"; var result = str.replace(/o+/g, "xxx"); document.write(result); var str = "1 10 100 1000 2000 "; //Do a global search for a "1", followed by zero or more "0" characters var result = str.replace(/10*/g,"x"); document.write(str + "<br/>"); document.write(result); var str = "1 10 100 1000 2000"; //Do a global search for a "1", followed by zero or one "0" characters var result = str.replace(/10?/g,"x"); document.write(str + "<br/>"); document.write(result); var str = "hello world hello world hello"; var result = str.replace(/^hello/,"x"); document.write(str + "<br/>"); document.write(result); var str = "hello world hello world hello"; var result = str.replace(/hello$/,"x"); document.write(str + "<br/>"); document.write(result);
  • #68: var myNumber = 2; while (myNumber != Infinity) {          // Execute until Infinity     myNumber = myNumber * myNumber; } var x =  2 / 0;          // x will be Infinity var x = 100 / "Apple";  // x will be NaN (Not a Number) var x = 100 / "10";     // x will be 10 ou can use the global JavaScript function isNaN() to find out if a value is a number. var x = 100 / "Apple"; isNaN(x);               // returns true because x is Not a Number
  • #69: //Global Methods <script> var n; n = 10>4; document.write(Number(n) + "<br/>") n = "10"; document.write(Number(n) + "<br/>") n = "27.34"; document.write(parseInt(n) + "<br/>") n = 65.786; document.write(parseInt(n) + "<br/>") n = "100 cats"; document.write(parseInt(n) + "<br/>") n = "50.75 Ruppess"; document.write(parseFloat(n) + "<br/>") </script>
  • #72: document.write(new Date() + "<br/>"); document.write(new Date(1000000000)+ "<br/>"); document.write(new Date("04 10 2014 20:55") + "<br/>"); document.write(new Date(88, 1, 10, 8, 40, 20, 400)+ "<br/>");
  • #73: var d = new Date(); document.write(d.getDate() + "<br/>"); document.write(d.getDay() + "<br/>"); document.write(d.getFullYear() + "<br/>"); document.write(d.getHours() + "<br/>"); document.write(d.getMilliseconds() + "<br/>"); document.write(d.getMinutes() + "<br/>"); document.write(d.getMonth() + "<br/>"); document.write(d.getSeconds() + "<br/>"); document.write(d.getTime() + "<br/>"); document.write(d.toLocaleTimeString() + "<br/>"); document.write(d.toLocaleDateString() + "<br/>");
  • #74: var d = new Date(); d.setDate(10); d.setFullYear(1988); d.setHours(8); d.setMilliseconds(400); d.setMinutes(40); d.setMonth(1); d.setSeconds(35); //d.setTime(10000); document.write(d + "<br/>");
  • #78: <body> <form name="abc"> <select name="country" onchange="changeparagraph()"> <option value="sri lanka">sri lanka</option> <option value="india">india</option> <option value="australia">australia</option> </select> </form> <p id="pmessage"></p> <script> function changeparagraph(){ document.getElementById("pmessage").innerHTML = document.abc.country.value; } </script> </body> ------------------------------------------------------------------------------------- <body> <p id="pmessage" onmouseover="over()" onmouseout="out()">This is a paragraph</p> <script> function over(){ document.getElementById("pmessage").innerHTML = "mouse moved over this paragraph!"; } function out(){ document.getElementById("pmessage").innerHTML = "mouse moved out from this paragraph!"; } </script> </body> ------------------------------------------------------------------------------- <body> <form name="myform"> <input type="text" name="txtname" onkeypress="keypress()" /> </form> <p id="pmessage" onkeypress="keypress()"></p> <script> function keypress(){ document.getElementById("pmessage").innerHTML = document.myform.txtname.value; } </script> </body>
  • #87: var x = document.myForm.fname.value;
  • #88: <body> <form name="frmDetails" action="test.php" onsubmit="return validateForm()"> Name: <input type="text" name="txtname" /><br/> Phone: <input type="text" name="txtphone" /><br/> Email: <input type="text" name="txtemail" /><br/> <input type="submit" value="Submit" /> </form> <script> function validateForm(){ var name = document.frmDetails.txtname.value; var phone = document.frmDetails.txtphone.value; var email = document.frmDetails.txtemail.value; if(name.trim() == ""){ alert("Enter the name"); document.frmDetails.txtname.focus(); return false; } if(phone.length != 10 || isNaN(phone)){ alert("Enter a valid phone number"); document.frmDetails.txtphone.focus(); return false; } if((email.indexOf("@") <= 2) || (email.lastIndexOf(".") - email.indexOf("@") <= 3)){ alert("Enter a valid email address"); document.frmDetails.txtemail.focus(); return false; } return true; } </script> </body>
  • #93: <body> <p id="p1" class="a">this is a paragraph</p> <p id="p2" class="b">this is a paragraph</p> <p id="p3" class="a">this is a paragraph</p> <p id="p4" class="b">this is a paragraph</p> <script> var a = document.getElementById("p1"); a.innerHTML = "this is first paragraph"; var b = document.getElementById("p2"); b.innerHTML = "this is second paragraph"; var c = document.getElementById("p3"); c.innerHTML = "this is third paragraph"; var d = document.getElementById("p4"); d.innerHTML = "this is fourth paragraph"; </script> </body> //-------------------------------------------------------------------------------------------------------------- <body> <p id="p1" class="a">this is a paragraph</p> <p id="p2" class="b">this is a paragraph</p> <p id="p3" class="a">this is a paragraph</p> <p id="p4" class="b">this is a paragraph</p> <script> var e = document.getElementsByTagName("p"); e[0].innerHTML = "this is first paragraph"; e[1].innerHTML = "this is second paragraph"; e[2].innerHTML = "this is third paragraph"; e[3].innerHTML = "this is fourth paragraph"; </script> </body> ------------------------------------------------------------------------------ <body> <p id="p1" class="a">this is a paragraph</p> <p id="p2" class="b">this is a paragraph</p> <p id="p3" class="a">this is a paragraph</p> <p id="p4" class="b">this is a paragraph</p> <script> var e = document.getElementsByClassName("a"); e[0].innerHTML = "this is first class a paragraph"; e[1].innerHTML = "this is second class a paragraph"; </script> </body>
  • #94: <body> <p id="p1" onclick="changeContent()">click me to change my contents</p> <p id="p2" onclick="centerAlign()">click me to make me center align</p> <p id="p3" onclick="rightAlign()">click me to make me right align</p> <p id="p4" onclick="changeColor()">click me to change my color</p> <script> function changeContent(){ document.getElementById("p1").innerHTML = "thank you!"; } function centerAlign(){ document.getElementById("p2").align = "center"; } function rightAlign(){ document.getElementById("p3").setAttribute("align", "right"); } function changeColor(){ document.getElementById("p4").style.color = "red"; document.getElementById("p4").style.backgroundColor = "yellow"; } </script> </body>
  • #95: ! Never use document.write() after the document is loaded. It will overwrite the document. --------------------------------------------------------------------------------------------------------- <body> <div id="demo"> <p id="pgh1">this is first paragraph</p> <p id="pgh2">this is second paragraph</p> </div> <script> var pgh3 = document.createElement("p"); //create a paragraph pgh3.innerHTML = "this is an another paragraph"; document.getElementById("demo").appendChild(pgh3); //add paragraph to division(demo) var pgh4 = document.createElement("p"); //create a paragraph pgh4.innerHTML = "this is replacing paragraph"; var x = document.getElementById("pgh2"); document.getElementById("demo").replaceChild(pgh4, x); // replaces the paragraph var y = document.getElementById("pgh1"); document.getElementById("demo").removeChild(y); </script> </body>
  • #96: <body> <button id="btnOk">OK</button> <script> document.getElementById("btnOk").onclick = function (){ alert("You have clicked OK button"); } </script>
  • #97: <body> <img src="" id="myimage"/> <a href="http://google.com" name="google">Google</a> <a href="http://yahoo.com" name="yahoo">Yahoo</a><br/><br/> <form name="myform"></form> <script> var obj; obj = document.anchors; //objects collection document.write(obj.google + "<br/>"); obj = document.body; //object document.write(obj + "<br/>"); obj = document.doctype; //object document.write(obj + "<br/>"); obj = document.documentElement; //object document.write(obj + "<br/>"); obj = document.domain; document.write(obj + "<br/>"); // only for sites with a hosted domain obj = document.forms; //objects collection document.write(obj.myform + "<br/>"); obj = document.images; //objects collection document.write(obj.myimage + "<br/>"); obj = document.links; //objects collection document.write(obj.yahoo + "<br/>"); obj = document.title; //property document.write(obj + "<br/>"); obj = document.URL; //property document.write(obj + "<br/>"); </script> </body>
  • #100: <body> <button onclick="openWin()">Open</button><br/> <button onclick="closeWin()">Close</button><br/> <button onclick="moveWin()">Move</button><br/> <button onclick="resizeWin()">Resize</button><br/> <script> document.write(window.innerHeight + "<br/>"); document.write(window.innerWidth + "<br/>"); var myWin; function openWin(){ myWin = window.open("http://google.com", "_blank", "height=200, width=300"); // myWin.document.write(“hello world”); //if you want to write something } function closeWin(){ myWin.close(); } //not working if new myWin page not loaded function moveWin(){ myWin.moveTo(500,100); myWin.focus(); } //not working if new myWin page not loaded function resizeWin(){ myWin.resizeTo(600,500); myWin.focus(); } </script> </body>
  • #101: <script> document.write(screen.width + "<br/>"); document.write(screen.height + "<br/>"); document.write(screen.availWidth + "<br/>"); document.write(screen.availHeight + "<br/>"); document.write(screen.colorDepth + "<br/>"); document.write(screen.pixelDepth + "<br/>"); // For modern computers, Color Depth and Pixel Depth are equal. //All modern computers use 24 bit or 32 bit hardware for color resolution //Older computers used 16 bits: 65,536 different "High Colors" resulution. //Very old computers, and old cell phones used 8 bits: 256 different "VGA colors". </script>
  • #102: <script> document.write(location.href + "<br/>"); document.write(location.hostname + "<br/>"); document.write(location.pathname + "<br/>"); document.write(location.protocol + "<br/>"); location.assign("http://google.com"); </script>
  • #103: <body> <a href="http://google.com">google</a> <br/> <button onclick="back()">Back</button> <br/> <button onclick="forward()">Forward</button> <br/> <script> function back(){ history.back(); } function forward(){ history.forward(); } </script> </body>
  • #104: <script> document.write("Cookie enabled: " + navigator.cookieEnabled + "<br/>"); document.write("App name: " + navigator.appName + "<br/>"); //IE11, Chrome, Firefox, and Safari return appName "Netscape". document.write("App code name: " + navigator.appCodeName + "<br/>"); //Chrome, Firefox, IE, Safari, and Opera all return appCodeName "Mozilla". document.write("Product: " + navigator.product + "<br/>"); document.write("App version: " + navigator.appVersion + "<br/>"); document.write("User agent: " + navigator.userAgent + "<br/>"); document.write("Platform: " + navigator.platform + "<br/>"); document.write("Language: " + navigator.language + "<br/>"); document.write("Java enabled: " + navigator.javaEnabled() + "<br/>"); </script>
  • #105: <body> <h1 id="hdrclock"></h1> <form name="frmuser"> Seconds: <input type="text" name="txtname" /> <input type="button" value="Set Alarm" onclick="setAlarm()" /> <input type="button" value="Cancel Alarm" onclick="cancelAlarm()" /> </form> <script> window.setInterval("showClock()",1000); function showClock(){ var d = new Date(); document.getElementById("hdrclock").innerHTML = d.toLocaleTimeString(); } var alarm; //To be able to use the clearTimeout() method, you must use a global variable x when creating the timeout method function setAlarm(){ var seconds = document.frmuser.txtname.value * 1000; alarm = window.setTimeout("alert('Time to wake up!')", seconds); } function cancelAlarm(){ window.clearTimeout(alarm); //window.clearInterval(x); also works } </script> </body>
  • #106: <body> <h1 id="welcome">Welcome</h1> <form name="myForm"> Name: <input type="text" name="username" /> <input type="button" value="Remember me" onclick="createCookie()" /> <input type="button" value="Clear" onclick="deleteCookie()"> </form> <script> document.getElementById("welcome").innerHTML = "Welcome " + retrieveCookie("name"); function createCookie(){ var name = document.myForm.username.value; document.cookie = "name=" + name; alert("Thank you! Visit us again"); } function retrieveCookie(cname){ var c = document.cookie; var ca = c.split("; "); // use space after ; or use trim() for(var i=0; i<=ca.length-1; i++){ if(ca[i].indexOf(cname)==0){ //if cookie begins with "name" var retVal = ca[i].slice(cname.length+1); //extracts the value after "name=" return retVal; } } return "" } function deleteCookie(){ document.cookie = "name=; expires=Thu, 01 Jan 1970 00:00:00 UTC"; //short date like “01 jan 1970” also works alert("Cookies cleared"); } </script> </body>
  • #108: Short date like expires=01 jan 1970 also works