SlideShare a Scribd company logo
Introduction to JavaScript
Table of Contents
 What is DHTML?
 DHTMLTechnologies
 HTML, CSS, JavaScript, DOM
2
Table of Contents (2)
 Introduction to JavaScript
 What is JavaScript
 Implementing JavaScript into Web pages
 In <head> part
 In <body> part
 In external .js file
3
Table of Contents (3)
 JavaScript Syntax
 JavaScript operators
 JavaScript DataTypes
 JavaScript Pop-up boxes
 alert, confirm and prompt
 Conditional and switch statements, loops and
functions
4
DHTML
Dynamic Behavior at the Client Side
What is DHTML?
 Dynamic HTML (DHTML)
 Makes possible a Web page to react and change
in response to the user’s actions
 DHTML = HTML + CSS + JavaScript
6
DHTML
HTML CSS JavaScript DOM
DTHML = HTML + CSS + JavaScript
 HTML defines Web sites content through
semantic tags (headings, paragraphs, lists, …)
 CSS defines 'rules' or 'styles' for presenting
every aspect of an HTML document
 Font (family, size, color, weight, etc.)
 Background (color, image, position, repeat)
 Position and layout (of any object on the page)
 JavaScript defines dynamic behavior
 Programming logic for interaction with the user,
to handle events, etc. 7
JavaScript
Dynamic Behavior in a Web Page
JavaScript
 JavaScript is a front-end scripting language
developed by Netscape for dynamic content
 Lightweight, but with limited capabilities
 Can be used as object-oriented language
 Client-side technology
 Embedded in your HTML page
 Interpreted by theWeb browser
 Simple and flexible
 Powerful to manipulate the DOM 9
JavaScript Advantages
 JavaScript allows interactivity such as:
 Implementing form validation
 React to user actions, e.g. handle keys
 Changing an image on moving mouse over it
 Sections of a page appearing and disappearing
 Content loading and changing dynamically
 Performing complex calculations
 Custom HTML controls, e.g. scrollable table
 Implementing AJAX functionality 10
What Can JavaScript Do?
 Can handle events
 Can read and write HTML elements and
modify the DOM tree
 Can validate form data
 Can access / modify browser cookies
 Can be used as object-oriented language
 Can handle exceptions
 Can perform asynchronous server calls (AJAX)
11
JavaScript Output
12
 JavaScript Display Possibilities
 JavaScript can "display" data in different ways:
 Writing into an HTML element, using
innerHTML.
 Writing into the HTML output using
document.write().
 Writing into an alert box, using window.alert().
 Writing into the browser console, using
console.log().
The First Script
first-script.html
13
<html>
<body>
<script type="text/javascript">
alert('Hello JavaScript!');
</script>
</body>
</html>
Another Small Example
small-example.html
14
<html>
<body>
<script type="text/javascript">
document.write('JavaScript rulez!');
</script>
</body>
</html>
Using JavaScript Code
 The JavaScript code can be placed in:
 <script> tag in the head
 <script> tag in the body – not recommended
 External files, linked via <script> tag the head
 Files usually have .js extension
 Highly recommended
 The .js files get cached by the browser
15
<script src="scripts.js" type="text/javscript">
<!– code placed here will not be executed! -->
</script>
JavaScript – When is Executed?
 JavaScript code is executed during the page
loading or when the browser fires an event
 All statements are executed at page loading
 Some statements just define functions that can
be called later
 Function calls or code can be attached as
"event handlers" via tag attributes
 Executed when the event is fired by the browser
16
<img src="logo.gif" onclick="alert('clicked!')" />
<html>
<head>
<script type="text/javascript">
function test (message) {
alert(message); essa
}
</script>
</head>
<body>
<img src="logo.gif"
onclick="test('clicked!')" />
</body>
</html>
Calling a JavaScript Function
from Event Handler – Example
image-onclick.html
17
Using External Script Files
 Using external script files:
 External JavaScript file:
18
<html>
<head>
<script src="sample.js" type="text/javascript">
</script>
</head>
<body>
<button onclick="sample()" value="Call JavaScript
function from sample.js" />
</body>
</html>
function sample() {
alert('Hello from sample.js!')
}
external-JavaScript.html
sample.js
The <script> tag is always empty.
The JavaScript
Syntax
JavaScript Syntax
 The JavaScript syntax is similar to C# and Java
 Operators (+, *, =, !=, &&, ++, …)
 Variables (typeless)
 Conditional statements (if, else)
 Loops (for, while)
 Arrays (my_array[]) and associative arrays
(my_array['abc'])
 Functions (can return value)
 Function variables
20
Variables
21
 All JavaScript variables must be identified with unique names.
 These unique names are called identifiers.
 Identifiers can be short names (like x and y) or more descriptive names
(age, sum, totalVolume).
 The general rules for constructing names for variables (unique
identifiers) are:
 Names can contain letters, digits, underscores, and dollar signs.
 Names must begin with a letter
 Names can also begin with $ and _ (but we will not use it in this tutorial)
 Names are case sensitive (y and Y are different variables)
 Reserved words (like JavaScript keywords) cannot be used as names
DataTypes
 JavaScript data types:
 Numbers (integer, floating-point)
 Boolean (true / false)
 String type – string of characters
 Arrays
 Associative arrays (hash tables)
22
var myName = "You can use both single or double
quotes for strings";
var my_array = [1, 5.3, "aaa"];
var my_hash = {a:2, b:3, c:"text"};
Greater than
<=
Symbol Meaning
>
< Less than
>= Greater than or equal to
Less than or equal to
== Equal
!= Not equal
Conditional Statement (if)
23
unitPrice = 1.30;
if (quantity > 100) {
unitPrice = 1.20;
}
Conditional Statement (if) (2)
 Very often when you write code, you want to perform diff
 You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
24
Use if to specify a block of code to be executed, if a specified condition is true
Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
Use switch to specify many alternative blocks of code to be executed
The if Statement syntax
if (condition) {
block of code to be executed if the condition is true
}
25
Conditional Statement (else,
else if)
if (condition) {
block of code to be executed if the condition is true
} else {
block of code to be executed if the condition is false
}
The else Statement syntax
The else if Statement syntax
if (condition1) {
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is false and condition2 is true
} else {
block of code to be executed if the condition1 is false and condition2 is false
}
Switch Statement
 The switch statement works like in C#:
26
switch (variable) {
case 1:
// do something
break;
case 'a':
// do something else
break;
case 3.14:
// another code
break;
default:
// something completely different
}
switch-statements.html
Loops
 Like in C#
 for loop
 while loop
 do … while loop
27
var counter;
for (counter=0; counter<4; counter++) {
alert(counter);
}
while (counter < 5) {
alert(++counter);
} loops.html
28
Interactivity with HTML Elements
UsingText box
29
<FORM name="F1" path=" ">
Name: <input type=“text" name=“txt1" >
Class: <input type=“text" name=“txt2" >
<input TYPE="button" value="CLICK"
ONCLICK = "clk()">
</FORM>
30
<html> <head>
<script language=“javascript”>
function clk()
{
Var x=document.F1.txt1.value;
Var z=document.F1.txt2.value;
Document.write (“your name is”+x+”your class is “+z);
}
</script></head>
<body>
<FORM name="F1" path=" ">
Name: <input type=“text" name=“txt1" >
Class: <input type=“text" name=“txt2" >
<input TYPE="button" value="CLICK" ONCLICK = "clk()">
</FORM></body>
31
UsingText box
<FORM name="F1" path=" ">
NO1: <input type=“text" name=“txt1" >
NO2: <input type=“text" name=“txt2" >
<input TYPE="button" value=“Add"
ONCLICK = "clk()">
</FORM>
32
function clk() {
Var x=document.F1.txt1.value;
Var z=document.F1.txt2.value;
A=ParseInt(x);
B= ParseInt(z);
C=A+B;
Alert(c);
}
<FORM name="F1" path=" ">
N01: <input type=“text" name=“txt1" >
No2: <input type=“text" name=“txt2" >
<input TYPE="button" value="CLICK" ONCLICK = "clk()">
</FORM>
33
Using Radio buttons
<FORM name="F1" path=" ">
<input type="radio" name="MS" > Single
<input type="radio" name="MS" > Married
<inputTYPE="button" value="CLICK" ONCLICK = "clk()">
</FORM>
34
 function clk()
 {
 if ( document.F1.MS[0].checked == true )
 alert ("Single");
 else if ( document.F1.MS[1].checked == true )
 alert ("Married");
 }
 <FORM name="F1" path=" ">
 <input type="radio" name="MS" > Single
 <input type="radio" name="MS" > Married
 <input TYPE="button" value="CLICK" ONCLICK = "clk()">
 </FORM>
