JavaScript FaaDoOEngineers.com FaaDoOEngineers.com.

Slides:



Advertisements
Similar presentations
Introducing JavaScript
Advertisements

Sue Wills July Objects The JavaScript language is completely centered around objects, and because of this, it is known as an Object Oriented Programming.
Java Script Session1 INTRODUCTION.
Introduction to JavaScript
1 CSC 551: Web Programming Spring 2004 client-side programming with JavaScript  scripts vs. programs  JavaScript vs. JScript vs. VBScript  common tasks.
The Web Warrior Guide to Web Design Technologies
MSc. Publishing on WWW JavaScript. What is JavaScript? A scripting language devised by Netscape Adds functionality to web pages by: Embedding code into.
Tutorial 10 Programming with JavaScript
XP 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial 10.
Information Technology Center Hany Abdelwahab Computer Specialist.
CS 299 – Web Programming and Design Overview of JavaScript and DOM Instructor: Dr. Fang (Daisy) Tang.
XP Tutorial 1 New Perspectives on JavaScript, Comprehensive1 Introducing JavaScript Hiding Addresses from Spammers.
Introduction to JavaScript. Aim To enable you to write you first JavaScript.
Javascript and the Web Whys and Hows of Javascript.
DHTML. What is DHTML?  DHTML is the combination of several built-in browser features in fourth generation browsers that enable a web page to be more.
JavaScript Teppo Räisänen LIIKE/OAMK HTML, CSS, JavaScript HTML defines the structure CSS defines the layout JavaScript is used for scripting It.
Introduction to JavaScript Dr. John P. Abraham University of Texas – Pan American.
CS346 - Javascript 1, 21 Module 1 Introduction to JavaScript CS346.
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
JavaScript Defined DOM (Document Object Model) General Syntax Body vs. Head Variables Math & Logic Selection Functions & Events Loops Animation Getting.
Advanced Web Design Scripting Tutorial Chapters. Scripting Intro The scripting part of the forthcoming Advanced Web Design textbook introduces you to.
SEG3210 DHTML Tutorial. DHTML DHTML is a combination of technologies used to create dynamic and interactive Web sites. –HTML - For creating text and image.
Bridges To Computing General Information: This document was created for use in the "Bridges to Computing" project of Brooklyn College. You are invited.
SYST Web Technologies SYST Web Technologies Lesson 6 – Intro to JavaScript.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
© 2000 – All Rights Reserved - Page 1 Introduction to JavaScript Programming Part Two.
DHTML: Dynamic HTML Internet Technology1. What is DHTML? A collection of enhancements to HTML ► To create dynamic and interactive websites Combination.
1 rfXcel Confidential Copyright 2007 Web Technology JavaScript 12/10/07.
JSP Java Server Pages Softsmith Infotech.
SEG3210 DHTML Tutorial. DHTML DHTML is a combination of technologies used to create dynamic and interactive Web sites. –HTML - For creating text and image.
Client Scripting1 Internet Systems Design. Client Scripting2 n “A scripting language is a programming language that is used to manipulate, customize,
What is Java Script? An extension to HTML. An extension to HTML. Allows authors to incorporate some functionality in their web pages. (without using CGI.
Javascript. Outline Introduction Fundamental of JavaScript Javascript events management DOM and Dynamic HTML (DHTML)
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
1 JavaScript in Context. Server-Side Programming.
TUTORIAL 10: PROGRAMMING WITH JAVASCRIPT Session 2: What is JavaScript?
Tutorial 10 Programming with JavaScript. XP Objectives Learn the history of JavaScript Create a script element Understand basic JavaScript syntax Write.
Tutorial 10 Programming with JavaScript
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
Introduction.  The scripting language most often used for client-side web development.  Influenced by many programming languages, easier for nonprogrammers.
JavaScript Syntax, how to use it in a HTML document
Overview of Form and Javascript fundamentals. Brief matching exercise 1. This is the software that allows a user to access and view HTML documents 2.
JavaScript Introduction.  JavaScript is a scripting language  A scripting language is a lightweight programming language  A JavaScript can be inserted.
1 JavaScript in Context. Server-Side Programming.
JavaScript Defined DOM (Document Object Model) General Syntax Body vs. Head Variables Math & Logic Selection Functions & Events Loops Animation Getting.
JavaScript Overview Developer Essentials How to Code Language Constructs The DOM concept- API, (use W3C model) Objects –properties Methods Events Applications;
CIS 3.5 Lecture 2.3 "Introduction to JavaScript".
Tutorial 10 Programming with JavaScript. 2New Perspectives on HTML, XHTML, and XML, Comprehensive, 3rd Edition Objectives Learn the history of JavaScript.
Tutorial 10 Programming with JavaScript. 2New Perspectives on HTML, XHTML, and XML, Comprehensive, 3rd Edition Objectives Learn the history of JavaScript.
1 CSC160 Chapter 1: Introduction to JavaScript Chapter 2: Placing JavaScript in an HTML File.
Javascript Basic Concepts Presentation By: Er. Sunny Chanday Lecturer CSE/IT RBIENT.
JavaScript and Ajax (JavaScript Environment) Week 6 Web site:
COM621: Advanced Interactive Web Development Lecture 5 – JavaScript.
Introduction to.
Module 1 Introduction to JavaScript
Applied Component I Unit II Introduction of java-script
Tutorial 10 Programming with JavaScript
JavaScript is a programming language designed for Web pages.
4. Javascript Pemrograman Web I Program Studi Teknik Informatika
JavaScript an introduction.
DHTML Javascript Internet Technology.
DHTML Javascript Internet Technology.
Introduction to JavaScript
Tutorial 10 Programming with JavaScript
Tutorial 10: Programming with javascript
JavaScript Basics What is JavaScript?
JavaScript is a scripting language designed for Web pages by Netscape.
An Introduction to JavaScript
Introduction to Programming and JavaScript
Presentation transcript:

JavaScript FaaDoOEngineers.com FaaDoOEngineers.com

Objectives Introduction to JavaScript Introduction to JavaScript programming language Using Script tag Inserting Java Script into tags Linking Java Script from separate files JavaScript expression and Operators Defining and naming variables Data Types Expression Operators – Arithmetic, String, Logical, Assignment, typeof FaaDoOEngineers.com

Objectives (Contd.) Functions and Flow Control Flow Control If…else For loops while loops Break and continue statements Using JavaScript functions Built in functions User defined functions Returning values from functions Events, Event Handlers FaaDoOEngineers.com

Objectives (Contd.) Objects and Arrays Properties and Methods Browser Object Hierarchy Addressing Objects Creating Objects Objects and Variables External Objects Security Implications Arrays and Objects FaaDoOEngineers.com

Objectives (Contd.) Document Object Model Introduction to DOM The Navigator Object The Window Object Communicating between windows Working With Frames in the DOM The Document object The Location & History Object Image Object Link Object FaaDoOEngineers.com

Objectives (Contd.) Form Validation The Form Object Model Recap of Form Elements Form Tag Events Controlling Submission Forms as Navigation List Events Buttons Text Processing FaaDoOEngineers.com

Objectives (Contd.) Cookies Introduction to HTTP Cookies Formatting Cookies Persisting Cookies Cookie Security JavaScript & Cookies Reading / Writing Cookies Modifying and deleting Cookies FaaDoOEngineers.com

Introduction To JavaScript FaaDoOEngineers.com FaaDoOEngineers.com

Introduction to Java Scripts What is JavaScript??? JavaScript is a scripting Language created by Netscape Scripting Language is a lightweight programming language. Scripting Languages are not needed to be compiled. The language is interpreted at runtime. What is a Scripting Language??? JavaScript is a simple scripting language invented specifically for use in web browsers to make websites more dynamic. On its own, HTML is capable of outputting more-or-less static pages. Once you load them up your view doesn't change much until you click a link to go to a new page. Adding JavaScript to your code allows you to change how the document looks completely, from changing text, to changing colours, to changing the options available in a drop-down list (and much, much more!). FaaDoOEngineers.com

Introduction to JavaScript (Contd.) A JavaScript is usually directly embedded in an HTML page. External JavaScripts can be created which can be used by HTML pages. JavaScript adds interactivity to HTML pages. JavaScript's are integrated into the browsing environment. JavaScripts are integrated into the browsing environment, which means they can get information about the browser and HTML page, and modify this information, thus changing how things are presented on your screen. This access to information gives JavaScript great power to modify the browsing experience. They can also react to events, such as when the user clicks their mouse, or points to a certain page element. This is also a very powerful ability. JavaScript is supported by Netscape 2+, Internet Explorer 3+, Opera 3+ and most of the other modern web browsers. Each new version of the main browsers has supported new generations of JavaScript commands, each more complex than the last. FaaDoOEngineers.com

Introduction to JavaScript (Contd.) Java is a programming language which requires compilation and interpretation. Java is used to make large scale applications. JavaScript is a scripting language which just requires interpretation. The script is some set of commands which the browser interprets. JavaScript is used to add interactivity in HTML Pages. Is JavaScript same as Java??? The two share many similarities. Most prominent of these is that they are both forms of Object-Oriented Programming, or OOP. This means that you work with small objects that are combined together to form larger objects . Both Java and Java Scripts share similar coding syntaxes. FaaDoOEngineers.com

Types of JavaScript Client-Side JavaScript (CSJS) -- an extended version of JavaScript that enables the enhancement and manipulation of web pages and client browsers. Server-Side JavaScript (SSJS) -- an extended version of JavaScript that enables back-end access to databases, file systems, and servers. Core JavaScript -- the base JavaScript language. The Course here deals with CSJS and Core JavaScript FaaDoOEngineers.com

Core JavaScript Core JavaScript encompasses all of the statements, operators, objects, and functions that make up the basic JavaScript language. The following objects are part of core JavaScript: array date math number string Originally called LiveScript, JavaScript is a cross-platform, object-oriented scripting language created by Brendan Eich of Netscape. As you can see, core JavaScript contains objects that are applicable to both client and server. If you know core JavaScript, you can easily write client-side and server-side JavaScript. Again, the only distinction is that client-side and server-side JavaScript have additional objects and functions that you can use that are specific to client-side or server-side functionality. Any JavaScript libraries (.js files) you create in core JavaScript can be used on both the client and the server with no changes whatsoever. FaaDoOEngineers.com

Client Side Java Scripting CSJS is composed of core JavaScript and many additional objects, such as the following: document form frame window Navigator History Client-Side JavaScript (CSJS) is the single most popular language on the Internet, used in major web pages which are too numerous to be counted The objects in CSJS enable you to manipulate HTML documents (checking form fields, submitting forms, creating dynamic pages, and such) and the browser itself (directing the browser to load other HTML pages, display messages, and so on). FaaDoOEngineers.com

Server Side JavaScript SSJS is composed of core JavaScript and additional objects and functions for accessing databases and file systems, sending e-mail, and so on. SSJS enables developers to quickly and easily create database-driven web applications by leveraging their existing knowledge of JavaScript. It's used to create and/or customize server-based applications by scripting the interaction between objects. SSJS is included with the Netscape Enterprise Server and is ideal for creating web applications that can be run on any platform, on any browser, and in any language. Why create something in Visual Basic or PowerBuilder that can be run on only one platform, when you can create a web application with SSJS that can be run on any existing platform (such as UNIX, Mac, and Windows) and even future platforms (like BEOS)? SSJS is also available in the Actra line of E-Commerce applications from Netscape, so that customers can customize their applications. The objects employed in the Actra implementation of SSJS are different from those used on the Enterprise Server because the data access engines are different. However, the core language is the same. For more info http://www.devarticles.com/c/a/JavaScript/Client-side-and-Server-side-JavaScript/3/ FaaDoOEngineers.com

Uses of JavaScript (Client Side) Menus for Navigation Form Validation Popup Windows Password Protecting Math Functions Special effects with document and background Status bar manipulation Messages Mouse Cursor Effects Links FaaDoOEngineers.com

Test Your Understanding ________________ is an extended version of JavaScript that enables the enhancement and manipulation of web pages and client browsers Client Side JavaScript Server Side JavaScript Core JavaScript FaaDoOEngineers.com

Test Your Understanding ________________ is an extended version of JavaScript that enables the enhancement and manipulation of web pages and client browsers Client Side JavaScript Server Side JavaScript Core JavaScript FaaDoOEngineers.com

Syntax rules of JavaScript Statements may or may not contain a semicolon at the end. Multiple statements on one line must be separated by a semicolon. JavaScript is case sensitive. FaaDoOEngineers.com

Using <script> tag The HTML <script> tag is used to enter JavaScript into a HTML. The <script> tag can be embedded within <head> tag. <body> tag. JavaScript in the head section will be executed when called. JavaScript in the body section will be executed while the HTML page is loaded. Unlimited number of JavaScript’s can be placed both in head and body section in a HTML document. JavaScripts in a page will be executed immediately while the page loads into the browser. This is not always what we want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event. FaaDoOEngineers.com

Using <script> tag Eg: <html> <head><title>Example</title> </head> <body> <script type="text/javascript"> document.write("Hello World!") </script> </body> </html> By entering the document.write command between the <script type="text/javascript"> and </script> tags, the browser will recognize it as a JavaScript command and execute the code line. In this case the browser will write Hello World! to the page: If we had not entered the <script> tag, the browser would have treated the document.write("Hello World!") command as pure text, and just write the entire line on the page. Is a standard command for writing output to a page FaaDoOEngineers.com

How to Handle Older Browsers Browsers that do not support JavaScript will display the script as it is. Use the HTML comment tag to prevent this. Eg. <script type="text/javascript"> <!-- document.write("Hello World!") // --> </script> The two forward slashes at the end of comment line (//) are a JavaScript comment symbol. This prevents the JavaScript compiler from compiling the line. FaaDoOEngineers.com

Using an External JavaScript A JavaScript can be written in an external file, which can be used by different HTML pages. The external script cannot contain the <script> tag. The external file needs to end with the .js extension. FaaDoOEngineers.com

Using External JavaScript (contd.) <html> <head><title>Example</title> </head> <body> <script src="External.js"> </script>> <p > This line has been written in the html page!!! </p> </body> </html> JavaScript.html document.write("This line has been writen in the External JavaScript!!!") External.js FaaDoOEngineers.com

Test Your Understanding Select the Correct Statement/s <script></script> is embedded within <head> </head> <script></script is embedded within <body></body> <script></script> is embedded within <title></title> FaaDoOEngineers.com

Test Your Understanding Select the Correct Statement/s <script></script> is embedded within <head> </head> <script></script is embedded within <body></body> <script></script> is embedded within <title></title> FaaDoOEngineers.com

JavaScript Operators & Expressions FaaDoOEngineers.com FaaDoOEngineers.com

JavaScript Variables and expression A variable is a symbolic name that represents some data in the memory. A variable value can change during the execution of the JavaScript. A variable can be referred by its name to see or change its value. Variables are name are case sensitive. Must begin with a letter or underscore. Variables in Javascript behave the same as variables in most popular programming languages (C, C++, etc) except that you don't have to declare variables before you use them. FaaDoOEngineers.com

Rules of a Variable Variable Declaration Variables can be declared using the var statement var <variable name>=some value Variables can also be created without using var statement <variable name>=some value Eg var firstname=“Samuel” OR firstname=“Samuel” FaaDoOEngineers.com

Data Type in JavaScript JavaScript is a loosely typed language. Loosely Typed?? Data Type of Variable need not be specified during declaration. Data types are automatically converted during script execution. FaaDoOEngineers.com

Data Type in JavaScript (contd.) JavaScript recognizes the following type of values: Values numbers boolean 9, 3.56 string true or false null Samuel, ”Samuel J Palmisano” A Special keyword which refers to nothing FaaDoOEngineers.com

Data Type in JavaScript (contd.) You can insert quotation marks inside strings by preceding them with a backslash. This is known as escaping the quotation marks. For example, var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service." document.write(quote) To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path c:\temp to a string, use the following: var home = "c:\\temp" You can declare a variable as: var x=“hi” x=30 The value type can be changed for a variable. Though this is not considered to be good programming. FaaDoOEngineers.com

JavaScript Operators Operators Conditional Arithmetic Assignment String Comparison typeof Logical FaaDoOEngineers.com

JavaScript Operator (contd.) Arithmetic FaaDoOEngineers.com

JavaScript Operator (contd.) Comparison FaaDoOEngineers.com

JavaScript Operator (contd.) Assignment FaaDoOEngineers.com

JavaScript Operator (contd.) Logical FaaDoOEngineers.com

JavaScript Operator (contd.) String FaaDoOEngineers.com

JavaScript Operator (contd.) Conditional FaaDoOEngineers.com

JavaScript Operator (contd.) typeof The "typeof" operator in JavaScript allows you to probe the data type of its operand, such as whether a variable is string, numeric, or even undefined. The below simple example alerts the data type of the variable "myvar" This special operator is helpful when troubleshooting. It reveals the type of data a variable or literal you are working with is, or the type of data an expression evaluates to. This is important because the type of data you are working with dictates how you are allowed to manipulate that data. Sometimes you will need to convert a type of data to another type, so it is helpful to be able to test the type of a value or expression at different stages of execution in your script. Used in concert with the alert method, an alert box indicating the data type is generated, helping you trouble shoot a problematic script. FaaDoOEngineers.com

Test Your Understanding x=20 x=“Test” typeof(x) evaluates to number string null FaaDoOEngineers.com

Test Your Understanding x=20 x=“Test” typeof(x) evaluates to number string null FaaDoOEngineers.com

Flow Control & Functions FaaDoOEngineers.com FaaDoOEngineers.com

Flow Control Conditional Statements if statement - use this statement if you want to execute some code only if a specified condition is true. if...else statement - use this statement if you want to execute some code if the condition is true and another code if the condition is false. if...else if....else statement - use this statement if you want to select one of many blocks of code to be executed. switch statement - use this statement if you want to select one of many blocks of code to be executed. Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. FaaDoOEngineers.com

while statement FaaDoOEngineers.com

break and continue Statements There are two special statements that can be used inside loops: break. continue. Break The break command will break the loop and continue executing the code that follows after the loop (if any). Continue The continue command will break the current loop and continue with the next value. FaaDoOEngineers.com

Example of break statement <html> <body> <script type="text/javascript"> var i=0 for (i=0;i<=5;i++) { if (i==3){break} document.write("The number is " + i) document.write("<br />") } </script> </body> </html> Result The number is 0 The number is 1 The number is 2 FaaDoOEngineers.com

Example of continue statement <html> <body> <script type="text/javascript"> var i=0 for (i=0;i<=5;i++) { if (i==3){continue} document.write("The number is " + i) document.write("<br />") } </script> </body> </html> Result The number is 0 The number is 1 The number is 2 The number is 4 The number is 5 FaaDoOEngineers.com

For loop The for Loop The for loop is used when you know in advance how many times the script should run FaaDoOEngineers.com

Functions A function is a reusable piece of code that will be executed when called for. A function can be called from anywhere from within the page or even from other pages if the function is stored in an external JavaScript (.js) file. Functions can be embedded in the <head></head> and within the<body> </body> tag. To assure that the function is read/loaded by the browser before it is called, it could be wise to put it in the <head> section. FaaDoOEngineers.com

Predefined functions in JavaScript DialogBoxes alert( message) Displays an alert box with a message defined by the string message. Eg. alert(“An Error Occurred!”) FaaDoOEngineers.com

Predefined functions in JavaScript (contd.) confirm(message) When called, it will display the message and two boxes. One box is "OK" and the other is "Cancel". If OK is selected, a value of true is returned, otherwise a value of false is returned. Eg. confirm(“Do you wish to Continue?”) FaaDoOEngineers.com

Predefined functions in JavaScript (contd.) prompt(message) Displays a box with the message passed to the function displayed. The user can then enter text in the prompt field, and choose OK or Cancel. If the user chooses Cancel, a NULL value is returned. If the user chooses OK, the string value entered in the field is returned. Eg: prompt(“enter your Name”) FaaDoOEngineers.com

Predefined functions in JavaScript (contd.) Conversion Functions eval(string) Converts a string to an integer or a float value. Eg x=“20” y=eval(x)+10 y contains the value 30 Eval() It can also evaluate expressions included with a string. In the example, value1 becomes 62. value1 = eval("124/2") , FaaDoOEngineers.com

Predefined functions in JavaScript (contd.) isNaN(value) If the value passed is not a number then a boolean value of true is returned else the boolean value of false is returned. Eg x=“Samuel” y=isNaN(x) The value stored in y is true FaaDoOEngineers.com

Predefined functions in JavaScript (contd.) parseInt(string) Converts a string to an integer returning the first integer encountered which is contained in the string. Eg x=77AB67 y=parseInt(x) y stores the value 77 If x=AB77 parseInt(x) will return NAN If x=67.7hj76 Parseint(x) will return 67 the floating point will not be taken into consideration FaaDoOEngineers.com

Predefined functions in JavaScript (contd.) parseFloat(string) Converts a string to an float value . Eg x=77.5AB67 y=parseFloat(x) y stores the value 77.5 If x=56ABC parseFloat(x) will return 56 If there are no floating points then the integral value is returned. FaaDoOEngineers.com

User Defined Functions FaaDoOEngineers.com

User Defined Functions (contd.) FaaDoOEngineers.com

User Defined Functions (contd.) FaaDoOEngineers.com

Events FaaDoOEngineers.com

Events (contd.) FaaDoOEngineers.com

Event Handlers FaaDoOEngineers.com

Common Event Handlers FaaDoOEngineers.com

Common Event Handlers (contd.) FaaDoOEngineers.com

Common Event Handlers (contd.) onLoad and onUnload The onload and onUnload events are triggered when the user enters or leaves the page. The onload event is also triggered when the image is loaded. The showstatus() function will be called when a user enters a page <body onload=“showStatus()”> The onload event is often used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information. Both the onload and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page. For example, you could have a popup asking for the user's name upon his first arrival to your page. The name is then stored in a cookie. Next time the visitor arrives at your page, you could have another popup saying something like: "Welcome John Doe!". FaaDoOEngineers.com

Common Event Handlers (contd.) onFocus, onBlur and onChange The onFocus, onBlur and onChange events are often used in combination with validation of form fields. The checkEmail() function will be called whenever the user changes the content of the field: <input type="text" size="30" id="email" onchange="checkEmail()">; Can refer to http://w3schools.com/jsref/jsref_events.asp for a complete reference of event handlers FaaDoOEngineers.com

Common Event Handlers (contd.) onSubmit The onSubmit event is used to validate ALL form fields before submitting it. The checkForm() function will be called when the user clicks the submit button in the form. <form method="post" action="xxx.htm" onsubmit="return checkForm()"> FaaDoOEngineers.com

Common Event Handlers (contd.) onMouseOver and onMouseOut onMouseOver and onMouseOut are often used to create "animated" buttons. An alert box appears when an onMouseOver event is detected: <a href="http://www.ibm.com" onmouseover="alert('An onMouseOver event’)”> <img src=“ibmlogo.gif" width="100" height="30"> </a> FaaDoOEngineers.com

Test Your Understanding FaaDoOEngineers.com

Test Your Understanding FaaDoOEngineers.com

Example FaaDoOEngineers.com

Example (contd.) FaaDoOEngineers.com

Example (contd.) FaaDoOEngineers.com

Example (contd.) FaaDoOEngineers.com

Example (contd.) FaaDoOEngineers.com

Example (contd.) FaaDoOEngineers.com

Example (contd.) function Addition(x,y) { var x1=document.form1.text1.value var y1=document.form1.text2.value var Ans=document.form1.text3.value var temp=x1+y1 } FaaDoOEngineers.com

Example (contd.) function Addition (x,y) { var x1=parseInt(x) var y1=parseInt(y) var Ans=document.form1.text3.value var temp=x1+y1 } FaaDoOEngineers.com

Example (contd.) function Addition (x,y) { var x1=parseInt(x) var y1=parseInt(y) var Ans=document.form1.text3.value var temp=x1+y1 } <INPUT TYPE=“button” value=“ +op “ onClick=“Addition(text1.value,text2.value)”> FaaDoOEngineers.com

Example (contd.) function Addition (x,y) { var x1=parseInt(x) var y1=parseInt(y) var Ans=document.form1.text3.value var temp=x1+y1 if(Ans==temp){ alert(“Your Result agrees with JavaScript!”) document.form1.text1.value=‘’ document.form1.text2.value=‘’ document.form1.text3.value=‘’ } else{ alert(“No, JavaScript evalutes this operation differently”) }} FaaDoOEngineers.com

Test Your Understanding FaaDoOEngineers.com

Test Your Understanding FaaDoOEngineers.com

A Complete Program <html> <head> <input type="button" onClick="myfunction('Good Morning!')" value="In the Morning"> onClick="myfunction('Good Evening!')" value="In the Evening"> </form> <p> When you click on one of the buttons, a function will be called. The function will alert the argument that is passed to it. </p> </body> </html> <html> <head> <script type="text/javascript"> function myfunction(txt) { alert(txt) } </script> </head> <body> <form> FaaDoOEngineers.com

Output FaaDoOEngineers.com

myfunction (txt) receives “ Good Morning!” FaaDoOEngineers.com

myfunction (txt) receives “ Good Evening !” FaaDoOEngineers.com

Objects & Arrays FaaDoOEngineers.com FaaDoOEngineers.com

JavaScript Objects JavaScript is not a true Object Oriented language as C++ or Java but rather an Object Based language. Objects in JavaScript are software entities such as the browser window or an HTML document. FaaDoOEngineers.com

JavaScript Objects (contd.) FaaDoOEngineers.com

JavaScript Objects (contd.) FaaDoOEngineers.com

JavaScript Objects (contd.) FaaDoOEngineers.com

JavaScript Objects (contd.) FaaDoOEngineers.com

JavaScript Objects (contd.) FaaDoOEngineers.com

JavaScript Objects (contd.) FaaDoOEngineers.com

JavaScript Objects (contd.) FaaDoOEngineers.com

JavaScript Objects (contd.) FaaDoOEngineers.com

JavaScript Objects (contd.) FaaDoOEngineers.com

Instances of Computer Objects (contd.) FaaDoOEngineers.com

JavaScript Core Objects FaaDoOEngineers.com

JavaScript Core Objects (contd.) Boolean Math 1. Boolean 2. Date Date Number 3. Function 4. Math 5. Number Function String 6. String FaaDoOEngineers.com

JavaScript Core Objects (contd.) Boolean Math 1. Boolean 2. Date Date Number 3. Function 4. Math 5. Number Function String 6. String FaaDoOEngineers.com

JavaScript Core Objects (contd.) Boolean Object This object is used to convert a non boolean value to a boolean value. The Boolean Object is an Object Wrapper for a Boolean value Boolean object is defined with the new keyword var BooleanObj=new Boolean() If the Boolean object has no initial value or if it is 0, -0, null, "", false, undefined, or NaN, the object is set to false. Otherwise it is true (even with the string "false")! FaaDoOEngineers.com

JavaScript Core Objects (contd.) All the following lines of code create Boolean objects with an initial value of false : var myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean("") var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN) FaaDoOEngineers.com

