SlideShare a Scribd company logo
JAVASCRIPT
ORIGINS
 JavaScript, which was developed by Netscape, was
originally named Mocha but soon was renamed LiveScript.
 In late 1995 LiveScript became a joint venture of Netscape
and Sun Microsystems, and its name again was changed,
this time to JavaScript.
 A language standard for JavaScript was developed in the
late 1990s by the European Computer Manufacturers
Association (ECMA) as ECMA-262.
 The official name of the standard language is ECMAScript.
ORIGINS
 JavaScript can be divided into three parts: the core, client
side, and server side.
 The core is the heart of the language, including its
operators, expressions, statements, and subprograms.
 Client-side JavaScript is a collection of objects that support
the control of a browser and interactions with users.
 Server-side JavaScript is a collection of objects that make
the language useful on a Web server.
JAVASCRIPT AND JAVA
JAVA JAVASCRIPT
Java is programming language JavaScript is a scripting language
It is strongly typed language It is dynamically typed language
Types are known at compile time Compile time type checking is
impossible
Objects in java are static JavaScript objects are dynamic
Collection of data members and
methods is fixed at compile time
The number of data members and
methods of an object can change during
execution
Object oriented programming language Object based language
USES OF JAVASCRIPT
 The JavaScript was initially introduced to provide
programming capability at both the server and client ends of
web connection
 The client side JavaScript is embedded in XHTML
documents and is interpreted by the browser.
 Interactions with users through form elements (buttons,
textboxes etc.).
 client side JavaScript cannot replace serves side JavaScript;
because server side software supports file operations,
database access, security, networking etc
 JavaScript is also used as an alternative to java applets.
 JavaScript support DOM [Document Object Model] which
enables JavaScript to access and modify CSS properties
and content of any element of a displayed XHTML document
EVENT-DRIVEN COMPUTATION OF JAVASCRIPT
 In JavaScript, the actions are often executed in response to
actions of the users of documents like mouse clicks and
form submissions.
 This form of computation supports user interactions through
the XHTML form elements on the client display
 One of the common uses of JavaScript is to check the
values provided in forms by users to determine whether the
values are sensible.
BROWSERS AND XHTML/JAVASCRIPT DOCUMENTS
 When a JavaScript script is encountered in the document, the
browser uses its JavaScript interpreter to “execute” the script.
 Output from the script becomes the next markup to be rendered.
 When the end of the script is reached, the browser goes back to
reading the XHTML document and displaying its content.
 There are two different ways to embed JavaScript in an XHTML
document: implicitly and explicitly.
 In explicit embedding, the JavaScript code physically resides in
the XHTML document.
 The JavaScript can be placed in its own file, separate from the
XHTML document. This approach, called implicit embedding, has
the advantage of hiding the script from the browser user.
 When JavaScript scripts are explicitly embedded, they can
appear in either part of an XHTML document—the head or the
body—depending on the purpose of the script.
OBJECT ORIENTATION AND JAVASCRIPT
 JavaScript is an object-based language
 It supports prototype-based inheritance
 Without class-based inheritance, JavaScript cannot support
polymorphism.
 A polymorphic variable can reference related methods of
objects of different classes within the same class hierarchy
JAVASCRIPT OBJECTS
 In JavaScript, objects are collections of properties, which
correspond to the members of classes in Java and C++.
 Each property is either a data property or a function or
method property.
 Data properties appear in two categories: primitive values
and references to other objects.
GENERAL SYNTACTIC CHARACTERISTICS
 Scripts can appear directly as the content of a <script>
tag.
 The type attribute of <script> must be set to
“text/javascript”.
 Eg: <script type=“text/javascript>
…………………………
…………………
</script>
 The JavaScript script can be indirectly embedded in an
XHTML document with the src attribute of a <script> tag,
whose value is the name of a file that contains the script—
for example,
Eg:
<script type = “text/javascript” src = “tst_number.js” > </script>
GENERAL SYNTACTIC CHARACTERISTICS
 In JavaScript, identifiers, or names, must begin with a letter,
an underscore ( _ ), or a dollar sign ($). Subsequent
characters may be letters, underscores, dollar signs, or
digits. There is no length limitation for identifiers.
 JavaScript has 25 reserved words
 In addition, JavaScript has a large collection of predefined
words, including alert, open, java, and self.
GENERAL SYNTACTIC CHARACTERISTICS
 JavaScript has two forms of comments, both of which are used in other
languages.
 The XHTML comment used to hide JavaScript uses the normal
beginning syntax, <!--
 The following XHTML comment form hides the enclosed script from
browsers that do not have JavaScript interpreters, but makes it visible
to browsers that do support JavaScript:
 The use of semicolons in JavaScript is unusual.
GENERAL SYNTACTIC CHARACTERISTICS
PRIMITIVES, OPERATIONS, AND EXPRESSIONS
 JavaScript has five primitive types: Number, String, Boolean,
Undefined, and Null.
 JavaScript includes predefined objects that are closely related to the
Number, String, and Boolean types, named Number, String, and
Boolean, respectively.
 These objects are called wrapper objects.
 The purpose of the wrapper objects is to provide properties and
methods that are convenient for use with values of the primitive types.
 The difference between primitives and objects is shown in the following
example.
NUMERIC AND STRING LITERALS
 All numeric literals are values of type Number. The Number type values
are represented internally in double-precision floating-point form.
 Floating-point literals can have decimal points, exponents, or both.
 The following are valid numeric literals:
72 7.2 .72 72. 7E2 7e2 .7e2 7.e2 7.2E-2
 Integer literals can be written in hexadecimal form by preceding their first
digit with either 0x or 0X.
 A string literal is a sequence of zero or more characters delimited by
either single quotes (‘) or double quotes (“).
 String literals can include characters specified with escape sequences,