35
getElementById
Now we get the data from HTML elements by it’s id
For this purpose we using getElementById
Function
Like this:
document.getElementById(“ Id of HTML elements")
36
function clk(){
var x= document.getElementById("txt").value;
alert(x);
}
<body>
<form id="form1" name="form1" method="post"
action="">
<input type="text" id="txt" name="text1" />
<input type="button" value="ok" onclick="clk()"
/>
</form> </body>
Example:
HTML Events
37
HTML events are "things" that happen to HTML elements.
When JavaScript is used in HTML pages, JavaScript can
"react" on these events.
An HTML event can be something the browser does, or
something a user does.
Here are some examples of HTML events:
• An HTML web page has finished loading
• An HTML input field was changed
• An HTML button was clicked
Often, when events happen, you may want to do
something.
JavaScript lets you execute code when events are
detected.
38
HTML allows event handler attributes, with JavaScript code,
to be added to HTML elements.
With single quotes:
<element event='some JavaScript‘>
With double quotes:
<element event="some JavaScript">
HTML Events..
<p>Click the button to display the date.</p>
<input type = “button” onclick="displayDate()“ value =“The time is?”>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
In the following example, an onclick attribute (with code), is added to
a <button> element:
Standard Popup Boxes
 Alert box with text and [OK] button
 Just a message shown in a dialog box:
 Confirmation box
 Contains text, [OK] button and [Cancel] button:
 Prompt box
 Contains text, input field with default value:
39
alert("Some text here");
confirm("Are you sure?”,”defaualt text”);
prompt ("enter amount", 10);
Sum of Numbers – Example
sum-of-numbers.html
40
<html>
<head>
<title>JavaScript Demo</title>
<script type="text/javascript">
function calcSum() {
value1 =
parseInt(document.mainForm.textBox1.value);
value2 =
parseInt(document.mainForm.textBox2.value);
sum = value1 + value2;
document.mainForm.textBoxSum.value = sum;
}
</script>
</head>
Sum of Numbers – Example (2)
sum-of-numbers.html (cont.)
41
<body>
<form name="mainForm">
<input type="text" name="textBox1" /> <br/>
<input type="text" name="textBox2" /> <br/>
<input type="button" value="Process"
onclick="javascript: calcSum()" />
<input type="text" name="textBoxSum"
readonly="readonly"/>
</form>
</body>
</html>
JavaScript Prompt – Example
prompt.html
42
price = prompt("Enter the price", "10.00");
alert('Price + VAT = ' + price * 1.2);
43
var r = confirm("Press a button");
if (r == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}
JavaScript Confirm– Example
The window.confirm() method can be written without the window prefix.
Confirmation Box
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to
proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false.
var person = prompt("Please enter your name",
“Ahmad Mahmood");
if (person != null) {
document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?"; }
A prompt box is often used if you want the user to input a
value before entering a page.
When a prompt box pops up, the user will have to click
either "OK" or "Cancel" to proceed after entering an input
value.
If the user clicks "OK" the box returns the input value. If the
user clicks "Cancel" the box returns null.
Array
44
JavaScript arrays are used to store multiple values in a single
variable.
var cars = ["Saab", "Volvo", "BMW"];
Definition :
An array is a special variable, which can hold more than one value
at a time.
If a list of items (a list of car names, for example), storing the cars
in single variables could look like this:
var car1 = "Saab";
var car2 = "Volvo";
var car3 = "BMW";
Creating an Array
Using an array literal is the easiest way to create
a JavaScriptArray.
Syntax:
var array_name = [item1, item2, ...];
var cars = ["Saab", "Volvo", "BMW"];
Array..
45
Using the JavaScript Keyword new:
var cars = new Array("Saab", "Volvo", "BMW");
Access the Elements of an Array:
array element is accessing by referring to the index number.
This statement accesses the value of the first element in cars:
var name = cars[0];
Changing an Array Element:
This statement changes the value of the first element in cars:
cars[0] = "Opel";
Functions
 Code structure – splitting code into parts
 Data comes in, processed, result returned
46
function average(a, b, c)
{
var total;
total = a+b+c;
return total/3;
}
Parameters come
in here.
Declaring variables
is optional.Type is
never declared.
Value returned
here.
Function Arguments
and ReturnValue
 Functions are not required to return a value
 When calling function it is not obligatory to
specify all of its arguments
 The function has access to all the arguments
passed via arguments array
47
function sum() {
var sum = 0;
for (var i = 0; i < arguments.length; i ++)
sum += parseInt(arguments[i]);
return sum;
}
alert(sum(1, 2, 4));
functions-demo.html
String Operations
 The + operator joins strings
 What is "9" + 9?
 Converting string to number:
48
string1 = "fat ";
string2 = "cats";
alert(string1 + string2); // fat cats
alert("9" + 9); // 99
alert(parseInt("9") + 9); // 18
Some string common function
49
The length property returns the number of
characters that are in a string, using an integer.
Below is the basic code for accessing this
property.
var myString = "123456";
var length = myString.length;
document.write("The string is this long: " + length);
Out put:
The string is this long: 6
Length
Spilt
50
The ability to split up a string into separate
chunks has been supported in many
programming languages, and it is available in
JavaScript as well. If you have a long string
like “this is computer science faculty" and
want to store each name separately, you can
specify the space character " " and have the
split function create a new chunk every time
it sees a space.
51
Let's start off with a little example that takes a string of
numbers and splits when it sees the number 5.That means
the delimiter for this example is 5. Notice that the split
function returns an array that we store into mySplitResult.
var myString = "123456789";
var mySplitResult = myString.split("5");
document.write("The first element is " + mySplitResult[0]);
document.write("<br />The second element is "
+ mySplitResult[1]);
Out put:
The first element is 1234
The second element is 6789
Search
52
The search() method searches a string for a
specified value and returns the position of
the match:
var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate");
Out put: 7
53
The most important thing to remember when creating a regular
expression is that it must be surrounded with slashes /regular
expression/.With that knowledge let's search a string to see if a
common name “2001" is inside it.
var myRegExp = /2001/;
var string1 = “the computer science facultyi s established in 2001 in IUST.";
var matchPos1 = string1.search(myRegExp);
if(matchPos1 != -1)
document.write("There was a match at position " + matchPos1);
else document.write("There was no match in the first string");
Out put: There was a match at position 44
For powerful search use regular expression
Extracting String Parts
54
There are 3 methods for extracting a part
of a string:
•slice(start, end)
•substring(start, end)
•substr(start, length)
Slice
55
slice() extracts a part of a string and returns the
extracted part in a new string.
The method takes 2 parameters: the start
position, and the end position (end not included).
This example slices out a portion of a string from
position 7 to position 12 (13-1):
var str = "Apple, Banana, Kiwi";
var res = str.slice(7, 13);
The result of res will be: Banana
Slice…
56
If a parameter is negative, the position is counted
from the end of the string.
This example slices out a portion of a string from
position -12 to position -6:
var str = "Apple, Banana, Kiwi";
var res = str.slice(-12, -6);
The result of res will be: Banana
If you omit the second parameter, the method will slice out the rest of the string:
var res = str.slice(7);
var res = str.slice(-12);
Substring
57
substring() is similar to slice().
The difference is that substring() cannot accept
negative indexes.
var str = "Apple, Banana, Kiwi";
var res = str.substring(7, 13);
The result of res will be: Banana
If you omit the second parameter, substring() will slice out the rest of the string.
substr
58
substr() is similar to Substring().
The difference is that the second parameter
specifies the length of the extracted part.
var str = "Apple, Banana, Kiwi";
var res = str.substr(7, 6);
The result of res will be: Banana
If you omit the second parameter, substr() will slice out the rest of the string.
If the first parameter is negative, the position counts from the end of the string.
Replace
59
The replace() method replaces a specified value with
another value in a string:
var str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "W3Schools");
Output Please visit W3Schools!
By default, the replace() method replaces only the
first match:
var str = "Please visit Microsoft and Microsoft!";
var n = str.replace("Microsoft", "W3Schools");
60
Replace…
By default, the replace() method is case sensitive. Writing
MICROSOFT (with upper-case) will not work:
var str = "Please visit Microsoft!";
var n = str.replace("MICROSOFT", "W3Schools");
To replace case insensitive, use a regular expression with
an /i (insensitive):
var str = "Please visit Microsoft!";
var n = str.replace(/MICROSOFT/i, "W3Schools");
To replace all matches, use a regular expression with a /g
str = "Please visit Microsoft and Microsoft!";
n = str.replace(/Microsoft/g, "W3Schools");
Index of
61
The indexOf() method returns the index of (the position
of) the first occurrence of a specified text in a string:
JavaScript counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is
the third ...
The lastIndexOf() method returns the index of
the last occurrence of a specified text in a string:
62
var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate");
Output 22
<script type="text/javascript">
var aURL = "http://www.tizag.com/";
var aPosition = aURL.indexOf("www");
document.write("The position of www = " + aPosition);
</script >
Out put: The position of www = 7
Both methods accept a second parameter as the starting position
for the search:
var aURL = http://www.webtizag.com/";
var aPosition = aURL.indexOf(“w", 10);
document.write("The position of www = " + aPosition);
The position of www = 11
Search and IndexOf
 The two methods, indexOf() and search(), are equal?
 They accept the same arguments (parameters), and
return the same value?
 But the differences are:
 The search() method cannot take a second start
position argument.
 The indexOf() method cannot take powerful search
values (regular expressions).
 We will learn more about regular expressions later.
63
Search and IndexOf
 The two methods, indexOf() and search(), are equal?
 They accept the same arguments (parameters), and
return the same value?
 But the differences are:
 The search() method cannot take a second start
position argument.
 The indexOf() method cannot take powerful search
values (regular expressions).
 We will learn more about regular expressions in a later
chapter. 64
Converting to Upper and Lower Case
A string is converted to upper case with toUpperCase():
var text1 = "Hello World!";
var text2 = text1.toUpperCase();
A string is converted to lower case with toLowerCase():
var text1 = "Hello World!";
var text2 = text1.toLowerCase();
65
charAt and charCodeAt
66
The charAt() method returns the character at a specified
index (position) in a string:
var str = "HELLO WORLD";
str.charAt(0); // returns H
The charCodeAt() method returns the unicode of the
character at a specified index in a string.
The method returns a UTF-16 code (an integer between 0
and 65535).
var str = "HELLO WORLD";
str.charCodeAt(0); // returns 72
innerHTML
67
The easiest way to get or change the content of an
element is by using the innerHTML property.
The innerHTML property is useful for getting or replacing
the content of HTML elements.
The innerHTML property can be used to get or change
any HTML element, including <html> and <body>.
Return the innerHTML property:
HTMLElementObject.innerHTML
Set the innerHTML property:
HTMLElementObject.innerHTML = text
Everything is Object
 Every variable can be considered as object
 For example strings and arrays have member
functions:
68
var test = "some string";
alert(test[7]); // shows letter 'r'
alert(test.charAt(5)); // shows letter 's'
alert("test".charAt(1)); //shows letter 'e'
alert("test".substring(1,3)); //shows 'es'
var arr = [1,3,4];
alert (arr.length); // shows 3
arr.push(7); // appends 7 to end of array
alert (arr[3]); // shows 7
objects.html
JavaScript Objects
69
Real Life Objects, Properties, and Methods
In real life, a car is an object.
A car has properties like weight and color, and methods like start and stop:
Object Properties Methods
car.name = Fiat
car.model = 500
car.weight = 850kg
car.color = white
car.start()
car.drive()
car.brake()
car.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.
JavaScript Objects…
70
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named car:
var car = {type:“Toyota", model:"500", color:"white"};
The values are written as name:value pairs (name and value separated by a colon).
Object Properties
The name:values pairs (in JavaScript objects) are called properties.
var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
Property PropertyValue
firstName John
lastName Doe
age 50
eyeColor blue
JavaScript Objects…
71
Spaces and line breaks are not important. An object definition can span multiple lines:
var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
Object Definition
You define (and create) a JavaScript object with an object literal:
var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};
JavaScript Objects…
72
objectName.propertyName
Accessing Object Properties
You can access object properties in two ways:
objectName["propertyName"]
<body>
<p>
There are two different ways to access an object property:
</p>
<p>You can use person.property or person["property"].</p>
<p id="demo"></p>
<script>
var person = {
firstName: "John",
lastName : "Doe",
id : 5566
};
document.getElementById("demo").innerHTML =
person.firstName + " " + person.lastName;
</script>
document.getElementById("demo"
).innerHTML =
person["firstName"] + " " +
person["lastName"];
HTML Document Object Model
(HDOM)
When a web page is loaded, the browser creates
a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects:
Document Object Model (DOM)
74
With the object model, JavaScript gets all the
power it needs to create dynamic HTML:
JavaScript can change all the HTML elements in the page
JavaScript can change all the HTML attributes in the page
JavaScript can change all the CSS styles in the page
JavaScript can remove existing HTML elements and attributes
JavaScript can add new HTML elements and attributes
JavaScript can react to all existing HTML events in the page
JavaScript can create new HTML events in the page
75
The DOM is a W3C (World Wide Web Consortium) standard.
The DOM defines a standard for accessing documents:
"TheW3C Document Object Model (DOM) is a platform and
language-neutral interface that allows programs and scripts to
dynamically access and update the content, structure, and style of
a document.“
The W3C DOM standard is separated into 3 different parts:
Core DOM - standard model for all document types
XML DOM - standard model for XML documents
HTML DOM - standard model for HTML documents
What is the DOM?
What is the HDOM?
 The HTML DOM is a standard object model
and programming interface for HTML.
 It defines:
76
The HTML elements as objects
The properties of all HTML elements
The methods to access all HTML elements
The events for all HTML elements
In other words:The HTML DOM is a standard for how to get,
change, add, or delete HTML elements.
JavaScript HTML DOM Methods
 HTML DOM methods are actions you can perform (on HTML
Elements).
 HTML DOM properties are values (of HTML Elements) that you
can set or change.
77
The DOM Programming Interface
The HTML DOM can be accessed with JavaScript (and with
other programming languages).
In the DOM, all HTML elements are defined as objects.
The programming interface is the properties and methods of each object.
A property is a value that you can get or set (like changing the content of an HTML
element).
A method is an action you can do (like add or deleting an HTML element).
JavaScript HTML DOM Methods…
The getElementById Method
 The most common way to access an HTML
element is to use the id of the element.
The innerHTML Property
 The easiest way to get the content of an element
is by using the innerHTML property.
 The innerHTML property is useful for getting or
replacing the content of HTML elements.
78
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "HelloWorld!";
</script>
JavaScript HTML DOM Documen
The HTML DOM document object is the owner of
all other objects in your web page.
The HTML DOM Document Object
 The document object represents your web page.
 If you want to access any element in an HTML
page, you always start with accessing the
document object.
 Next slide: some examples of how you can use
the document object to access and manipulate
HTML. 79
80
Finding HTML Elements
Method Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class name
Changing HTML Elements
Method Description
element.innerHTML = new html content Change the inner HTML of an element
element.attribute = new value Change the attribute value of an HTML element
element.setAttribute(attribute, value) Change the attribute value of an HTML element
element.style.property = new style Change the style of an HTML element
Adding and Deleting Elements
Method Description
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(element) Replace an HTML element
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
Note : that you don't use the "on" prefix for the event; use "click" instead of "onclick".
Syntax element.addEventListener(event, function, useCapture);
The first parameter is the type of the event (like "click" or "mousedown").
The second parameter is the function we want to call when the event occurs.
The third parameter is a boolean value specifying whether to use event bubbling
or event capturing.This parameter is optional.
DOM Nodes
According to the W3C HTML DOM standard, everything in an HTML
document is a node:
 The entire document is a document node
 Every HTML element is an element node
 The text inside HTML elements are text nodes
 Every HTML attribute is an attribute node
 All comments are comment
nodes
82
With the HTML DOM, all nodes in the
node tree can be accessed by JavaScript.
New nodes can be created, and all nodes
can be modified or deleted.
Node Relationships
83
The nodes in the node tree have a hierarchical relationship to each other.
The terms parent, child, and sibling are used to describe the relationships.
In a node tree, the top node is called the root (or root node)
Every node has exactly one parent, except the root (which has no
parent)
A node can have a number of children
Siblings (brothers or sisters) are nodes with the same parent
<head>
<title>DOMTutorial</title>
</head>
<body>
<h1>DOM Lesson one</h1>
<p>Hello world!</p>
</body>
84
Node Relationships…
From the HTML above you can read:
<html> is the root node
<html> has no parents
<html> is the parent of <head> and <body>
<head> is the first child of <html>
<body> is the last child of <html>
and:
<head> has one child: <title>
<title> has one child (a text node): "DOM
Tutorial"
<body> has two children: <h1> and <p>
<h1> has one child: "DOM Lesson one"
<p> has one child: "Hello world!"
<h1> and <p> are siblings
and
Navigating Between Nodes
You can use the following node properties to navigate between nodes with JavaScript:
parentNode
childNodes[nodenumber]
firstChild
lastChild
nextSibling
previousSibling
Warning !
A common error in DOM processing is to
expect an element node to contain text.
The value of the text node can be accessed by the
node's innerHTML property, or the nodeValue.
Node Relationships…
85
Child Nodes and NodeValues
In addition to the innerHTML property, you can also use the childNodes and
nodeValue properties to get the content of an element.
The following example collects the node value of an <h1> element and copies it
into a <p> element:
<script>
var myText =
document.getElementById("intro").childNodes[0].nodeValue;
document.getElementById("demo").innerHTML = myText;
</script>
<h1 id="intro">My First Page</h1> <p id="demo">Hello!</p>
In the example above, getElementById is a method, while childNodes and nodeValue are
properties.
In this tutorial we use the innerHTML property. However, learning the method above is
useful for understanding the tree structure and the navigation of the DOM.
Node Relationships…
 Using the firstChild property is the same as using childNodes[0]:
86
<script>
myText =
document.getElementById("intro").firstChild.nodeValue;
document.getElementById("demo").innerHTML = myText;
</script>
<h1 id="intro">My First Page</h1>
<p id="demo">Hello World!</p>
DOM Root Nodes
There are two special properties that
allow access to the full document:
document.body -The body of the
document
document.documentElement –The
full document
<p>Hello World!</p>
<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates
the <b>document.body</b>
property.</p>
</div>
<script>
alert(document.body.innerHTML);
</script>
Node Relationships…
87
Creating New HTML Elements (Nodes)
To add a new element to the HTML DOM, you must create the element (element
node) first, and then append it to an existing element.
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
<div id="div1">
<p id="p1">This is
a paragraph.</p>
<p id="p2">This is
another paragraph.
</p>
</div>
Creating new HTML Elements - insertBefore()
The appendChild() method in the previous example, appended the new element as the last
child of the parent.
If you don't want that you can use the insertBefore() method:
var element = document.getElementById("div1");
var child = document.getElementById("p1");
element.insertBefore(para,child);
Node Relationships…
88
Removing Existing HTML Elements
To remove an HTML element, you must know the parent of the element:
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.removeChild(child);
The method
node.remove() is
implemented in the DOM
4 specification.
But because of poor
browser support, you
should not use it.
Replacing HTML Elements
To replace an element to the HTML DOM, use the replaceChild() method:
<div id="div1">
<p id="p1">This is a
paragraph.</p>
<p id="p2">This is another
paragraph.</p>
</div>
var para = document.createElement("p");
var node =
document.createTextNode("This is
new.");
para.appendChild(node);
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.replaceChild(para,child);
The Built-In
Browser Objects
Built-in Browser Objects
 The browser provides some read-only data via:
 window
 The top node of the DOM tree
 Represents the browser's window
 document
 holds information the current loaded document
 screen
 Holds the user’s display properties
 navigtor
 Holds information about the browser
 History
 Contain the browser history
 location
 Contain the current page URL
90
DOM Hierarchy – Example
91
window
navigator screen document history location
form
button form
form
Window Object Details
 Properties
 status: Specifies a temporary message that
appears on the status bar on the bottom of the
browser window.
Browser support
 location: Identifies the URL associated with a
window object. It can be used to redirect the
client to another URL.
 document: Refers to the current document
being displayed in the window. 92
Methods of Windows object
open(): Opens a new window with a specified document or opens the
document in the specified named window.
window.open("URL", "windowName", "featureList");
close(): Closes the current window. window.close();
alert(): Displays a message in a dialog box with an OK button.
confirm(): Displays a Confirm dialog box with OK and Cancel buttons.
prompt(): Displays a Prompt dialog box with a text field for entering a
value, with a OK & Cancel button.
blur() & focus(): Removes focus from or gives focus to a window.
93
94
<INPUT TYPE="button"VALUE="Open Window“
onClick = " NW = window.open (‘ ‘ , 'NewWin‘ ,
'toolbar=no, status=no, width=200,height=100‘ );” >
<INPUTTYPE="button"VALUE="Close Window"
onClick="NW.close();" >
<INPUTTYPE="button"VALUE="Close Main Window"
onClick="window.close();">
Window. open example
Window .prompt example
95
<html>
<head>
<script language="javascript">
document.write("This illustrates the Prompt
method");
var username=prompt("What is your name?","")
alert("Hello," + username + "!")
</script>
</head>
<body> </body> </html>
Opening New Window – Example
 window.open()
96
var newWindow = window.open("", "sampleWindow",
"width=300, height=100, menubar=yes,
status=yes, resizable=yes");
newWindow.document.write(
"<html><head><title>
Sample Title</title>
</head><body><h1>Sample
Text</h1></body>");
newWindow.status =
"Hello folks";
window-open.html
The Navigator Object
97
alert(window.navigator.userAgent);
The navigator in the
browser window
The userAgent
(browser ID)
The browser
window
Document and Location
 document object
 Provides some built-in arrays of specific objects
on the currently loaded Web page
 document.location
 Used to access the currently open URL or
redirect the browser
98
document.links[0].href = "yahoo.com";
document.write(
"This is some <b>bold text</b>");
document.location = "http://www.yahoo.com/";
The Screen Object
 The screen object contains information about
the display
99
window.moveTo(0, 0);
x = screen.availWidth;
y = screen.availHeight;
window.resizeTo(x, y);
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"Screen width is " + screen.width;
</script>
</body>
</html>
ScreenWidth: 1440
Regular Expressions
If you use HTML forms on your
website, and want to make sure
that your visitors submit valid data
on those forms, you might want to
consider using some regular
expressions in JavaScript
FormValidation – Example
101
function checkForm()
{
var valid = true;
if (document.mainForm.firstName.value == "") {
alert("Please type in your first name!");
document.getElementById("firstNameError").
style.display = "inline";
valid = false;
}
return valid;
}
…
<form name="mainForm" onsubmit="return checkForm()">
<input type="text" name="firstName" />
…
</form>
form-validation.html
Regular Expression syntax
 / Escapes special characters to literal and
literal characters to special
 […] Match any one character between the
brackets
 [^…] Match any one character not between the
brackets
 w, W Match any wordnon-word character
 s, S Match any whitespace/non-whitespace
 d, D Match any digit/non-digit
 ^, $ require match at beginning/end of a string
or in multi-line mode, beginning/end of
a line
 a | b Match either a or b
 + Match previous term one or more times
 ^ Matches beginning of input
 $ Matches end of input
FormValidation
/^[0-9]+$/ : Match values with Digits from 0 to 9
/^[1-5]+$/ : Match values with Digits from 1 to 5
/^[a-z]+$/ : Match values with alphabet from a to z
(small letter)
/^[A-Z]+$/ : Match values with alphabet from A to Z
/^[a-z0-9]+$/ : Match values with letter and Digits
/^[w-.+]+@[a-zA-Z0-9.-]+.[a-zA-z0-9]{2,4}$/
Match values with valid Email address
That all use with match function
The Math Object
 The Math object provides some mathematical
functions
104
for (i=1; i<=20; i++) {
var x = Math.random();
x = 10*x + 1;
x = Math.floor(x);
document.write(
"Random number (" +
i + ") in range " +
"1..10 --> " + x +
"<br/>");
}
math.html
Math Objects
 Math.PI; // returns 3.141592653589793
 Math.round(4.7); // returns 5
 Math.pow(8, 2); // returns 64
 Math.sqrt(64); // returns 8
 Math.abs(-4.7); // returns 4.7
 Math.ceil(4.4); // returns 5
 Math.floor(4.7); // returns 4
 Math.Random(); //returns a random number
between 0 (inclusive), and 1 (exclusive): 105
The Date Object
 The Date object provides date / calendar
functions
106
var now = new Date();
var result = "It is now " + now;
document.getElementById("timeField")
.innerText = result;
...
<p id="timeField"></p>
dates.html
Timing Events
107
The window object allows execution of code at specified time
intervals.
These time intervals are called timing events.
The two key methods to use with JavaScript are:
setTimeout(function, milliseconds)
Executes a function, after waiting a specified number of milliseconds.
setInterval(function, milliseconds)
Same as setTimeout(), but repeats the execution of the function continuously.
The setTimeout() and setInterval() are both methods of the HTML
DOMWindow object.
Timers: setTimeout()
 Make something happen (once) after a fixed
delay
108
var timer = setTimeout('bang()', 5000);
clearTimeout(timer);
5 seconds after this statement
executes, this function is called
Cancels the timer
Timers: setInterval()
 Make something happen repeatedly at fixed
intervals
109
var timer = setInterval('clock()', 1000);
clearInterval(timer);
This function is called
continuously per 1 second.
Stop the timer.
Timer – Example
110
<script type="text/javascript">
function timerFunc() {
var now = new Date();
var hour = now.getHours();
var min = now.getMinutes();
var sec = now.getSeconds();
document.getElementById("clock").value =
"" + hour + ":" + min + ":" + sec;
}
setInterval('timerFunc()', 1000);
</script>
<input type="text" id="clock" />
timer-demo.html
What Are Cookies?
 Small memory-resident pieces of information sent from a server to your
computer
Cookies were invented to solve the problem "how to remember
information about the user":
When a user visits a web page, his name can be stored in a
cookie.
Next time the user visits the page, the cookie "remembers" his
name.
Cookies are saved in name-value pairs like:
username=John Doe
When a browser request a web page from a server, cookies
belonging to the page is added to the request.This way the server
gets the necessary data to "remember" information about users.
Create a Cookie with JavaScript
JavaScript can create, read, and delete cookies with
the document.cookie property.
With JavaScript, a cookie can be created like this:
document.cookie="username=John Doe";
You can also add an expiry date (in UTC time). By default, the cookie
is deleted when the browser is closed:
document.cookie="username=John Doe; expires=Thu, 18 Dec
2013 12:00:00 UTC";
With a path parameter, you can tell the browser what path the cookie
belongs to. By default, the cookie belongs to the current page.
document.cookie="username=John Doe; expires=Thu, 18 Dec
2013 12:00:00 UTC; path=/";
Read a Cookie with JavaScript
 With JavaScript, cookies can be read like this:
var x = document.cookie;
document.cookie will return all cookies in one string much like:
cookie1=value; cookie2=value; cookie3=value;
Change a Cookie with JavaScript
With JavaScript, you can change a cookie the same way as you
create it:
document.cookie="username=John Smith;
expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
The old cookie is overwritten.
Delete a Cookie with JavaScript
Deleting a cookie is very simple. Just set the
expires parameter to a passed date:
document.cookie = "username=; expires=Thu, 01 Jan 1970
00:00:00 UTC";
Note : don't have to specify a cookie value when you
delete a cookie.
A Function to Set a Cookie
First, we create a function that stores the name of
the visitor in a cookie variable:
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires; }
Example explained:
The parameters of the function above are the name of the cookie
(cname), the value of the cookie (cvalue), and the number of days
until the cookie should expire (exdays).
The function sets a cookie by adding together the cookie name,
the cookie value, and the expires string.
A Function to Get a Cookie
Then, we create a function that returns the value of a specified cookie:
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name)== 0) return c.substring(name.length,c.length); }
return "“; }
Function explained:
Take the cookiename as parameter (cname).
Create a variable (name) with the text to search for (cname + "=").
Split document.cookie on semicolons into an array called ca (ca =
document.cookie.split(';')).
Loop through the ca array (i=0;i<ca.length;i++), and read out each value c=ca[i]).
If the cookie is found (c.indexOf(name) == 0), return the value of the
cookie (c.substring(name.length,c.length). If the cookie is not found, return "".
A Function to Check a Cookie
 Last, we create the function that checks if a cookie is set.
 If the cookie is set it will display a greeting.
 If the cookie is not set, it will display a prompt box, asking for the
name of the user, and stores the username cookie for 365 days,
by calling the setCookie function:
function checkCookie() {
var username=getCookie("username");
if (username!="") {
alert("Welcome again " + username);
}else{
username = prompt("Please enter your name:", "");
if (username != "" && username != null) {
setCookie("username", username, 365); } } }
JavaScript Errors -Throw andTry to Catch
The try statement lets you test a block of code for errors.
The catch statement lets you handle the error.
The throw statement lets you create custom errors.
The finally statement lets you execute code, after try and catch,
regardless of the result.
ErrorsWill Happen!
When executing JavaScript code, different errors can occur.
Errors can be coding errors made by the programmer, errors due to
wrong input, and other unforeseeable things:
<p id="demo"></p>
<script>
try {
adddlert("Welcome guest!"); }
catch(err) {
document.getElementById("demo").innerHTML = err.message; }
</script>
JavaScript try and catch
119
The try statement allows you to define a block of code to be tested
for errors while it is being executed.
The catch statement allows you to define a block of code to be
executed, if an error occurs in the try block.
The JavaScript statements try and catch come in pairs:
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
JavaScript Basics
END

More Related Content

Similar to JavaScript lesson 1.pptx

BITM3730 10-17.pptx
BITM3730 10-17.pptxBITM3730 10-17.pptx
BITM3730 10-17.pptx
MattMarino13
 
13-IntroJavascript.pptx
13-IntroJavascript.pptx13-IntroJavascript.pptx
13-IntroJavascript.pptx
suchita74
 
13-IntroJavascript.pptx
13-IntroJavascript.pptx13-IntroJavascript.pptx
13-IntroJavascript.pptx
ssuserd695d1
 
13-IntroJavascript.pptx
13-IntroJavascript.pptx13-IntroJavascript.pptx
13-IntroJavascript.pptx
ShilpaBhojne
 
13-IntroJavascript.pptxIntroduction to java script
13-IntroJavascript.pptxIntroduction to java script13-IntroJavascript.pptxIntroduction to java script
13-IntroJavascript.pptxIntroduction to java script
gdckviksitbharat
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
Aiman Hud
 
Javascript
JavascriptJavascript
Javascript
orestJump
 
UNIT 1 (7).pptx
UNIT 1 (7).pptxUNIT 1 (7).pptx
UNIT 1 (7).pptx
DrDhivyaaCRAssistant
 
Java 17
Java 17Java 17
Java 17
Mutlu Okuducu
 
Javascript
JavascriptJavascript
Javascript
Sun Technlogies
 
Wt unit 5
Wt unit 5Wt unit 5
Wt unit 5
team11vgnt
 
FSJavaScript.ppt
FSJavaScript.pptFSJavaScript.ppt
FSJavaScript.ppt
AbhishekKumar66407
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoftch samaram
 
Javascript
JavascriptJavascript
Javascript
D V BHASKAR REDDY
 
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and ScriptingIT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
pkaviya
 
Java scripts
Java scriptsJava scripts
Java scripts
Capgemini India
 
10. session 10 loops and arrays
10. session 10   loops and arrays10. session 10   loops and arrays
10. session 10 loops and arraysPhúc Đỗ
 
MSTCCU'16 - Aspiration Webbers - Session 4 - intro. to JS
MSTCCU'16 - Aspiration Webbers - Session 4 - intro. to JSMSTCCU'16 - Aspiration Webbers - Session 4 - intro. to JS
MSTCCU'16 - Aspiration Webbers - Session 4 - intro. to JS
Moataz_Hesham
 

Similar to JavaScript lesson 1.pptx (20)

BITM3730 10-17.pptx
BITM3730 10-17.pptxBITM3730 10-17.pptx
BITM3730 10-17.pptx
 
13-IntroJavascript.pptx
13-IntroJavascript.pptx13-IntroJavascript.pptx
13-IntroJavascript.pptx
 
13-IntroJavascript.pptx
13-IntroJavascript.pptx13-IntroJavascript.pptx
13-IntroJavascript.pptx
 
13-IntroJavascript.pptx
13-IntroJavascript.pptx13-IntroJavascript.pptx
13-IntroJavascript.pptx
 
13-IntroJavascript.pptxIntroduction to java script
13-IntroJavascript.pptxIntroduction to java script13-IntroJavascript.pptxIntroduction to java script
13-IntroJavascript.pptxIntroduction to java script
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Javascript
JavascriptJavascript
Javascript
 
UNIT 1 (7).pptx
UNIT 1 (7).pptxUNIT 1 (7).pptx
UNIT 1 (7).pptx
 
Java 17
Java 17Java 17
Java 17
 
Javascript
JavascriptJavascript
Javascript
 
Wt unit 5
Wt unit 5Wt unit 5
Wt unit 5
 
FSJavaScript.ppt
FSJavaScript.pptFSJavaScript.ppt
FSJavaScript.ppt
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
 
Javascript
JavascriptJavascript
Javascript
 
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and ScriptingIT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
 
Java scripts
Java scriptsJava scripts
Java scripts
 
10. session 10 loops and arrays
10. session 10   loops and arrays10. session 10   loops and arrays
10. session 10 loops and arrays
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
JavaScript
JavaScriptJavaScript
JavaScript
 
MSTCCU'16 - Aspiration Webbers - Session 4 - intro. to JS
MSTCCU'16 - Aspiration Webbers - Session 4 - intro. to JSMSTCCU'16 - Aspiration Webbers - Session 4 - intro. to JS
MSTCCU'16 - Aspiration Webbers - Session 4 - intro. to JS
 

Recently uploaded

Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 

Recently uploaded (20)

Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 

JavaScript lesson 1.pptx

  • 2. Table of Contents  What is DHTML?  DHTMLTechnologies  HTML, CSS, JavaScript, DOM 2
  • 3. Table of Contents (2)  Introduction to JavaScript  What is JavaScript  Implementing JavaScript into Web pages  In <head> part  In <body> part  In external .js file 3
  • 4. Table of Contents (3)  JavaScript Syntax  JavaScript operators  JavaScript DataTypes  JavaScript Pop-up boxes  alert, confirm and prompt  Conditional and switch statements, loops and functions 4
  • 5. DHTML Dynamic Behavior at the Client Side
  • 6. What is DHTML?  Dynamic HTML (DHTML)  Makes possible a Web page to react and change in response to the user’s actions  DHTML = HTML + CSS + JavaScript 6 DHTML HTML CSS JavaScript DOM
  • 7. DTHML = HTML + CSS + JavaScript  HTML defines Web sites content through semantic tags (headings, paragraphs, lists, …)  CSS defines 'rules' or 'styles' for presenting every aspect of an HTML document  Font (family, size, color, weight, etc.)  Background (color, image, position, repeat)  Position and layout (of any object on the page)  JavaScript defines dynamic behavior  Programming logic for interaction with the user, to handle events, etc. 7
  • 9. JavaScript  JavaScript is a front-end scripting language developed by Netscape for dynamic content  Lightweight, but with limited capabilities  Can be used as object-oriented language  Client-side technology  Embedded in your HTML page  Interpreted by theWeb browser  Simple and flexible  Powerful to manipulate the DOM 9
  • 10. JavaScript Advantages  JavaScript allows interactivity such as:  Implementing form validation  React to user actions, e.g. handle keys  Changing an image on moving mouse over it  Sections of a page appearing and disappearing  Content loading and changing dynamically  Performing complex calculations  Custom HTML controls, e.g. scrollable table  Implementing AJAX functionality 10
  • 11. What Can JavaScript Do?  Can handle events  Can read and write HTML elements and modify the DOM tree  Can validate form data  Can access / modify browser cookies  Can be used as object-oriented language  Can handle exceptions  Can perform asynchronous server calls (AJAX) 11
  • 12. JavaScript Output 12  JavaScript Display Possibilities  JavaScript can "display" data in different ways:  Writing into an HTML element, using innerHTML.  Writing into the HTML output using document.write().  Writing into an alert box, using window.alert().  Writing into the browser console, using console.log().
  • 13. The First Script first-script.html 13 <html> <body> <script type="text/javascript"> alert('Hello JavaScript!'); </script> </body> </html>
  • 14. Another Small Example small-example.html 14 <html> <body> <script type="text/javascript"> document.write('JavaScript rulez!'); </script> </body> </html>
  • 15. Using JavaScript Code  The JavaScript code can be placed in:  <script> tag in the head  <script> tag in the body – not recommended  External files, linked via <script> tag the head  Files usually have .js extension  Highly recommended  The .js files get cached by the browser 15 <script src="scripts.js" type="text/javscript"> <!– code placed here will not be executed! --> </script>
  • 16. JavaScript – When is Executed?  JavaScript code is executed during the page loading or when the browser fires an event  All statements are executed at page loading  Some statements just define functions that can be called later  Function calls or code can be attached as "event handlers" via tag attributes  Executed when the event is fired by the browser 16 <img src="logo.gif" onclick="alert('clicked!')" />
  • 17. <html> <head> <script type="text/javascript"> function test (message) { alert(message); essa } </script> </head> <body> <img src="logo.gif" onclick="test('clicked!')" /> </body> </html> Calling a JavaScript Function from Event Handler – Example image-onclick.html 17
  • 18. Using External Script Files  Using external script files:  External JavaScript file: 18 <html> <head> <script src="sample.js" type="text/javascript"> </script> </head> <body> <button onclick="sample()" value="Call JavaScript function from sample.js" /> </body> </html> function sample() { alert('Hello from sample.js!') } external-JavaScript.html sample.js The <script> tag is always empty.
  • 20. JavaScript Syntax  The JavaScript syntax is similar to C# and Java  Operators (+, *, =, !=, &&, ++, …)  Variables (typeless)  Conditional statements (if, else)  Loops (for, while)  Arrays (my_array[]) and associative arrays (my_array['abc'])  Functions (can return value)  Function variables 20
  • 21. Variables 21  All JavaScript variables must be identified with unique names.  These unique names are called identifiers.  Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).  The general rules for constructing names for variables (unique identifiers) are:  Names can contain letters, digits, underscores, and dollar signs.  Names must begin with a letter  Names can also begin with $ and _ (but we will not use it in this tutorial)  Names are case sensitive (y and Y are different variables)  Reserved words (like JavaScript keywords) cannot be used as names
  • 22. DataTypes  JavaScript data types:  Numbers (integer, floating-point)  Boolean (true / false)  String type – string of characters  Arrays  Associative arrays (hash tables) 22 var myName = "You can use both single or double quotes for strings"; var my_array = [1, 5.3, "aaa"]; var my_hash = {a:2, b:3, c:"text"};
  • 23. Greater than <= Symbol Meaning > < Less than >= Greater than or equal to Less than or equal to == Equal != Not equal Conditional Statement (if) 23 unitPrice = 1.30; if (quantity > 100) { unitPrice = 1.20; }
  • 24. Conditional Statement (if) (2)  Very often when you write code, you want to perform diff  You can use conditional statements in your code to do this. In JavaScript we have the following conditional statements: 24 Use if to specify a block of code to be executed, if a specified condition is true Use else to specify a block of code to be executed, if the same condition is false Use else if to specify a new condition to test, if the first condition is false Use switch to specify many alternative blocks of code to be executed The if Statement syntax if (condition) { block of code to be executed if the condition is true }
  • 25. 25 Conditional Statement (else, else if) if (condition) { block of code to be executed if the condition is true } else { block of code to be executed if the condition is false } The else Statement syntax The else if Statement syntax if (condition1) { block of code to be executed if condition1 is true } else if (condition2) { block of code to be executed if the condition1 is false and condition2 is true } else { block of code to be executed if the condition1 is false and condition2 is false }
  • 26. Switch Statement  The switch statement works like in C#: 26 switch (variable) { case 1: // do something break; case 'a': // do something else break; case 3.14: // another code break; default: // something completely different } switch-statements.html
  • 27. Loops  Like in C#  for loop  while loop  do … while loop 27 var counter; for (counter=0; counter<4; counter++) { alert(counter); } while (counter < 5) { alert(++counter); } loops.html
  • 29. UsingText box 29 <FORM name="F1" path=" "> Name: <input type=“text" name=“txt1" > Class: <input type=“text" name=“txt2" > <input TYPE="button" value="CLICK" ONCLICK = "clk()"> </FORM>
  • 30. 30 <html> <head> <script language=“javascript”> function clk() { Var x=document.F1.txt1.value; Var z=document.F1.txt2.value; Document.write (“your name is”+x+”your class is “+z); } </script></head> <body> <FORM name="F1" path=" "> Name: <input type=“text" name=“txt1" > Class: <input type=“text" name=“txt2" > <input TYPE="button" value="CLICK" ONCLICK = "clk()"> </FORM></body>
  • 31. 31 UsingText box <FORM name="F1" path=" "> NO1: <input type=“text" name=“txt1" > NO2: <input type=“text" name=“txt2" > <input TYPE="button" value=“Add" ONCLICK = "clk()"> </FORM>
  • 32. 32 function clk() { Var x=document.F1.txt1.value; Var z=document.F1.txt2.value; A=ParseInt(x); B= ParseInt(z); C=A+B; Alert(c); } <FORM name="F1" path=" "> N01: <input type=“text" name=“txt1" > No2: <input type=“text" name=“txt2" > <input TYPE="button" value="CLICK" ONCLICK = "clk()"> </FORM>
  • 33. 33 Using Radio buttons <FORM name="F1" path=" "> <input type="radio" name="MS" > Single <input type="radio" name="MS" > Married <inputTYPE="button" value="CLICK" ONCLICK = "clk()"> </FORM>
  • 34. 34  function clk()  {  if ( document.F1.MS[0].checked == true )  alert ("Single");  else if ( document.F1.MS[1].checked == true )  alert ("Married");  }  <FORM name="F1" path=" ">  <input type="radio" name="MS" > Single  <input type="radio" name="MS" > Married  <input TYPE="button" value="CLICK" ONCLICK = "clk()">  </FORM>
  • 35. 35 getElementById Now we get the data from HTML elements by it’s id For this purpose we using getElementById Function Like this: document.getElementById(“ Id of HTML elements")
  • 36. 36 function clk(){ var x= document.getElementById("txt").value; alert(x); } <body> <form id="form1" name="form1" method="post" action=""> <input type="text" id="txt" name="text1" /> <input type="button" value="ok" onclick="clk()" /> </form> </body> Example:
  • 37. HTML Events 37 HTML events are "things" that happen to HTML elements. When JavaScript is used in HTML pages, JavaScript can "react" on these events. An HTML event can be something the browser does, or something a user does. Here are some examples of HTML events: • An HTML web page has finished loading • An HTML input field was changed • An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected.
  • 38. 38 HTML allows event handler attributes, with JavaScript code, to be added to HTML elements. With single quotes: <element event='some JavaScript‘> With double quotes: <element event="some JavaScript"> HTML Events.. <p>Click the button to display the date.</p> <input type = “button” onclick="displayDate()“ value =“The time is?”> <script> function displayDate() { document.getElementById("demo").innerHTML = Date(); } </script> In the following example, an onclick attribute (with code), is added to a <button> element:
  • 39. Standard Popup Boxes  Alert box with text and [OK] button  Just a message shown in a dialog box:  Confirmation box  Contains text, [OK] button and [Cancel] button:  Prompt box  Contains text, input field with default value: 39 alert("Some text here"); confirm("Are you sure?”,”defaualt text”); prompt ("enter amount", 10);
  • 40. Sum of Numbers – Example sum-of-numbers.html 40 <html> <head> <title>JavaScript Demo</title> <script type="text/javascript"> function calcSum() { value1 = parseInt(document.mainForm.textBox1.value); value2 = parseInt(document.mainForm.textBox2.value); sum = value1 + value2; document.mainForm.textBoxSum.value = sum; } </script> </head>
  • 41. Sum of Numbers – Example (2) sum-of-numbers.html (cont.) 41 <body> <form name="mainForm"> <input type="text" name="textBox1" /> <br/> <input type="text" name="textBox2" /> <br/> <input type="button" value="Process" onclick="javascript: calcSum()" /> <input type="text" name="textBoxSum" readonly="readonly"/> </form> </body> </html>
  • 42. JavaScript Prompt – Example prompt.html 42 price = prompt("Enter the price", "10.00"); alert('Price + VAT = ' + price * 1.2);
  • 43. 43 var r = confirm("Press a button"); if (r == true) { x = "You pressed OK!"; } else { x = "You pressed Cancel!"; } JavaScript Confirm– Example The window.confirm() method can be written without the window prefix. Confirmation Box A confirm box is often used if you want the user to verify or accept something. When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false. var person = prompt("Please enter your name", “Ahmad Mahmood"); if (person != null) { document.getElementById("demo").innerHTML = "Hello " + person + "! How are you today?"; } A prompt box is often used if you want the user to input a value before entering a page. When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.
  • 44. Array 44 JavaScript arrays are used to store multiple values in a single variable. var cars = ["Saab", "Volvo", "BMW"]; Definition : An array is a special variable, which can hold more than one value at a time. If a list of items (a list of car names, for example), storing the cars in single variables could look like this: var car1 = "Saab"; var car2 = "Volvo"; var car3 = "BMW"; Creating an Array Using an array literal is the easiest way to create a JavaScriptArray. Syntax: var array_name = [item1, item2, ...]; var cars = ["Saab", "Volvo", "BMW"];
  • 45. Array.. 45 Using the JavaScript Keyword new: var cars = new Array("Saab", "Volvo", "BMW"); Access the Elements of an Array: array element is accessing by referring to the index number. This statement accesses the value of the first element in cars: var name = cars[0]; Changing an Array Element: This statement changes the value of the first element in cars: cars[0] = "Opel";
  • 46. Functions  Code structure – splitting code into parts  Data comes in, processed, result returned 46 function average(a, b, c) { var total; total = a+b+c; return total/3; } Parameters come in here. Declaring variables is optional.Type is never declared. Value returned here.
  • 47. Function Arguments and ReturnValue  Functions are not required to return a value  When calling function it is not obligatory to specify all of its arguments  The function has access to all the arguments passed via arguments array 47 function sum() { var sum = 0; for (var i = 0; i < arguments.length; i ++) sum += parseInt(arguments[i]); return sum; } alert(sum(1, 2, 4)); functions-demo.html
  • 48. String Operations  The + operator joins strings  What is "9" + 9?  Converting string to number: 48 string1 = "fat "; string2 = "cats"; alert(string1 + string2); // fat cats alert("9" + 9); // 99 alert(parseInt("9") + 9); // 18
  • 49. Some string common function 49 The length property returns the number of characters that are in a string, using an integer. Below is the basic code for accessing this property. var myString = "123456"; var length = myString.length; document.write("The string is this long: " + length); Out put: The string is this long: 6 Length
  • 50. Spilt 50 The ability to split up a string into separate chunks has been supported in many programming languages, and it is available in JavaScript as well. If you have a long string like “this is computer science faculty" and want to store each name separately, you can specify the space character " " and have the split function create a new chunk every time it sees a space.
  • 51. 51 Let's start off with a little example that takes a string of numbers and splits when it sees the number 5.That means the delimiter for this example is 5. Notice that the split function returns an array that we store into mySplitResult. var myString = "123456789"; var mySplitResult = myString.split("5"); document.write("The first element is " + mySplitResult[0]); document.write("<br />The second element is " + mySplitResult[1]); Out put: The first element is 1234 The second element is 6789
  • 52. Search 52 The search() method searches a string for a specified value and returns the position of the match: var str = "Please locate where 'locate' occurs!"; var pos = str.search("locate"); Out put: 7
  • 53. 53 The most important thing to remember when creating a regular expression is that it must be surrounded with slashes /regular expression/.With that knowledge let's search a string to see if a common name “2001" is inside it. var myRegExp = /2001/; var string1 = “the computer science facultyi s established in 2001 in IUST."; var matchPos1 = string1.search(myRegExp); if(matchPos1 != -1) document.write("There was a match at position " + matchPos1); else document.write("There was no match in the first string"); Out put: There was a match at position 44 For powerful search use regular expression
  • 54. Extracting String Parts 54 There are 3 methods for extracting a part of a string: •slice(start, end) •substring(start, end) •substr(start, length)
  • 55. Slice 55 slice() extracts a part of a string and returns the extracted part in a new string. The method takes 2 parameters: the start position, and the end position (end not included). This example slices out a portion of a string from position 7 to position 12 (13-1): var str = "Apple, Banana, Kiwi"; var res = str.slice(7, 13); The result of res will be: Banana
  • 56. Slice… 56 If a parameter is negative, the position is counted from the end of the string. This example slices out a portion of a string from position -12 to position -6: var str = "Apple, Banana, Kiwi"; var res = str.slice(-12, -6); The result of res will be: Banana If you omit the second parameter, the method will slice out the rest of the string: var res = str.slice(7); var res = str.slice(-12);
  • 57. Substring 57 substring() is similar to slice(). The difference is that substring() cannot accept negative indexes. var str = "Apple, Banana, Kiwi"; var res = str.substring(7, 13); The result of res will be: Banana If you omit the second parameter, substring() will slice out the rest of the string.
  • 58. substr 58 substr() is similar to Substring(). The difference is that the second parameter specifies the length of the extracted part. var str = "Apple, Banana, Kiwi"; var res = str.substr(7, 6); The result of res will be: Banana If you omit the second parameter, substr() will slice out the rest of the string. If the first parameter is negative, the position counts from the end of the string.
  • 59. Replace 59 The replace() method replaces a specified value with another value in a string: var str = "Please visit Microsoft!"; var n = str.replace("Microsoft", "W3Schools"); Output Please visit W3Schools! By default, the replace() method replaces only the first match: var str = "Please visit Microsoft and Microsoft!"; var n = str.replace("Microsoft", "W3Schools");
  • 60. 60 Replace… By default, the replace() method is case sensitive. Writing MICROSOFT (with upper-case) will not work: var str = "Please visit Microsoft!"; var n = str.replace("MICROSOFT", "W3Schools"); To replace case insensitive, use a regular expression with an /i (insensitive): var str = "Please visit Microsoft!"; var n = str.replace(/MICROSOFT/i, "W3Schools"); To replace all matches, use a regular expression with a /g str = "Please visit Microsoft and Microsoft!"; n = str.replace(/Microsoft/g, "W3Schools");
  • 61. Index of 61 The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string: JavaScript counts positions from zero. 0 is the first position in a string, 1 is the second, 2 is the third ... The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:
  • 62. 62 var str = "Please locate where 'locate' occurs!"; var pos = str.lastIndexOf("locate"); Output 22 <script type="text/javascript"> var aURL = "http://www.tizag.com/"; var aPosition = aURL.indexOf("www"); document.write("The position of www = " + aPosition); </script > Out put: The position of www = 7 Both methods accept a second parameter as the starting position for the search: var aURL = http://www.webtizag.com/"; var aPosition = aURL.indexOf(“w", 10); document.write("The position of www = " + aPosition); The position of www = 11
  • 63. Search and IndexOf  The two methods, indexOf() and search(), are equal?  They accept the same arguments (parameters), and return the same value?  But the differences are:  The search() method cannot take a second start position argument.  The indexOf() method cannot take powerful search values (regular expressions).  We will learn more about regular expressions later. 63
  • 64. Search and IndexOf  The two methods, indexOf() and search(), are equal?  They accept the same arguments (parameters), and return the same value?  But the differences are:  The search() method cannot take a second start position argument.  The indexOf() method cannot take powerful search values (regular expressions).  We will learn more about regular expressions in a later chapter. 64
  • 65. Converting to Upper and Lower Case A string is converted to upper case with toUpperCase(): var text1 = "Hello World!"; var text2 = text1.toUpperCase(); A string is converted to lower case with toLowerCase(): var text1 = "Hello World!"; var text2 = text1.toLowerCase(); 65
  • 66. charAt and charCodeAt 66 The charAt() method returns the character at a specified index (position) in a string: var str = "HELLO WORLD"; str.charAt(0); // returns H The charCodeAt() method returns the unicode of the character at a specified index in a string. The method returns a UTF-16 code (an integer between 0 and 65535). var str = "HELLO WORLD"; str.charCodeAt(0); // returns 72
  • 67. innerHTML 67 The easiest way to get or change the content of an element is by using the innerHTML property. The innerHTML property is useful for getting or replacing the content of HTML elements. The innerHTML property can be used to get or change any HTML element, including <html> and <body>. Return the innerHTML property: HTMLElementObject.innerHTML Set the innerHTML property: HTMLElementObject.innerHTML = text
  • 68. Everything is Object  Every variable can be considered as object  For example strings and arrays have member functions: 68 var test = "some string"; alert(test[7]); // shows letter 'r' alert(test.charAt(5)); // shows letter 's' alert("test".charAt(1)); //shows letter 'e' alert("test".substring(1,3)); //shows 'es' var arr = [1,3,4]; alert (arr.length); // shows 3 arr.push(7); // appends 7 to end of array alert (arr[3]); // shows 7 objects.html
  • 69. JavaScript Objects 69 Real Life Objects, Properties, and Methods In real life, a car is an object. A car has properties like weight and color, and methods like start and stop: Object Properties Methods car.name = Fiat car.model = 500 car.weight = 850kg car.color = white car.start() car.drive() car.brake() car.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.
  • 70. JavaScript Objects… 70 Objects are variables too. But objects can contain many values. This code assigns many values (Fiat, 500, white) to a variable named car: var car = {type:“Toyota", model:"500", color:"white"}; The values are written as name:value pairs (name and value separated by a colon). Object Properties The name:values pairs (in JavaScript objects) are called properties. var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; Property PropertyValue firstName John lastName Doe age 50 eyeColor blue
  • 71. JavaScript Objects… 71 Spaces and line breaks are not important. An object definition can span multiple lines: var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; Object Definition You define (and create) a JavaScript object with an object literal: var person = { firstName:"John", lastName:"Doe", age:50, eyeColor:"blue" };
  • 72. JavaScript Objects… 72 objectName.propertyName Accessing Object Properties You can access object properties in two ways: objectName["propertyName"] <body> <p> There are two different ways to access an object property: </p> <p>You can use person.property or person["property"].</p> <p id="demo"></p> <script> var person = { firstName: "John", lastName : "Doe", id : 5566 }; document.getElementById("demo").innerHTML = person.firstName + " " + person.lastName; </script> document.getElementById("demo" ).innerHTML = person["firstName"] + " " + person["lastName"];
  • 73. HTML Document Object Model (HDOM) When a web page is loaded, the browser creates a Document Object Model of the page. The HTML DOM model is constructed as a tree of Objects:
  • 74. Document Object Model (DOM) 74 With the object model, JavaScript gets all the power it needs to create dynamic HTML: JavaScript can change all the HTML elements in the page JavaScript can change all the HTML attributes in the page JavaScript can change all the CSS styles in the page JavaScript can remove existing HTML elements and attributes JavaScript can add new HTML elements and attributes JavaScript can react to all existing HTML events in the page JavaScript can create new HTML events in the page
  • 75. 75 The DOM is a W3C (World Wide Web Consortium) standard. The DOM defines a standard for accessing documents: "TheW3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.“ The W3C DOM standard is separated into 3 different parts: Core DOM - standard model for all document types XML DOM - standard model for XML documents HTML DOM - standard model for HTML documents What is the DOM?
  • 76. What is the HDOM?  The HTML DOM is a standard object model and programming interface for HTML.  It defines: 76 The HTML elements as objects The properties of all HTML elements The methods to access all HTML elements The events for all HTML elements In other words:The HTML DOM is a standard for how to get, change, add, or delete HTML elements.
  • 77. JavaScript HTML DOM Methods  HTML DOM methods are actions you can perform (on HTML Elements).  HTML DOM properties are values (of HTML Elements) that you can set or change. 77 The DOM Programming Interface The HTML DOM can be accessed with JavaScript (and with other programming languages). In the DOM, all HTML elements are defined as objects. The programming interface is the properties and methods of each object. A property is a value that you can get or set (like changing the content of an HTML element). A method is an action you can do (like add or deleting an HTML element).
  • 78. JavaScript HTML DOM Methods… The getElementById Method  The most common way to access an HTML element is to use the id of the element. The innerHTML Property  The easiest way to get the content of an element is by using the innerHTML property.  The innerHTML property is useful for getting or replacing the content of HTML elements. 78 <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "HelloWorld!"; </script>
  • 79. JavaScript HTML DOM Documen The HTML DOM document object is the owner of all other objects in your web page. The HTML DOM Document Object  The document object represents your web page.  If you want to access any element in an HTML page, you always start with accessing the document object.  Next slide: some examples of how you can use the document object to access and manipulate HTML. 79
  • 80. 80 Finding HTML Elements Method Description document.getElementById(id) Find an element by element id document.getElementsByTagName(name) Find elements by tag name document.getElementsByClassName(name) Find elements by class name Changing HTML Elements Method Description element.innerHTML = new html content Change the inner HTML of an element element.attribute = new value Change the attribute value of an HTML element element.setAttribute(attribute, value) Change the attribute value of an HTML element element.style.property = new style Change the style of an HTML element
  • 81. Adding and Deleting Elements Method Description document.createElement(element) Create an HTML element document.removeChild(element) Remove an HTML element document.appendChild(element) Add an HTML element document.replaceChild(element) Replace an HTML element 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 Note : that you don't use the "on" prefix for the event; use "click" instead of "onclick". Syntax element.addEventListener(event, function, useCapture); The first parameter is the type of the event (like "click" or "mousedown"). The second parameter is the function we want to call when the event occurs. The third parameter is a boolean value specifying whether to use event bubbling or event capturing.This parameter is optional.
  • 82. DOM Nodes According to the W3C HTML DOM standard, everything in an HTML document is a node:  The entire document is a document node  Every HTML element is an element node  The text inside HTML elements are text nodes  Every HTML attribute is an attribute node  All comments are comment nodes 82 With the HTML DOM, all nodes in the node tree can be accessed by JavaScript. New nodes can be created, and all nodes can be modified or deleted.
  • 83. Node Relationships 83 The nodes in the node tree have a hierarchical relationship to each other. The terms parent, child, and sibling are used to describe the relationships. In a node tree, the top node is called the root (or root node) Every node has exactly one parent, except the root (which has no parent) A node can have a number of children Siblings (brothers or sisters) are nodes with the same parent <head> <title>DOMTutorial</title> </head> <body> <h1>DOM Lesson one</h1> <p>Hello world!</p> </body>
  • 84. 84 Node Relationships… From the HTML above you can read: <html> is the root node <html> has no parents <html> is the parent of <head> and <body> <head> is the first child of <html> <body> is the last child of <html> and: <head> has one child: <title> <title> has one child (a text node): "DOM Tutorial" <body> has two children: <h1> and <p> <h1> has one child: "DOM Lesson one" <p> has one child: "Hello world!" <h1> and <p> are siblings and Navigating Between Nodes You can use the following node properties to navigate between nodes with JavaScript: parentNode childNodes[nodenumber] firstChild lastChild nextSibling previousSibling Warning ! A common error in DOM processing is to expect an element node to contain text. The value of the text node can be accessed by the node's innerHTML property, or the nodeValue.
  • 85. Node Relationships… 85 Child Nodes and NodeValues In addition to the innerHTML property, you can also use the childNodes and nodeValue properties to get the content of an element. The following example collects the node value of an <h1> element and copies it into a <p> element: <script> var myText = document.getElementById("intro").childNodes[0].nodeValue; document.getElementById("demo").innerHTML = myText; </script> <h1 id="intro">My First Page</h1> <p id="demo">Hello!</p> In the example above, getElementById is a method, while childNodes and nodeValue are properties. In this tutorial we use the innerHTML property. However, learning the method above is useful for understanding the tree structure and the navigation of the DOM.
  • 86. Node Relationships…  Using the firstChild property is the same as using childNodes[0]: 86 <script> myText = document.getElementById("intro").firstChild.nodeValue; document.getElementById("demo").innerHTML = myText; </script> <h1 id="intro">My First Page</h1> <p id="demo">Hello World!</p> DOM Root Nodes There are two special properties that allow access to the full document: document.body -The body of the document document.documentElement –The full document <p>Hello World!</p> <div> <p>The DOM is very useful!</p> <p>This example demonstrates the <b>document.body</b> property.</p> </div> <script> alert(document.body.innerHTML); </script>
  • 87. Node Relationships… 87 Creating New HTML Elements (Nodes) To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element. var para = document.createElement("p"); var node = document.createTextNode("This is new."); para.appendChild(node); var element = document.getElementById("div1"); element.appendChild(para); <div id="div1"> <p id="p1">This is a paragraph.</p> <p id="p2">This is another paragraph. </p> </div> Creating new HTML Elements - insertBefore() The appendChild() method in the previous example, appended the new element as the last child of the parent. If you don't want that you can use the insertBefore() method: var element = document.getElementById("div1"); var child = document.getElementById("p1"); element.insertBefore(para,child);
  • 88. Node Relationships… 88 Removing Existing HTML Elements To remove an HTML element, you must know the parent of the element: <div id="div1"> <p id="p1">This is a paragraph.</p> <p id="p2">This is another paragraph.</p> </div> <script> var parent = document.getElementById("div1"); var child = document.getElementById("p1"); parent.removeChild(child); The method node.remove() is implemented in the DOM 4 specification. But because of poor browser support, you should not use it. Replacing HTML Elements To replace an element to the HTML DOM, use the replaceChild() method: <div id="div1"> <p id="p1">This is a paragraph.</p> <p id="p2">This is another paragraph.</p> </div> var para = document.createElement("p"); var node = document.createTextNode("This is new."); para.appendChild(node); var parent = document.getElementById("div1"); var child = document.getElementById("p1"); parent.replaceChild(para,child);
  • 90. Built-in Browser Objects  The browser provides some read-only data via:  window  The top node of the DOM tree  Represents the browser's window  document  holds information the current loaded document  screen  Holds the user’s display properties  navigtor  Holds information about the browser  History  Contain the browser history  location  Contain the current page URL 90
  • 91. DOM Hierarchy – Example 91 window navigator screen document history location form button form form
  • 92. Window Object Details  Properties  status: Specifies a temporary message that appears on the status bar on the bottom of the browser window. Browser support  location: Identifies the URL associated with a window object. It can be used to redirect the client to another URL.  document: Refers to the current document being displayed in the window. 92
  • 93. Methods of Windows object open(): Opens a new window with a specified document or opens the document in the specified named window. window.open("URL", "windowName", "featureList"); close(): Closes the current window. window.close(); alert(): Displays a message in a dialog box with an OK button. confirm(): Displays a Confirm dialog box with OK and Cancel buttons. prompt(): Displays a Prompt dialog box with a text field for entering a value, with a OK & Cancel button. blur() & focus(): Removes focus from or gives focus to a window. 93
  • 94. 94 <INPUT TYPE="button"VALUE="Open Window“ onClick = " NW = window.open (‘ ‘ , 'NewWin‘ , 'toolbar=no, status=no, width=200,height=100‘ );” > <INPUTTYPE="button"VALUE="Close Window" onClick="NW.close();" > <INPUTTYPE="button"VALUE="Close Main Window" onClick="window.close();"> Window. open example
  • 95. Window .prompt example 95 <html> <head> <script language="javascript"> document.write("This illustrates the Prompt method"); var username=prompt("What is your name?","") alert("Hello," + username + "!") </script> </head> <body> </body> </html>
  • 96. Opening New Window – Example  window.open() 96 var newWindow = window.open("", "sampleWindow", "width=300, height=100, menubar=yes, status=yes, resizable=yes"); newWindow.document.write( "<html><head><title> Sample Title</title> </head><body><h1>Sample Text</h1></body>"); newWindow.status = "Hello folks"; window-open.html
  • 97. The Navigator Object 97 alert(window.navigator.userAgent); The navigator in the browser window The userAgent (browser ID) The browser window
  • 98. Document and Location  document object  Provides some built-in arrays of specific objects on the currently loaded Web page  document.location  Used to access the currently open URL or redirect the browser 98 document.links[0].href = "yahoo.com"; document.write( "This is some <b>bold text</b>"); document.location = "http://www.yahoo.com/";
  • 99. The Screen Object  The screen object contains information about the display 99 window.moveTo(0, 0); x = screen.availWidth; y = screen.availHeight; window.resizeTo(x, y); <html> <body> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "Screen width is " + screen.width; </script> </body> </html> ScreenWidth: 1440
  • 100. Regular Expressions If you use HTML forms on your website, and want to make sure that your visitors submit valid data on those forms, you might want to consider using some regular expressions in JavaScript
  • 101. FormValidation – Example 101 function checkForm() { var valid = true; if (document.mainForm.firstName.value == "") { alert("Please type in your first name!"); document.getElementById("firstNameError"). style.display = "inline"; valid = false; } return valid; } … <form name="mainForm" onsubmit="return checkForm()"> <input type="text" name="firstName" /> … </form> form-validation.html
  • 102. Regular Expression syntax  / Escapes special characters to literal and literal characters to special  […] Match any one character between the brackets  [^…] Match any one character not between the brackets  w, W Match any wordnon-word character  s, S Match any whitespace/non-whitespace  d, D Match any digit/non-digit  ^, $ require match at beginning/end of a string or in multi-line mode, beginning/end of a line  a | b Match either a or b  + Match previous term one or more times  ^ Matches beginning of input  $ Matches end of input
  • 103. FormValidation /^[0-9]+$/ : Match values with Digits from 0 to 9 /^[1-5]+$/ : Match values with Digits from 1 to 5 /^[a-z]+$/ : Match values with alphabet from a to z (small letter) /^[A-Z]+$/ : Match values with alphabet from A to Z /^[a-z0-9]+$/ : Match values with letter and Digits /^[w-.+]+@[a-zA-Z0-9.-]+.[a-zA-z0-9]{2,4}$/ Match values with valid Email address That all use with match function
  • 104. The Math Object  The Math object provides some mathematical functions 104 for (i=1; i<=20; i++) { var x = Math.random(); x = 10*x + 1; x = Math.floor(x); document.write( "Random number (" + i + ") in range " + "1..10 --> " + x + "<br/>"); } math.html
  • 105. Math Objects  Math.PI; // returns 3.141592653589793  Math.round(4.7); // returns 5  Math.pow(8, 2); // returns 64  Math.sqrt(64); // returns 8  Math.abs(-4.7); // returns 4.7  Math.ceil(4.4); // returns 5  Math.floor(4.7); // returns 4  Math.Random(); //returns a random number between 0 (inclusive), and 1 (exclusive): 105
  • 106. The Date Object  The Date object provides date / calendar functions 106 var now = new Date(); var result = "It is now " + now; document.getElementById("timeField") .innerText = result; ... <p id="timeField"></p> dates.html
  • 107. Timing Events 107 The window object allows execution of code at specified time intervals. These time intervals are called timing events. The two key methods to use with JavaScript are: setTimeout(function, milliseconds) Executes a function, after waiting a specified number of milliseconds. setInterval(function, milliseconds) Same as setTimeout(), but repeats the execution of the function continuously. The setTimeout() and setInterval() are both methods of the HTML DOMWindow object.
  • 108. Timers: setTimeout()  Make something happen (once) after a fixed delay 108 var timer = setTimeout('bang()', 5000); clearTimeout(timer); 5 seconds after this statement executes, this function is called Cancels the timer
  • 109. Timers: setInterval()  Make something happen repeatedly at fixed intervals 109 var timer = setInterval('clock()', 1000); clearInterval(timer); This function is called continuously per 1 second. Stop the timer.
  • 110. Timer – Example 110 <script type="text/javascript"> function timerFunc() { var now = new Date(); var hour = now.getHours(); var min = now.getMinutes(); var sec = now.getSeconds(); document.getElementById("clock").value = "" + hour + ":" + min + ":" + sec; } setInterval('timerFunc()', 1000); </script> <input type="text" id="clock" /> timer-demo.html
  • 111. What Are Cookies?  Small memory-resident pieces of information sent from a server to your computer Cookies were invented to solve the problem "how to remember information about the user": When a user visits a web page, his name can be stored in a cookie. Next time the user visits the page, the cookie "remembers" his name. Cookies are saved in name-value pairs like: username=John Doe When a browser request a web page from a server, cookies belonging to the page is added to the request.This way the server gets the necessary data to "remember" information about users.
  • 112. Create a Cookie with JavaScript JavaScript can create, read, and delete cookies with the document.cookie property. With JavaScript, a cookie can be created like this: document.cookie="username=John Doe"; You can also add an expiry date (in UTC time). By default, the cookie is deleted when the browser is closed: document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC"; With a path parameter, you can tell the browser what path the cookie belongs to. By default, the cookie belongs to the current page. document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
  • 113. Read a Cookie with JavaScript  With JavaScript, cookies can be read like this: var x = document.cookie; document.cookie will return all cookies in one string much like: cookie1=value; cookie2=value; cookie3=value; Change a Cookie with JavaScript With JavaScript, you can change a cookie the same way as you create it: document.cookie="username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/"; The old cookie is overwritten.
  • 114. Delete a Cookie with JavaScript Deleting a cookie is very simple. Just set the expires parameter to a passed date: document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC"; Note : don't have to specify a cookie value when you delete a cookie.
  • 115. A Function to Set a Cookie First, we create a function that stores the name of the visitor in a cookie variable: function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires="+d.toUTCString(); document.cookie = cname + "=" + cvalue + "; " + expires; } Example explained: The parameters of the function above are the name of the cookie (cname), the value of the cookie (cvalue), and the number of days until the cookie should expire (exdays). The function sets a cookie by adding together the cookie name, the cookie value, and the expires string.
  • 116. A Function to Get a Cookie Then, we create a function that returns the value of a specified cookie: function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1); if (c.indexOf(name)== 0) return c.substring(name.length,c.length); } return "“; } Function explained: Take the cookiename as parameter (cname). Create a variable (name) with the text to search for (cname + "="). Split document.cookie on semicolons into an array called ca (ca = document.cookie.split(';')). Loop through the ca array (i=0;i<ca.length;i++), and read out each value c=ca[i]). If the cookie is found (c.indexOf(name) == 0), return the value of the cookie (c.substring(name.length,c.length). If the cookie is not found, return "".
  • 117. A Function to Check a Cookie  Last, we create the function that checks if a cookie is set.  If the cookie is set it will display a greeting.  If the cookie is not set, it will display a prompt box, asking for the name of the user, and stores the username cookie for 365 days, by calling the setCookie function: function checkCookie() { var username=getCookie("username"); if (username!="") { alert("Welcome again " + username); }else{ username = prompt("Please enter your name:", ""); if (username != "" && username != null) { setCookie("username", username, 365); } } }
  • 118. JavaScript Errors -Throw andTry to Catch The try statement lets you test a block of code for errors. The catch statement lets you handle the error. The throw statement lets you create custom errors. The finally statement lets you execute code, after try and catch, regardless of the result. ErrorsWill Happen! When executing JavaScript code, different errors can occur. Errors can be coding errors made by the programmer, errors due to wrong input, and other unforeseeable things: <p id="demo"></p> <script> try { adddlert("Welcome guest!"); } catch(err) { document.getElementById("demo").innerHTML = err.message; } </script>
  • 119. JavaScript try and catch 119 The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block. The JavaScript statements try and catch come in pairs: try { Block of code to try } catch(err) { Block of code to handle errors }