JavaScript Core Objects (contd.) All the following lines of code create Boolean objects with an initial value of true: var myBoolean=new Boolean(true) var myBoolean=new Boolean("true") var myBoolean=new Boolean("false") var myBoolean=new Boolean("Richard") FaaDoOEngineers.com

Test Your Understanding FaaDoOEngineers.com

Test Your Understanding FaaDoOEngineers.com

JavaScript Core Objects (contd.) Boolean Math 1. Boolean 2. Date Date Number 3. Function 4. Math 5. Number Function String 6. String FaaDoOEngineers.com

JavaScript Core Objects (contd.) Date Object The Date object is used to work with dates and times.  An instance of the Date object with the "new" keyword. An instance of Date object can be created as: var myDate=new Date() var myDate=new Date("Month dd, yyyy hh:mm:ss") var myDate=new Date("Month dd, yyyy") var myDate=new Date(yy,mm,dd,hh,mm,ss) var myDate=new Date(yy,mm,dd) var myDate= new Date(milliseconds) FaaDoOEngineers.com

JavaScript Core Objects (contd.) FaaDoOEngineers.com

JavaScript Core Objects (contd.) FaaDoOEngineers.com

JavaScript Core Objects (contd.) FaaDoOEngineers.com

JavaScript Core Objects (contd.) FaaDoOEngineers.com