such as n and t.
OTHER PRIMITIVE TYPES
 The only value of type Null is the reserved word null, which
indicates no value.
 The only value of type Undefined is undefined.
 The only values of type Boolean are true and false.
DECLARING VARIABLES
 A variable can be declared either by assigning it a value, in
which case the interpreter implicitly declares it to be a
variable, or by listing it in a declaration statement that
begins with the reserved word var. Initial values can be
included in a var declaration, as with some of the variables
in the following declaration:
 A variable that has been declared but not assigned a value,
has the value undefined.
NUMERIC OPERATORS
 JavaScript has the typical collection of numeric operators: the binary
operators + for addition, - for subtraction, * for multiplication, / for
division, and % for modulus.
 The unary operators are plus (+), negate (-), decrement (--), and
increment (++). The increment and decrement operators can be either
prefix or postfix.
 All numeric operations are done in double-precision floating point.
 The precedence rules of a language specify which operator is evaluated
first when two operators with different precedence are adjacent in an
expression.
 The associativity rules of a language specify which operator is evaluated
first when two operators with the same precedence are adjacent in an
expression
THE MATH OBJECT
 The Math object provides a collection of properties of
Number objects and methods that operate on Number
objects. The Math object has methods for the trigonometric
functions, such as sin (for sine) and cos (for cosine), as well
as for other commonly used mathematical operations.
 Among these are floor, to truncate a number; round, to
round a number; and max, to return the largest of two given
numbers.
 Ex: Math.sin(x)
 Math.sqrt(x)
THE NUMBER OBJECT
 The Number object includes a collection of useful properties
that have constant values.
 The Number object has a method, toString
 The toString method converts the number through which it is
called to a string
Property Meaning
MAX_VALUE Largest representable
number
MIN_VALUE Smallest representable
number
NaN Not a number
POSITIVE_INFINITY Special value to represent
infinity
NEGATIVE_INFINITY Special value to represent
negative infinity
PI The value of 𝜋
THE STRING CATENATION OPERATOR
 Var first=“Brijesh”
 Name=first + “ Patel”
IMPLICIT TYPE CONVERSIONS
 The JavaScript interpreter performs several different implicit
type conversions. Such conversions are called coercions.
 If either operand of a + operator is a string, the operator is
interpreted as a string catenation operator. If the other
operand is not a string, it is coerced to a string.
 Example1: “August ” + 1977
“August 1997”
Example2: 7 * “3”
21 & will not be evaluated as string
EXPLICIT TYPE CONVERSIONS
 Strings that contain numbers can be converted to numbers
with the String constructor.
var str_value = String(value);
 This conversion could also be done with the toString
method, which has the advantage that it can be given a
parameter to specify the base of the resulting number.
var num = 6;
var str_value = num.toString(); //the result is “6” var
str_value_binary = num.toString(2); //the result is “110”
 A number also can be converted to a string by catenating it
with the empty string.
var str_value = num+””
EXPLICIT TYPE CONVERSIONS
 String can be explicitly converted to numbers in a variety of
ways.
 Number constructor
 var number = Number(aString);
 Var number=aString – 0;
 Javascript has two predefine functions to convert string to
number
 parseInt();
 parseFloat();
STRING PROPERTIES AND METHODS
 The String object includes one property, length, and a large
collection of methods.
 Consider, var str = “George”;
str.charAt(2) is ‘o’
str.indexOf(‘r’) is 3
str.substring(2, 4) is ‘org’
str.toLowerCase() is ‘george’
THE TYPEOF OPERATOR
 The typeof operator returns the type of its single operand.
 typeof produces “number”, “string”, or “boolean” if the
operand is of primitive type Number, String, or Boolean,
respectively.
 If the operand is an object or null, typeof produces “object”.
 If the operand is a variable that has not been assigned a
value, typeof produces “undefined”, reflecting the fact that
variables themselves are not typed.
 Notice that the typeof operator always returns a string.
 The operand for typeof can be placed in parentheses,
making it appear to be a function.
 Therefore, typeof x and typeof(x) are equivalent.
THE DATE OBJECT
 A Date object is created with the new operator and the Date
constructor, which has several forms.
 var today = new Date();
 Table shows the methods, along with the descriptions, that retrieve
information from a Date object.
SCREEN OUTPUT AND KEYBOARD INPUT
 JavaScript models the XHTML document with the Document object.
 The window in which the browser displays an XHTML document is
modelled with the Window object.
 The Window object includes two properties, document and window.
 The document property refers to the Document object.
 The window property is self-referential; it refers to the Window object.
 write is used to create XHTML code, the only useful punctuation in its
parameter is in the form of XHTML tags. Therefore, the parameter of
write often includes <br />.
 The writeln method implicitly adds “n” to its parameter, but since
browsers ignore line breaks when displaying XHTML, it has no effect on
the output.
 The parameter of write can include any XHTML tags and content.
 The write method actually can take any number of parameters.
 Multiple parameters are concatenated and placed in the output.
 Example: document.write(“The result is: ”, result, “<br />”);
SCREEN OUTPUT AND KEYBOARD INPUT
 There are 3 types of pop-up boxes:
 Alert
 Confirm
 Prompt
 The alert method opens a dialog window and displays its parameter in
that window. It also displays an OK button.
 alert(“The sum is:” + sum + “n”);
SCREEN OUTPUT AND KEYBOARD INPUT
 The confirm method opens a dialog window in which the method
displays its string parameter, along with two buttons: OK and Cancel.
 confirm returns a Boolean value that indicates the user’s button input:
true for OK and false for Cancel. This method is often used to offer the
user the choice of continuing some process.
 var question = confirm(“Do you want to continue this download?”);
SCREEN OUTPUT AND KEYBOARD INPUT
 The prompt method creates a dialog window that contains a text box
used to collect a string of input from the user, which prompt returns as
its value.
CONTROL STATEMENTS
 lists the relational operators.
CONTROL STATEMENTS
 SELECTION STATEMENTS
 The selection statements (if-then and if-then-else) of JavaScript are similar to those of
the common programming languages.
 THE switch STATEMENT
CONTROL STATEMENTS
 LOOP STATEMENTS
 Syntax of while:
while(Control Expression)
statement or compound statement
 Syntax of for:
for(initial expression; control expression; increment expression)
Statement or compound statements
o JavaScript includes one more loop statement, the for-in statement, which is
most often used with objects.
for(identifier in object)
Statement or compound statement
OBJECT CREATION AND MODIFICATION
 Objects are often created with a new expression, which
must include a call to a constructor method.
var my_object = new Object(); //creates an object that has no properties:
 The number of members of a class in a typical object-
oriented language is fixed at compile time. The number of
properties in a JavaScript object is dynamic.
 A property for an object is created by assigning a value to
that property’s name.
 var my_car = {make: “Ford”, model: “SVT”};
 Properties can be accessed in two ways.
 var prop1 = my_car.make;
 var prop2 = my_car[“make”];
OBJECT CREATION AND MODIFICATION
 A property can be deleted with delete
 delete my_car.model;
 JavaScript has a loop statement, for-in, that is perfect for
listing the properties of an object.
 Array elements are accessed as in Java: var first = new Ar[0];
 Can be multi-dimensional as in Java
 .length property gives the current length
 = the highest subscript to which a value has been assigned + 1, or
the initial size, whichever is larger
 Can be read or written
 Arrays are not fixed in length
 By setting new array elements using an index beyond the current
length, or by setting the length property to a larger value you extend
the array (very much NOT like Java)
 By setting the length property to a smaller value you shrink the array
 Space is not reserved for each element, only those defined
(assigned)
var a = new Array(5); // all are undefined
a[100] = 2; // has only 1 defined
37
Arrays
 JS has arrays which look like Java arrays
 Standard variable names to reference Array objects
 Indexed with [ ]
 JS arrays are objects!
 Can be created with new keyword
var newAr = new Array(“one”, “two”, “three”, 4);
var newAr = new Array(3);
 1st way creates and initializes array (> 1 argument)
 2nd way just sets size (1 int argument)
 Can also be created with array literal
var newAr = [“one”, 2, “three”];
 Note the square brackets, not braces
 Note that values of different data types can be mixed
38
Arrays
 Array with non-numeric indices
 Also called a hash
 Created as Object and filled using index value
var myHash = new Object();
myHash[“me”] = “Instructor”;
myHash[“you”] = “Student”;
for (var i in myHash)
alert (i + "-" + myHash[i]);
39
Associative Arrays
demoArrays.html
 Flexibility of arrays allows many methods; var list = [2, 4, 6, 8,
10]
 slice() – returns part of an array: list.slice(1,3) => array [4, 6]
 concat( ) – concatenates new elements to the end of the array; returns
new array: list.concat(12) => [2, 4, 6, 8, 10, 12]
 join( ) – creates a string from the array elements, separated by
commas (or specified delimiter): list.join(“ : ”) => “2 : 4 : 6 : 8: 10”
 reverse( ) – reverses order of the array elements; affects calling array
 sort( ) – converts elements to strings, sorts them alphabetically (or you
can specify another order as a function); affects calling array
 push( ), pop( ) – add/delete elements to the high end of array
 unshift( ), shift( ) – add/delete elements at the beginning of the array
40
Arrays
FUNCTIONS
 A function header consists of the reserved word function, the function’s
name, and a parenthesized list of parameters if there are any.
 A return statement returns control from the function in which it appears
to the function’s caller.
 LOCAL VARIABLES
 Variables that are implicitly declared have global scope
 Any variable explicitly declared with var in the body of a function has
local scope.
 PARAMETERS
 The parameter values that appear in a call to a function are called
actual parameters.
 parameters in calls to the function, are called formal parameters.
 Example:
function greet(hour, name)
 {
if(hour < 12)
document.write(“Good morning, “+name);
else if(hour < 18)
document.write(“Good afternoon, “+name);
else if(hour < 24)
document.write(“Good evening, “+name);
else return false;
}
42
Functions
 CONSTRUCTORS
 JavaScript constructors are special methods that
create and initialize the properties of newly created
objects.
 Every new expression must include a call to a
constructor whose name is the same as that of the
object being created.
 Constructors are actually called by the new operator,
which immediately precedes them in the new
expression.
 Obviously, a constructor must be able to reference the
object on which it is to operate. JavaScript has a
predefined reference variable for this purpose, named
this.
 When the constructor is called, this is a reference to
the newly created object. The this variable is used to
construct and initialize the properties of the object.
 For example, the constructor
 could be used as in the following statement: my_car = new
car(“Ford”, “Contour SVT”, “2000”);
 For example, suppose you wanted a method for car objects
that listed the property values. A function that could serve as
such a method could be written as follows:
 The following line must then be added to the car
constructor:
 this.display = display_car;
 Now the call my_car.display() will produce the following
output
THE DOCUMENT OBJECT MODEL
 The DOM is an application programming interface (API) that
defines an interface between XHTML documents and
application programs.
 It is an abstract model because it must apply to a variety of
application programming languages.
 Each language that interfaces with the DOM must define a
binding to that interface.
 The actual DOM specification consists of a collection of
interfaces, including one for each document tree node type.
 They define the objects, methods, and properties that are
associated with their respective node types.
 With the DOM, users can write code in programming
languages to create documents, move around in their
structures, and change, add, or delete elements and their
content.
 Documents in the DOM have a treelike structure, but there