JavaScript Core Objects (contd.) FaaDoOEngineers.com

JavaScript Core Objects (contd.) FaaDoOEngineers.com

JavaScript Core Objects (contd.) FaaDoOEngineers.com

JavaScript Core Objects (contd.) FaaDoOEngineers.com

JavaScript Core Objects (contd.) FaaDoOEngineers.com

JavaScript Core Objects (contd.) Commonly used methods of the Date Object FaaDoOEngineers.com

JavaScript Core Objects (contd.) FaaDoOEngineers.com

JavaScript Core Objects (contd.) Boolean Math 1. Boolean 2. Date Date Number 3. Function 4. Math 5. Number Function String 6. String FaaDoOEngineers.com

JavaScript Core Objects (contd.) FaaDoOEngineers.com

JavaScript Core Objects (contd.) FaaDoOEngineers.com

JavaScript Core Objects (contd.) FaaDoOEngineers.com

JavaScript Core Objects (contd.) FaaDoOEngineers.com

JavaScript Core Objects (contd.) Boolean Math 1. Boolean 2. Date Date Number 3. Function 4. Math 5. Number Function String 6. String FaaDoOEngineers.com

JavaScript Core Objects (contd.) Math Object Math object allows to perform common mathematical functions. The Math object includes several Mathematical values and functions. The Math object need not be defined before using it. FaaDoOEngineers.com