can be more than one tree in a document.
chap04.ppt
In the JavaScript binding to the DOM, the elements of a document are objects,
with both data and operations.
The data are called properties, and the operations are, naturally, called
methods.
Example: <input type = “text” name = “address”>
ELEMENT ACCESS IN JAVASCRIPT
• There are several ways the object associated with an XHTML form element
can be addressed in JavaScript. The original (DOM 0) way is to use the forms
and elements arrays of the Document object, which is referenced through the
document property of the Window object.
The DOM address of the button in this example, using the forms and elements
arrays, is as follows:
var dom = document.forms[0].elements[0];
ELEMENT ACCESS IN JAVASCRIPT
Using the name attributes, the button’s DOM address is as follows:
var dom = document.myForm.turnItOn;
One drawback of this approach is that the XHTML 1.1 standard does not allow the
name attribute in the form element, even though the attribute is now valid for form
elements.
Hence, alternatively we use,
var dom = document.getElementById(“turnItOn”);
EVENTS AND EVENT HANDLING
 One important use of JavaScript for Web programming is to detect
certain activities of the browser and the browser user and provide
computation when those activities occur. These computations are
specified with a special form of programming called event-driven
programming.
 An event is a notification that something specific has occurred, either
with the browser, such as the completion of the loading of a document, or
because of a browser user action, such as a mouse click on a form
button.
 An event handler is a script that is implicitly executed in response to the
appearance of an event.
 Events are created by activities associated with specific XHTML
elements.
 The process of connecting an event handler to an event is called
registration.
EVENTS, ATTRIBUTES, AND TAGS
EVENTS, ATTRIBUTES, AND TAGS
EVENTS, ATTRIBUTES, AND TAGS
REGISTER AN EVENT HANDLER
 As mentioned previously, there are two ways to register an event handler in
the DOM 0 event model. One of these is by assigning the event handler
script to an event tag attribute, as in the following example:
 In many cases, the handler consists of more than a single statement. In
these cases, often a function is used and the literal string value of the
attribute is the call to the function. Consider the example of a button element:
 An event handler function could also be registered by assigning its name to
the associated event property on the button object, as in the following
example:
HANDLING EVENTS FROM BODY ELEMENTS
 The events most often created by body elements are load and unload.
HANDLING EVENTS FROM BUTTON ELEMENTS
 Buttons in a Web document provide an effective
way to collect simple input from the browser user.
Example: //radio_click.html <html> <head> <title>
radio_click.html</title> <script type =
"text/javascript" src = "radio_click.js"> </script>
</head> <body> <h4> Choose your favourite
Director in Kannada Film Industry</h4> <form id =
"myForm" action = " ">
<p>
<label><input type = "radio" name = "dButton" value = "1" onclick = "dChoice(1)"/>
Yogaraj Bhat</label><br/>
<label><input type = "radio" name = "dButton" value = "2" onclick = "dChoice(2)"/>
Suri</label><br/> <label><input type = "radio" name = "dButton" value = "3"
onclick = "dChoice(3)"/> Guru Prasad</label><br/>
<label><input type = "radio" name = "dButton" value = "4" onclick = "dChoice(4)"/>
Prakash</label> </p> </form> </body> </html> //radio_click.js function
dChoice(ch)
{
switch(ch)
{
case 1: alert("Mungaaru Male"); break;
case 2: alert("Duniya"); break;
case 3: alert("Eddelu Manjunatha"); break;
case 4: alert("Milana"); break;
default: alert("Ooops..Invalid choice :O"); break;
}
}
chap04.ppt
HANDLING EVENTS FROM TEXT BOX AND PASSWORD ELEMENTS
Text boxes and passwords can create four different events: blur, focus,
change, and select.
chap04.ppt
chap04.ppt
chap04.ppt
chap04.ppt

More Related Content

PPT
Javascript
PPTX
WT Unit-3 PPT.pptx
PPT
data-types-operators-datatypes-operators.ppt
PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
PDF
JavaScript Programming
PPTX
javascript
PDF
8 introduction to_java_script
PPT
An introduction to javascript
Javascript
WT Unit-3 PPT.pptx
data-types-operators-datatypes-operators.ppt
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
JavaScript Programming
javascript
8 introduction to_java_script
An introduction to javascript

Similar to chap04.ppt (20)

PPTX
Java script
PPTX
Java script
PDF
javascriptPresentation.pdf
PPTX
copa-ii.pptx
PPT
introduction to javascript concepts .ppt
PPTX
Lecture 5 javascript
PPTX
javascript client side scripting la.pptx
PPTX
Unit 3-Javascript.pptx
PPTX
JavaScript_III.pptx
PPT
13665449.ppt
PPTX
Basics of Javascript
PPTX
JavaScript Lecture notes.pptx
PPT
fundamentals of JavaScript for students.ppt
PPT
Basics of Javascript
PPTX
Java script
PDF
Client sidescripting javascript
PDF
JavaScript Getting Started
PPTX
Javascript
PPT
JavaScript - An Introduction
DOCX
Java script
Java script
javascriptPresentation.pdf
copa-ii.pptx
introduction to javascript concepts .ppt
Lecture 5 javascript
javascript client side scripting la.pptx
Unit 3-Javascript.pptx
JavaScript_III.pptx
13665449.ppt
Basics of Javascript
JavaScript Lecture notes.pptx
fundamentals of JavaScript for students.ppt
Basics of Javascript
Java script
Client sidescripting javascript
JavaScript Getting Started
Javascript
JavaScript - An Introduction
Ad

More from Varsha Uchagaonkar (6)

PPT
Introduction to XML.ppt
PPTX
wpsession15.pptx
PPTX
wpsession9.pptx
PPTX
wptoolbox.pptx
PPT
Introduction to XML.ppt
Introduction to XML.ppt
wpsession15.pptx
wpsession9.pptx
wptoolbox.pptx
Introduction to XML.ppt
Ad