JavaScript Core Objects (contd.) Mathematical values provided by JavaScript Math.E Math.PI Math.SQRT2 Math.SQRT1_2 Math.LN2 Math.LN10 Math.LOG2E Math.LOG10E JavaScript provides eight mathematical values (constants) that can be accessed from the Math object. These are: E, PI, square root of 2, square root of 1/2, natural log of 2, natural log of 10, base-2 log of E, and base-10 log of E. FaaDoOEngineers.com

JavaScript Core Objects (contd.) Methods of Math object If you intend to invoke Math multiple times in your script, a good statement to remember is "with." Using it you can omit the "Math." prefix for any subsequent Math properties/methods: with (Math) { var x= sin(3.5) var y=tan(5) var result=max(x,y) } FaaDoOEngineers.com

Test Your Understanding FaaDoOEngineers.com

Test Your Understanding FaaDoOEngineers.com

JavaScript Core Objects (contd.) Boolean Math 1. Boolean 2. Date Date Number 3. Function 4. Math 5. Number Function String 6. String FaaDoOEngineers.com

JavaScript Core Objects (contd.) FaaDoOEngineers.com

JavaScript Core Objects (contd.) FaaDoOEngineers.com

JavaScript Core Objects (contd.) FaaDoOEngineers.com

JavaScript Core Objects (contd.) Boolean Math 1. Boolean 2. Date Date Number 3. Function 4. Math 5. Number Function String 6. String FaaDoOEngineers.com