Recently uploaded (20)

PPTX
EDP Competencies-types, process, explanation
PDF
Chalkpiece Annual Report from 2019 To 2025
PPTX
LITERATURE CASE STUDY DESIGN SEMESTER 5.pptx
PDF
Introduction-to-World-Schools-format-guide.pdf
PPTX
CLASS_11_BUSINESS_STUDIES_PPT_CHAPTER_1_Business_Trade_Commerce.pptx
PPTX
YV PROFILE PROJECTS PROFILE PRES. DESIGN
PPTX
An introduction to AI in research and reference management
PDF
The Basics of Presentation Design eBook by VerdanaBold
PDF
YOW2022-BNE-MinimalViableArchitecture.pdf
PPTX
iec ppt- ppt on iec pulmonary rehabilitation 1.pptx
PPT
robotS AND ROBOTICSOF HUMANS AND MACHINES
PPTX
Media And Information Literacy for Grade 12
PPT
Machine printing techniques and plangi dyeing
PPTX
Tenders & Contracts Works _ Services Afzal.pptx
PPTX
Complete Guide to Microsoft PowerPoint 2019 – Features, Tools, and Tips"
PDF
GSH-Vicky1-Complete-Plans on Housing.pdf
PPTX
HPE Aruba-master-icon-library_052722.pptx
PDF
SOUND-NOTE-ARCHITECT-MOHIUDDIN AKHAND SMUCT
PDF
Quality Control Management for RMG, Level- 4, Certificate
PDF
Emailing DDDX-MBCaEiB.pdf DDD_Europe_2022_Intro_to_Context_Mapping_pdf-165590...
EDP Competencies-types, process, explanation
Chalkpiece Annual Report from 2019 To 2025
LITERATURE CASE STUDY DESIGN SEMESTER 5.pptx
Introduction-to-World-Schools-format-guide.pdf
CLASS_11_BUSINESS_STUDIES_PPT_CHAPTER_1_Business_Trade_Commerce.pptx
YV PROFILE PROJECTS PROFILE PRES. DESIGN
An introduction to AI in research and reference management
The Basics of Presentation Design eBook by VerdanaBold
YOW2022-BNE-MinimalViableArchitecture.pdf
iec ppt- ppt on iec pulmonary rehabilitation 1.pptx
robotS AND ROBOTICSOF HUMANS AND MACHINES
Media And Information Literacy for Grade 12
Machine printing techniques and plangi dyeing
Tenders & Contracts Works _ Services Afzal.pptx
Complete Guide to Microsoft PowerPoint 2019 – Features, Tools, and Tips"
GSH-Vicky1-Complete-Plans on Housing.pdf
HPE Aruba-master-icon-library_052722.pptx
SOUND-NOTE-ARCHITECT-MOHIUDDIN AKHAND SMUCT
Quality Control Management for RMG, Level- 4, Certificate
Emailing DDDX-MBCaEiB.pdf DDD_Europe_2022_Intro_to_Context_Mapping_pdf-165590...