JavaScript Core Objects (contd.) String object The String object is used to manipulate a stored piece of text. String objects must be created using the new keyword. JavaScript automatically converts the string primitive to a temporary String object A string literal can be embedded within a single or double quotation marks. Because Javascript automatically converts between string primitives and String objects, you can call any of the methods of the String object on a string primitive FaaDoOEngineers.com

JavaScript Core Objects (contd.) String primitives and String objects give different results when evaluated as JavaScript. Primitives are treated as source code, but String objects are treated as a character sequence object. s1 = "2 + 2“ // creates a string primitive s2 = new String("2 + 2") // creates a String object eval(s1) // returns the number 4 eval(s2) // returns the string "2 + 2“ eval(s2.valueOf()); // returns the number 4 FaaDoOEngineers.com

JavaScript Core Objects (contd.) Common Methods of String Object FaaDoOEngineers.com

Defining Arrays An Array object is used to store a set of values in a single variable name. An Array object is created with the new keyword. An array can be created as: var MyArray=new Array() An array can also be created by specifying the array size. var MyArray=new Array(3) FaaDoOEngineers.com

Arrays (contd.) Data can be entered into an array as: var MyArray=new Array() MyArray[0]=“Paul” MyArray[1]=“Sam” MyArray[2]=“Niel” Data can also be entered into an array as: var MyArray=new Array(“Paul”,”Sam”, “Niel”) If you specify numbers or true/false values inside the array then the type of variables will be numeric or Boolean instead of string. FaaDoOEngineers.com

Arrays (contd.) Accessing Arrays You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0 . var MyArray=new Array() Myarray [0] The starting index To modify/insert a value in an existing array, just add a new value to the array with a specified index number: FaaDoOEngineers.com

Document Object Model FaaDoOEngineers.com FaaDoOEngineers.com

Document Object Model The DOM is a programming API for documents. It is based on an object structure that closely resembles the structure of the documents it models. For instance, consider this table, taken from an HTML document: <TABLE> <TBODY> <TR> <TD>Shady Grove</TD> <TD>Aeolian</TD> </TR> <TR> <TD>Over the River, Charlie</TD> <TD>Dorian</TD> </TR> </TBODY> </TABLE> The Document Object Model (DOM) is an application programming interface (API) for valid HTML and well-formed XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated In the DOM, documents have a logical structure which is very much like a tree; to be more precise, which is like a "forest" or "grove", which can contain more than one tree. Each document contains zero or one doctype nodes, one root element node, and zero or more comments or processing instructions; the root element serves as the root of the element tree for the document. However, the DOM does not specify that documents must be implemented as a tree or a grove, nor does it specify how the relationships among objects be implemented. The DOM is a logical model that may be implemented in any convenient manner. In this specification, we use the term structure model to describe the tree-like representation of a document. FaaDoOEngineers.com

Document Object Model (contd.) Graphical representation of the DOM of the example table The Document Object Model (DOM) is an application programming interface (API) for valid HTML and well-formed XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated In the DOM, documents have a logical structure which is very much like a tree; to be more precise, which is like a "forest" or "grove", which can contain more than one tree. Each document contains zero or one doctype nodes, one root element node, and zero or more comments or processing instructions; the root element serves as the root of the element tree for the document. However, the DOM does not specify that documents must be implemented as a tree or a grove, nor does it specify how the relationships among objects be implemented. The DOM is a logical model that may be implemented in any convenient manner. In this specification, we use the term structure model to describe the tree-like representation of a document. FaaDoOEngineers.com

Document Object Model (contd.) With JavaScript you can restructure an entire HTML document. You can add, remove, change, or reorder items on a page. To change anything on a page, JavaScript needs access to all elements in the HTML document. This access, along with methods and properties to add, move, change, or remove HTML elements, is given through the Document Object Model (DOM). In 1998, W3C published the Level 1 DOM specification. This specification allowed access to and manipulation of every single element in an HTML page. All browsers have implemented this recommendation, and therefore, incompatibility problems in the DOM have almost disappeared. FaaDoOEngineers.com

Document Object Model (contd.) Document Tree All the nodes above have relationships to each other. Every node except for the document node has a parent node. E.g. the parent node of the <head> and <body> nodes are the <html> node, and the parent node of the "Hello world!" text node is the <p> node. Most element nodes have child nodes. E.g. the <head> node has one child node: the <title> node. The <title> node also has one child node: the text node "DOM Tutorial". Nodes are siblings when they share a parent. E.g. the <h1> and <p> nodes are siblings, because their parent is the <body> node. Nodes can also have descendants. Descendants are all the nodes that are children of a node, or children of those children, and so on. E.g. all text nodes are descendants of the <html> node, while the first text node are descendant of the <head> node. Nodes can also have ancestors. Ancestors are nodes that are parents of a node, or parents of this parent, and so on. E.g. all text nodes have the <html> node as an ancestor. FaaDoOEngineers.com

How to access the nodes in an HTML You can find the element you want to manipulate in several ways: By using the getElementById() and getElementsByTagName() methods By using the parentNode, firstChild, and lastChild properties of an element node FaaDoOEngineers.com

Navigator Object Navigator object is the object representation of the client internet browser or web navigator program that is being used. This is a top level object to all others object in DOM hierarchy. FaaDoOEngineers.com

Navigator Object Properties appCodeName – The name of the browser’s code such as Internet Explorer appName – The name of the browser. appVersion – The version of the browser. plugins – An array of plug-ins supported by the browser and installed on the browser. cpuClass – The type of CPU which may be “x86”. cookieEnabled – A boolean value of true or false depending on whether cookies are enabled in the browser. FaaDoOEngineers.com

Navigator Object Methods javaEnabled() – Returns a boolean telling if the browser has JavaScript enabled. FaaDoOEngineers.com

Window Object The Window object is the top level object in the JavaScript hierarchy. The Window object represents a browser window. A Window object is created automatically with every instance of a <body> or <frameset> tag. FaaDoOEngineers.com

Window Object Collections Frames[] – Returns all named frames in the window. FaaDoOEngineers.com

Window Object Properties name – sets of return the name of the window. status – sets or returns the name of the window. length – sets or returns the number of frames in the window. self – returns a reference to the current window. statusbar - sets whether or not the browser’s statusbar should be visible. toolbar - sets whether or not the browser’s toolbar should be visible. closed – Returns all named frames in the window document history FaaDoOEngineers.com

Window Object Methods open() – Opens a new browser window. createPopup() – Creates a popup window. setInterval(code,millisec[,lang]) – Evaluates an expression at specified intervals. clearInterval(id_of_setInterval) – cancels a timeout that is set with the setInterval() method. setTimeout(code,millisec[,lang]) – Evaluates an expression after a specified number of milliseconds. clearTimeout(id_of_setTimeout) – cancels a timeout that is set with the setTimeout() method. focus() – sets the focus to the current window. blur() – removes focus from the current window. close() – closes the current window. setTimeout(code,millisec[,lang]) – where, code refers to a pointer to a function or the code to be executed, millisec refers to time in milliseconds, lang refers to Language in use (JavaScript,VBScript). setInterval(code,millisec[,"lang"]) - where, code refers to a pointer to a function or the code to be executed, millisec refers to time in milliseconds, lang refers to Language in use (JavaScript,VBScript). clearInterval(id_of_setinterval) - The ID value returned by setInterval() is used as the parameter for the clearInterval() method. It is a int value. clearTimeout(id_of_setTimeout) – id of the setTimeout method(). It is a int value. moveTo(x,y) – Moves a window to the specified position. x refers to the current x coordinate, y refers to the current y coordinate. moveBy(x,y) – Moves a window relative to its current position. x refers to the current x coordinate, y refers to the current y coordinate. FaaDoOEngineers.com

Frame Object Frame object represents an HTML frame. For each instance of a <frame> tag in an HTML document, a Frame object is created. imageObject.align=left|right|top|middle|bottom Go(number/URL) – number specifies the position of the page in the list. Src – Sets or returns the URL of an image. The new image inherits the height & width attributes of the original image. FaaDoOEngineers.com

Frames are instances of Window object Frame Object (contd.) In Document Object Model Frames are instances of Window object FaaDoOEngineers.com

Frame Object (contd.) FaaDoOEngineers.com

Frame Object (contd.) FaaDoOEngineers.com

Frame Object (contd.) FaaDoOEngineers.com

Frame Object (contd.) FaaDoOEngineers.com

Frame Object (contd.) FaaDoOEngineers.com

Frame Object (contd.) FaaDoOEngineers.com

Frame Object (contd.) FaaDoOEngineers.com

Frame Object (contd.) FaaDoOEngineers.com

Frame Object (contd.) FaaDoOEngineers.com

Frame Object (contd.) FaaDoOEngineers.com