chap04.ppt

  • 2. ORIGINS  JavaScript, which was developed by Netscape, was originally named Mocha but soon was renamed LiveScript.  In late 1995 LiveScript became a joint venture of Netscape and Sun Microsystems, and its name again was changed, this time to JavaScript.  A language standard for JavaScript was developed in the late 1990s by the European Computer Manufacturers Association (ECMA) as ECMA-262.  The official name of the standard language is ECMAScript.
  • 3. ORIGINS  JavaScript can be divided into three parts: the core, client side, and server side.  The core is the heart of the language, including its operators, expressions, statements, and subprograms.  Client-side JavaScript is a collection of objects that support the control of a browser and interactions with users.  Server-side JavaScript is a collection of objects that make the language useful on a Web server.
  • 4. JAVASCRIPT AND JAVA JAVA JAVASCRIPT Java is programming language JavaScript is a scripting language It is strongly typed language It is dynamically typed language Types are known at compile time Compile time type checking is impossible Objects in java are static JavaScript objects are dynamic Collection of data members and methods is fixed at compile time The number of data members and methods of an object can change during execution Object oriented programming language Object based language
  • 5. USES OF JAVASCRIPT  The JavaScript was initially introduced to provide programming capability at both the server and client ends of web connection  The client side JavaScript is embedded in XHTML documents and is interpreted by the browser.  Interactions with users through form elements (buttons, textboxes etc.).  client side JavaScript cannot replace serves side JavaScript; because server side software supports file operations, database access, security, networking etc  JavaScript is also used as an alternative to java applets.  JavaScript support DOM [Document Object Model] which enables JavaScript to access and modify CSS properties and content of any element of a displayed XHTML document
  • 6. EVENT-DRIVEN COMPUTATION OF JAVASCRIPT  In JavaScript, the actions are often executed in response to actions of the users of documents like mouse clicks and form submissions.  This form of computation supports user interactions through the XHTML form elements on the client display  One of the common uses of JavaScript is to check the values provided in forms by users to determine whether the values are sensible.
  • 7. BROWSERS AND XHTML/JAVASCRIPT DOCUMENTS  When a JavaScript script is encountered in the document, the browser uses its JavaScript interpreter to “execute” the script.  Output from the script becomes the next markup to be rendered.  When the end of the script is reached, the browser goes back to reading the XHTML document and displaying its content.  There are two different ways to embed JavaScript in an XHTML document: implicitly and explicitly.  In explicit embedding, the JavaScript code physically resides in the XHTML document.  The JavaScript can be placed in its own file, separate from the XHTML document. This approach, called implicit embedding, has the advantage of hiding the script from the browser user.  When JavaScript scripts are explicitly embedded, they can appear in either part of an XHTML document—the head or the body—depending on the purpose of the script.
  • 8. OBJECT ORIENTATION AND JAVASCRIPT  JavaScript is an object-based language  It supports prototype-based inheritance  Without class-based inheritance, JavaScript cannot support polymorphism.  A polymorphic variable can reference related methods of objects of different classes within the same class hierarchy
  • 9. JAVASCRIPT OBJECTS  In JavaScript, objects are collections of properties, which correspond to the members of classes in Java and C++.  Each property is either a data property or a function or method property.  Data properties appear in two categories: primitive values and references to other objects.
  • 10. GENERAL SYNTACTIC CHARACTERISTICS  Scripts can appear directly as the content of a <script> tag.  The type attribute of <script> must be set to “text/javascript”.  Eg: <script type=“text/javascript> ………………………… ………………… </script>  The JavaScript script can be indirectly embedded in an XHTML document with the src attribute of a <script> tag, whose value is the name of a file that contains the script— for example, Eg: <script type = “text/javascript” src = “tst_number.js” > </script>
  • 11. GENERAL SYNTACTIC CHARACTERISTICS  In JavaScript, identifiers, or names, must begin with a letter, an underscore ( _ ), or a dollar sign ($). Subsequent characters may be letters, underscores, dollar signs, or digits. There is no length limitation for identifiers.  JavaScript has 25 reserved words  In addition, JavaScript has a large collection of predefined words, including alert, open, java, and self.
  • 12. GENERAL SYNTACTIC CHARACTERISTICS  JavaScript has two forms of comments, both of which are used in other languages.  The XHTML comment used to hide JavaScript uses the normal beginning syntax, <!--  The following XHTML comment form hides the enclosed script from browsers that do not have JavaScript interpreters, but makes it visible to browsers that do support JavaScript:  The use of semicolons in JavaScript is unusual.
  • 14. PRIMITIVES, OPERATIONS, AND EXPRESSIONS  JavaScript has five primitive types: Number, String, Boolean, Undefined, and Null.  JavaScript includes predefined objects that are closely related to the Number, String, and Boolean types, named Number, String, and Boolean, respectively.  These objects are called wrapper objects.  The purpose of the wrapper objects is to provide properties and methods that are convenient for use with values of the primitive types.  The difference between primitives and objects is shown in the following example.
  • 15. NUMERIC AND STRING LITERALS  All numeric literals are values of type Number. The Number type values are represented internally in double-precision floating-point form.  Floating-point literals can have decimal points, exponents, or both.  The following are valid numeric literals: 72 7.2 .72 72. 7E2 7e2 .7e2 7.e2 7.2E-2  Integer literals can be written in hexadecimal form by preceding their first digit with either 0x or 0X.  A string literal is a sequence of zero or more characters delimited by either single quotes (‘) or double quotes (“).  String literals can include characters specified with escape sequences, such as n and t.
  • 16. OTHER PRIMITIVE TYPES  The only value of type Null is the reserved word null, which indicates no value.  The only value of type Undefined is undefined.  The only values of type Boolean are true and false.
  • 17. DECLARING VARIABLES  A variable can be declared either by assigning it a value, in which case the interpreter implicitly declares it to be a variable, or by listing it in a declaration statement that begins with the reserved word var. Initial values can be included in a var declaration, as with some of the variables in the following declaration:  A variable that has been declared but not assigned a value, has the value undefined.
  • 18. NUMERIC OPERATORS  JavaScript has the typical collection of numeric operators: the binary operators + for addition, - for subtraction, * for multiplication, / for division, and % for modulus.  The unary operators are plus (+), negate (-), decrement (--), and increment (++). The increment and decrement operators can be either prefix or postfix.  All numeric operations are done in double-precision floating point.  The precedence rules of a language specify which operator is evaluated first when two operators with different precedence are adjacent in an expression.  The associativity rules of a language specify which operator is evaluated first when two operators with the same precedence are adjacent in an expression
  • 19. THE MATH OBJECT  The Math object provides a collection of properties of Number objects and methods that operate on Number objects. The Math object has methods for the trigonometric functions, such as sin (for sine) and cos (for cosine), as well as for other commonly used mathematical operations.  Among these are floor, to truncate a number; round, to round a number; and max, to return the largest of two given numbers.  Ex: Math.sin(x)  Math.sqrt(x)
  • 20. THE NUMBER OBJECT  The Number object includes a collection of useful properties that have constant values.  The Number object has a method, toString  The toString method converts the number through which it is called to a string Property Meaning MAX_VALUE Largest representable number MIN_VALUE Smallest representable number NaN Not a number POSITIVE_INFINITY Special value to represent infinity NEGATIVE_INFINITY Special value to represent negative infinity PI The value of 𝜋
  • 21. THE STRING CATENATION OPERATOR  Var first=“Brijesh”  Name=first + “ Patel”
  • 22. IMPLICIT TYPE CONVERSIONS  The JavaScript interpreter performs several different implicit type conversions. Such conversions are called coercions.  If either operand of a + operator is a string, the operator is interpreted as a string catenation operator. If the other operand is not a string, it is coerced to a string.  Example1: “August ” + 1977 “August 1997” Example2: 7 * “3” 21 & will not be evaluated as string
  • 23. EXPLICIT TYPE CONVERSIONS  Strings that contain numbers can be converted to numbers with the String constructor. var str_value = String(value);  This conversion could also be done with the toString method, which has the advantage that it can be given a parameter to specify the base of the resulting number. var num = 6; var str_value = num.toString(); //the result is “6” var str_value_binary = num.toString(2); //the result is “110”  A number also can be converted to a string by catenating it with the empty string. var str_value = num+””
  • 24. EXPLICIT TYPE CONVERSIONS  String can be explicitly converted to numbers in a variety of ways.  Number constructor  var number = Number(aString);  Var number=aString – 0;  Javascript has two predefine functions to convert string to number  parseInt();  parseFloat();
  • 25. STRING PROPERTIES AND METHODS  The String object includes one property, length, and a large collection of methods.  Consider, var str = “George”; str.charAt(2) is ‘o’ str.indexOf(‘r’) is 3 str.substring(2, 4) is ‘org’ str.toLowerCase() is ‘george’
  • 26. THE TYPEOF OPERATOR  The typeof operator returns the type of its single operand.  typeof produces “number”, “string”, or “boolean” if the operand is of primitive type Number, String, or Boolean, respectively.  If the operand is an object or null, typeof produces “object”.  If the operand is a variable that has not been assigned a value, typeof produces “undefined”, reflecting the fact that variables themselves are not typed.  Notice that the typeof operator always returns a string.  The operand for typeof can be placed in parentheses, making it appear to be a function.  Therefore, typeof x and typeof(x) are equivalent.
  • 27. THE DATE OBJECT  A Date object is created with the new operator and the Date constructor, which has several forms.  var today = new Date();  Table shows the methods, along with the descriptions, that retrieve information from a Date object.
  • 28. SCREEN OUTPUT AND KEYBOARD INPUT  JavaScript models the XHTML document with the Document object.  The window in which the browser displays an XHTML document is modelled with the Window object.  The Window object includes two properties, document and window.  The document property refers to the Document object.  The window property is self-referential; it refers to the Window object.  write is used to create XHTML code, the only useful punctuation in its parameter is in the form of XHTML tags. Therefore, the parameter of write often includes <br />.  The writeln method implicitly adds “n” to its parameter, but since browsers ignore line breaks when displaying XHTML, it has no effect on the output.  The parameter of write can include any XHTML tags and content.  The write method actually can take any number of parameters.  Multiple parameters are concatenated and placed in the output.  Example: document.write(“The result is: ”, result, “<br />”);
  • 29. SCREEN OUTPUT AND KEYBOARD INPUT  There are 3 types of pop-up boxes:  Alert  Confirm  Prompt  The alert method opens a dialog window and displays its parameter in that window. It also displays an OK button.  alert(“The sum is:” + sum + “n”);
  • 30. SCREEN OUTPUT AND KEYBOARD INPUT  The confirm method opens a dialog window in which the method displays its string parameter, along with two buttons: OK and Cancel.  confirm returns a Boolean value that indicates the user’s button input: true for OK and false for Cancel. This method is often used to offer the user the choice of continuing some process.  var question = confirm(“Do you want to continue this download?”);
  • 31. SCREEN OUTPUT AND KEYBOARD INPUT  The prompt method creates a dialog window that contains a text box used to collect a string of input from the user, which prompt returns as its value.
  • 32. CONTROL STATEMENTS  lists the relational operators.
  • 33. CONTROL STATEMENTS  SELECTION STATEMENTS  The selection statements (if-then and if-then-else) of JavaScript are similar to those of the common programming languages.  THE switch STATEMENT
  • 34. CONTROL STATEMENTS  LOOP STATEMENTS  Syntax of while: while(Control Expression) statement or compound statement  Syntax of for: for(initial expression; control expression; increment expression) Statement or compound statements o JavaScript includes one more loop statement, the for-in statement, which is most often used with objects. for(identifier in object) Statement or compound statement
  • 35. OBJECT CREATION AND MODIFICATION  Objects are often created with a new expression, which must include a call to a constructor method. var my_object = new Object(); //creates an object that has no properties:  The number of members of a class in a typical object- oriented language is fixed at compile time. The number of properties in a JavaScript object is dynamic.  A property for an object is created by assigning a value to that property’s name.  var my_car = {make: “Ford”, model: “SVT”};  Properties can be accessed in two ways.  var prop1 = my_car.make;  var prop2 = my_car[“make”];
  • 36. OBJECT CREATION AND MODIFICATION  A property can be deleted with delete  delete my_car.model;  JavaScript has a loop statement, for-in, that is perfect for listing the properties of an object.
  • 37.  Array elements are accessed as in Java: var first = new Ar[0];  Can be multi-dimensional as in Java  .length property gives the current length  = the highest subscript to which a value has been assigned + 1, or the initial size, whichever is larger  Can be read or written  Arrays are not fixed in length  By setting new array elements using an index beyond the current length, or by setting the length property to a larger value you extend the array (very much NOT like Java)  By setting the length property to a smaller value you shrink the array  Space is not reserved for each element, only those defined (assigned) var a = new Array(5); // all are undefined a[100] = 2; // has only 1 defined 37 Arrays
  • 38.  JS has arrays which look like Java arrays  Standard variable names to reference Array objects  Indexed with [ ]  JS arrays are objects!  Can be created with new keyword var newAr = new Array(“one”, “two”, “three”, 4); var newAr = new Array(3);  1st way creates and initializes array (> 1 argument)  2nd way just sets size (1 int argument)  Can also be created with array literal var newAr = [“one”, 2, “three”];  Note the square brackets, not braces  Note that values of different data types can be mixed 38 Arrays
  • 39.  Array with non-numeric indices  Also called a hash  Created as Object and filled using index value var myHash = new Object(); myHash[“me”] = “Instructor”; myHash[“you”] = “Student”; for (var i in myHash) alert (i + "-" + myHash[i]); 39 Associative Arrays demoArrays.html
  • 40.  Flexibility of arrays allows many methods; var list = [2, 4, 6, 8, 10]  slice() – returns part of an array: list.slice(1,3) => array [4, 6]  concat( ) – concatenates new elements to the end of the array; returns new array: list.concat(12) => [2, 4, 6, 8, 10, 12]  join( ) – creates a string from the array elements, separated by commas (or specified delimiter): list.join(“ : ”) => “2 : 4 : 6 : 8: 10”  reverse( ) – reverses order of the array elements; affects calling array  sort( ) – converts elements to strings, sorts them alphabetically (or you can specify another order as a function); affects calling array  push( ), pop( ) – add/delete elements to the high end of array  unshift( ), shift( ) – add/delete elements at the beginning of the array 40 Arrays
  • 41. FUNCTIONS  A function header consists of the reserved word function, the function’s name, and a parenthesized list of parameters if there are any.  A return statement returns control from the function in which it appears to the function’s caller.  LOCAL VARIABLES  Variables that are implicitly declared have global scope  Any variable explicitly declared with var in the body of a function has local scope.  PARAMETERS  The parameter values that appear in a call to a function are called actual parameters.  parameters in calls to the function, are called formal parameters.
  • 42.  Example: function greet(hour, name)  { if(hour < 12) document.write(“Good morning, “+name); else if(hour < 18) document.write(“Good afternoon, “+name); else if(hour < 24) document.write(“Good evening, “+name); else return false; } 42 Functions
  • 43.  CONSTRUCTORS  JavaScript constructors are special methods that create and initialize the properties of newly created objects.  Every new expression must include a call to a constructor whose name is the same as that of the object being created.  Constructors are actually called by the new operator, which immediately precedes them in the new expression.  Obviously, a constructor must be able to reference the object on which it is to operate. JavaScript has a predefined reference variable for this purpose, named this.  When the constructor is called, this is a reference to the newly created object. The this variable is used to construct and initialize the properties of the object.  For example, the constructor
  • 44.  could be used as in the following statement: my_car = new car(“Ford”, “Contour SVT”, “2000”);  For example, suppose you wanted a method for car objects that listed the property values. A function that could serve as such a method could be written as follows:  The following line must then be added to the car constructor:  this.display = display_car;  Now the call my_car.display() will produce the following output
  • 45. THE DOCUMENT OBJECT MODEL  The DOM is an application programming interface (API) that defines an interface between XHTML documents and application programs.  It is an abstract model because it must apply to a variety of application programming languages.  Each language that interfaces with the DOM must define a binding to that interface.  The actual DOM specification consists of a collection of interfaces, including one for each document tree node type.  They define the objects, methods, and properties that are associated with their respective node types.  With the DOM, users can write code in programming languages to create documents, move around in their structures, and change, add, or delete elements and their content.  Documents in the DOM have a treelike structure, but there can be more than one tree in a document.
  • 47. In the JavaScript binding to the DOM, the elements of a document are objects, with both data and operations. The data are called properties, and the operations are, naturally, called methods. Example: <input type = “text” name = “address”> ELEMENT ACCESS IN JAVASCRIPT • There are several ways the object associated with an XHTML form element can be addressed in JavaScript. The original (DOM 0) way is to use the forms and elements arrays of the Document object, which is referenced through the document property of the Window object. The DOM address of the button in this example, using the forms and elements arrays, is as follows: var dom = document.forms[0].elements[0];
  • 48. ELEMENT ACCESS IN JAVASCRIPT Using the name attributes, the button’s DOM address is as follows: var dom = document.myForm.turnItOn; One drawback of this approach is that the XHTML 1.1 standard does not allow the name attribute in the form element, even though the attribute is now valid for form elements. Hence, alternatively we use, var dom = document.getElementById(“turnItOn”);
  • 49. EVENTS AND EVENT HANDLING  One important use of JavaScript for Web programming is to detect certain activities of the browser and the browser user and provide computation when those activities occur. These computations are specified with a special form of programming called event-driven programming.  An event is a notification that something specific has occurred, either with the browser, such as the completion of the loading of a document, or because of a browser user action, such as a mouse click on a form button.  An event handler is a script that is implicitly executed in response to the appearance of an event.  Events are created by activities associated with specific XHTML elements.  The process of connecting an event handler to an event is called registration.
  • 53. REGISTER AN EVENT HANDLER  As mentioned previously, there are two ways to register an event handler in the DOM 0 event model. One of these is by assigning the event handler script to an event tag attribute, as in the following example:  In many cases, the handler consists of more than a single statement. In these cases, often a function is used and the literal string value of the attribute is the call to the function. Consider the example of a button element:  An event handler function could also be registered by assigning its name to the associated event property on the button object, as in the following example:
  • 54. HANDLING EVENTS FROM BODY ELEMENTS  The events most often created by body elements are load and unload.
  • 55. HANDLING EVENTS FROM BUTTON ELEMENTS  Buttons in a Web document provide an effective way to collect simple input from the browser user. Example: //radio_click.html <html> <head> <title> radio_click.html</title> <script type = "text/javascript" src = "radio_click.js"> </script> </head> <body> <h4> Choose your favourite Director in Kannada Film Industry</h4> <form id = "myForm" action = " ">
  • 56. <p> <label><input type = "radio" name = "dButton" value = "1" onclick = "dChoice(1)"/> Yogaraj Bhat</label><br/> <label><input type = "radio" name = "dButton" value = "2" onclick = "dChoice(2)"/> Suri</label><br/> <label><input type = "radio" name = "dButton" value = "3" onclick = "dChoice(3)"/> Guru Prasad</label><br/> <label><input type = "radio" name = "dButton" value = "4" onclick = "dChoice(4)"/> Prakash</label> </p> </form> </body> </html> //radio_click.js function dChoice(ch) { switch(ch) { case 1: alert("Mungaaru Male"); break; case 2: alert("Duniya"); break; case 3: alert("Eddelu Manjunatha"); break; case 4: alert("Milana"); break; default: alert("Ooops..Invalid choice :O"); break; } }
  • 58. HANDLING EVENTS FROM TEXT BOX AND PASSWORD ELEMENTS Text boxes and passwords can create four different events: blur, focus, change, and select.