Frame Object (contd.) FaaDoOEngineers.com

Frame Object (contd.) FaaDoOEngineers.com

Frame Object (contd.) FaaDoOEngineers.com

Frame Object (contd.) FaaDoOEngineers.com

Frame Object (contd.) FaaDoOEngineers.com

Frame Object (contd.) FaaDoOEngineers.com

Test Your Understanding FaaDoOEngineers.com

Test Your Understanding FaaDoOEngineers.com

Document Object The document object represents the entire HTML document and can be used to access all elements in a page. The document object is part of the window object and is accessed through the window.document property or simply document. setTimeout(code,millisec[,lang]) – where, code refers to a pointer to a function or the code to be executed, millisec refers to time in milliseconds, lang refers to Language in use (JavaScript,VBScript). setInterval(code,millisec[,"lang"]) - where, code refers to a pointer to a function or the code to be executed, millisec refers to time in milliseconds, lang refers to Language in use (JavaScript,VBScript). clearInterval(id_of_setinterval) - The ID value returned by setInterval() is used as the parameter for the clearInterval() method. It is a int value. clearTimeout(id_of_setTimeout) – id of the setTimeout method(). It is a int value. moveTo(x,y) – Moves a window to the specified position. x refers to the current x coordinate, y refers to the current y coordinate. moveBy(x,y) – Moves a window relative to its current position. x refers to the current x coordinate, y refers to the current y coordinate. FaaDoOEngineers.com

Document Object Collections anchors[] - Returns a reference to all Anchor objects in the document. forms[] - Returns a reference to all Form objects in the document. images[] - Returns a reference to all Image objects in the document. links[] - Returns a reference to all Area and Link objects in the document. FaaDoOEngineers.com

Document Object Properties Body – gives direct access to the <body> element. Cookie – Sets or returns all cookies associated with the current document. lastModified – Returns the date and time a document was last modified. Title – Returns the title of the current document. URL – Returns the URL of the current document. FaaDoOEngineers.com

Document Object Methods write() - Writes HTML expressions or JavaScript code to a document writeln() – Similar to write(), with the addition of writing a new line character after each expression. open() - Opens a stream to collect the output from any document.write() or document.writeln() methods. close() - Closes an output stream opened with the document.open() method, and displays the collected data getElementByID() – Returns a reference to the first object with the specified id. getElementsByName() – Returns a collection of objects with the specified name. getElementsByTagName() – Return a collection of objects with the specified tag name. FaaDoOEngineers.com

Location Object Location object is an JavaScript object it is not an DOM object. The Location object is automatically created by the JavaScript runtime engine and contains information about the current URL. The Location object is part of the Window object and is accessed through the window.location property. FaaDoOEngineers.com

Location Object (contd.) FaaDoOEngineers.com

Location Object (contd.) FaaDoOEngineers.com

Location Object (contd.) FaaDoOEngineers.com

Location Object (contd.) FaaDoOEngineers.com

Location Object (contd.) FaaDoOEngineers.com

Location Object (contd.) FaaDoOEngineers.com

Location Object Methods Assign (url) – It loads a new document. Reload() – the current document. Replace() – Replaces the current document with a new one. FaaDoOEngineers.com

Location Object Example <html> <body> <script> switch (window.location.protocol) { case "http:": document.write("From Web<BR>\n") break case "file:": document.write("From Local computer<BR>\n") default: document.write("Unknown Source<BR>\n") } </script> </body> </html> FaaDoOEngineers.com

If Accessed from the Local File System Output: If Accessed from the Local File System FaaDoOEngineers.com

If the page is delivered by a Web Server. Output: If the page is delivered by a Web Server. FaaDoOEngineers.com

History Object History object is a JavaScript object. The History object is automatically created by the JavaScript runtime engine and consists of and array of URLs. It is a part of window object & accessed through window.history property. FaaDoOEngineers.com

History Object (contd.) FaaDoOEngineers.com

History Object (contd.) go(number|URL) – Loads a specific page in the history list. Length is a property that returns the number of elements in the history list. FaaDoOEngineers.com

History Object (contd.) FaaDoOEngineers.com

History Object (contd.) FaaDoOEngineers.com

Test Your Understanding FaaDoOEngineers.com

Test Your Understanding FaaDoOEngineers.com

Form Object Model FaaDoOEngineers.com

Form Object Model (contd.) FaaDoOEngineers.com

Form Object Model (contd.) FaaDoOEngineers.com

Test Your Understanding FaaDoOEngineers.com

Test Your Understanding FaaDoOEngineers.com

Form Object Model (contd.) FaaDoOEngineers.com

Form Object Model (contd.) FaaDoOEngineers.com

Form Object Model (contd.) FaaDoOEngineers.com

Form Object Model (contd.) FaaDoOEngineers.com

Form Object Model (contd.) FaaDoOEngineers.com

Test Your Understanding FaaDoOEngineers.com

Test Your Understanding FaaDoOEngineers.com

Form Object Model (contd.) FaaDoOEngineers.com

Form Object Model (contd.) FaaDoOEngineers.com

Test Your Understanding FaaDoOEngineers.com

Test Your Understanding FaaDoOEngineers.com

Form Object Model (contd.) FaaDoOEngineers.com

Form Object Model (contd.) FaaDoOEngineers.com

Form Object Model (contd.) FaaDoOEngineers.com

Form Object Model (contd.) FaaDoOEngineers.com

Test Your Understanding FaaDoOEngineers.com

Test Your Understanding FaaDoOEngineers.com

Test Your Understanding FaaDoOEngineers.com

Test Your Understanding FaaDoOEngineers.com

Cookies FaaDoOEngineers.com FaaDoOEngineers.com

Cookies A cookie can store a small amount of information about a user visiting a site. A cookie is a small text file that is stored on the site visitor's computer by their browser . Because the cookie is stored on the user’s computer, it does not require any server space no matter how many users you have . With JavaScript, you can both create and retrieve cookie values. Cookies were originally invented by Netscape to give 'memory' to web servers and browsers. The HTTP protocol, which arranges for the transfer of web pages to your browser and browser requests for pages to servers, is state-less, which means that once the server has sent a page to a browser requesting it, it doesn't remember a thing about it. So if you come to the same web page a second, third, hundredth or millionth time, the server once again considers it the very first time you ever came there. This can be annoying in a number of ways. The server cannot remember if you identified yourself when you want to access protected pages, it cannot remember your user preferences, it cannot remember anything. As soon as personalization was invented, this became a major problem. Cookies were invented to solve this problem. There are other ways to solve it, but cookies are easy to maintain and very versatile. FaaDoOEngineers.com

Cookies (contd.) You can use cookies to : save user preferences. customize data. remember the last visit. Keep track of items in an order while a user browses. Remember the information your site’s visitors gave last time. Cookies can be created, read and erased by JavaScript. They are accessible through the property document.cookie According to Netscape's official documentation, a client can hold up to 300 cookies. A cookie can be up to 4KB, including its name and value, which is exactly 4000 characters. A maximum of 20 cookies per server or domain are allowed. FaaDoOEngineers.com

Cookies (contd.) What does a cookie contain? Name value pair The first element in a cookie is a "name" attribute, followed by the data to be stored in the cookie. The expiry date specifies how long the cookie is valid for. Cookies can be read by JavaScript too. They're mostly used for storing user preferences. The first element in a cookie is a "name" attribute. Here, the "name" is a string used to identify the cookie (akin to a variable name), followed by the data to be stored in the cookie. This variable-value pair is required; you can't bake a cookie without it. FaaDoOEngineers.com

Cookies (contd.) What does a cookie contain? The path The domain this states where the cookie may be accessed from on the Web site. Most often, this is set to the server's document root. The domain The "domain" attribute allows you to set a domain name for the cookie. Again, this is optional. Each cookie also has a domain and a path. The domain tells the browser to which domain the cookie should be sent. If you don't specify it, it becomes the domain of the page that sets the cookie, in the case of this page www.quirksmode.org. Please note that the purpose of the domain is to allow cookies to cross sub-domains. My cookie will not be read by search.quirksmode.org because its domain is www.quirksmode.org . When I set the domain to quirksmode.org, the search sub-domain may also read the cookie. I cannot set the cookie domain to a domain I'm not in, I cannot make the domain www.microsoft.com . Only quirksmode.org is allowed, in this case. The path gives you The path gives you the chance to specify a directory where the cookie is active. So if you want the cookie to be only sent to pages in the directory cgi-bin, set the path to /cgi-bin. Usually the path is set to /, which means the cookie is valid throughout the entire domain. This script does so, so the cookies you can set on this page will be sent to any page in the www.quirksmode.org domain (though only this page has a script that searches for the cookies and does something with them). FaaDoOEngineers.com

Question The name-value pair is the _____________ element in the first Cookie first second third FaaDoOEngineers.com

Answer The name-value pair is the _____________ element in the first Cookie first second third FaaDoOEngineers.com

Cookies and Security Turn up security level on your browser to disable cookies or prompt for cookie. Delete the content of a cookie and then write protect it. Use 3rd party software: Cookie Pal, CookieMaster, CookieCrusher to monitor, browse and edit cookies. With these 3rd party softwares you can decide which cookies you want to accept or reject and let Cookie Pal handle the rest - transparently and efficiently! FaaDoOEngineers.com

Format of Cookie First the name value pair. Then a semicolon and a space. Then the expiry date. Expiry date should be in UTC format. Then again a semicolon and a space. Then the path. FaaDoOEngineers.com

Format of Cookie (contd.) document.cookie=<name of cookie>=<value of cookie>;<blank space>expires=<date in UTC format>;<blank space>path=<path location> Example document.cookie = ‘user=Paul; expires=Thu, 2 Aug 2008 20:47:11 UTC; path=/' FaaDoOEngineers.com

Example of Setting a Cookie <html> <head> <script language="JavaScript"> function setCookie(name, value) { var exp=new Date("January 31,2008") document.cookie=name+"="+escape (value)+"; expires="+exp.toGMTString() +"; path=/“ document.write(“Cookie has been set”) )    </script> </head> <body> <form> <input type="button" value="Set a Cookie" onClick="setCookie(‘user',‘Paul Smith')"> </form> </body> </html> What does the escape function do? Set an expiry date FaaDoOEngineers.com

escape() function There's no escape! Strictly speaking, we should be escaping our cookie values -- encoding non-alphanumeric characters such as spaces and semicolons. This is to ensure that our browser can interpret the values properly. Fortunately this is easy to do with JavaScript's escape() function. For example document.cookie = "username=" + escape(“Paul Smith") + "; expires=15/02/2003 00:00:00"; FaaDoOEngineers.com

Example of Setting a Cookie </script> </head> <body> <form> <input type="button" value="Set a Cookie" onClick="setCookie(‘user',‘Paul Smith')"> </form> </body> </html> <html> <head> <script language="JavaScript"> function setCookie(name, value) { var exp=new Date("January 31,2008") document.cookie=name+"="+escape (value)+"; expires="+exp.toGMTString() +"; path=/“ document.write(“Cookie has been set”) )    This is a very strict syntax, don't change it! The value stored is user=Paul Smith Setting the cookie FaaDoOEngineers.com

Reading a Cookie <html> <head> <script language="JavaScript"> function readCookie() { var ca = document.cookie document.write(ca) }   </script> </head> <body> <form><input type="button" value="read" onClick="readCookie()"> </form> </body> </html> U can use the various String methods to extract the different parts of the cookie Value retrieved is user=Paul Smith Returns the cookie name value pair FaaDoOEngineers.com

Extracting only the value from the Cookie <html> <head> <script language="JavaScript"> function readCookie(c_name) { if (document.cookie.length>0) {c_start=document.cookie.indexOf(c_name + "=") if (c_start!=-1) c_start=c_start + c_name.length+1 c_end=document.cookie.indexOf(";",c_start) if (c_end==-1) c_end=document.cookie.length document.write( document.cookie.substring(c_start,c_end)) }  </script> </head> <body> <form> <input type="button" value="read" onClick="readCookie('user')"> </form> </body> </html> Displays the value: Paul Smith This program checks for the cookie name “user” and uses the String functions to display the value FaaDoOEngineers.com

Delete Cookies <body> <form> <html> <head> <script language="JavaScript"> function deleteCookie ( cookie_name) { var cookie_date = new Date ( ) cookie_date.setTime ( cookie_date.getTime() - 1 ) document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString() }  </script> </head> <body> <form> <input type="button" value=“delete" onClick="deleteCookie(‘user')"> </form> </body> </html> Refer to the cookie name created and reduce the expiry time period The cookie's expiry date is set to one second less then the current date. FaaDoOEngineers.com

Modifying a cookie To modify a cookie simply reset the values and use the same procedure for setting the cookie. Ensure that the cookie name is existing or a new cookie will be created. FaaDoOEngineers.com

Summary Cookies are small text files that sit on your hard disk. Cookies are created when you visit websites that use cookies to store information that they need (or prefer). Websites often use cookies to personalize the user experience - such as remembering your name (assuming you supplied it previously) or remembering the items in your shopping cart from previous visits. Despite the many misconceptions about cookies being malicious, they are quite harmless. Cookies can't give your personal details to other websites, or transmit a virus or anything like that. A cookie can only be read by the server that created it. Websites normally use cookies to make its users' lives easier, not harder. FaaDoOEngineers.com

Thank You For Your Participation FaaDoOEngineers.com FaaDoOEngineers.com