This document provides an outline for a lecture on JavaScript. It covers an introduction to JavaScript, its capabilities, versions, embedding JavaScript code, and basic topics like variables, data types, and control structures. It also discusses the future of JavaScript and provides some simple examples of JavaScript code.
This document provides an introduction to JavaScript including:
- JavaScript is an interpreted, untyped scripting language originally developed for use in web browsers.
- JavaScript is used to specify the behavior of web pages and can dynamically manipulate HTML, CSS, and DOM.
- The standardized version of JavaScript is called ECMAScript. Core JavaScript contains basic language elements and objects that can be extended for different purposes like client-side or server-side JavaScript.
- JavaScript is a prototype-based language that uses dynamic typing and has primitives like numbers, strings, booleans as well as object types. It includes basic syntax elements like variables, operators, and control structures.
JavaScript can change HTML content, attributes, styles, and validate data. It can be placed in the <body> and <head> sections between <script> tags. Functions and events allow JavaScript code to run when events occur. JavaScript can output to alerts, the document, elements, and the console. It uses data types like numbers, strings, Booleans, arrays, and objects. Conditionals like if/else and switch statements allow different code blocks to run based on conditions. Loops like for, for/in, while, and do/while repeat code.
JavaScript is a client-side scripting language that allows web pages to become interactive and dynamic. It can update and modify the content of an HTML page without needing to reload the page. JavaScript code can be embedded directly in HTML pages or placed in separate .js files. Common uses of JavaScript include validating form input, detecting the visitor's browser, creating cookies, and adding interactivity to HTML elements like buttons and links.
JavaScript was originally named Mocha but was renamed LiveScript and then JavaScript. It is a lightweight, interpreted programming language designed for creating network-centric and browser-based applications. JavaScript can be used for client-side scripting through features like popup boxes and event handling, and for server-side scripting by running JavaScript code on the server with Node.js. It includes basic datatypes, operators, control flows, and built-in objects for manipulating the browser and its DOM.
Introduction to JavaScript course. The course was updated in 2014-15.
Will allow you to understand what is JavaScript, what's it history and how you can use it.
The set of slides "Introduction to jQuery" is a follow up - which would allow the reader to have a basic understanding across JavaScript and jQuery.
This document provides an introduction and overview of JavaScript. It discusses that JavaScript is a client-side scripting language that can be inserted into HTML pages and run by web browsers to provide interactive and dynamic features. It covers JavaScript basics like data types, variables, operators, functions, and events. It also explains how to write JavaScript code directly in HTML pages or externally and shows examples of built-in functions and how to create user-defined functions.
JavaScript was designed to add interactivity to HTML pages. It is a scripting language that is usually embedded directly into HTML pages and allows for dynamic text, event handling, reading/writing HTML elements, and validating form data. JavaScript supports both client-side and server-side scripting and was originally developed by Netscape under the name LiveScript before being renamed. It provides programming capabilities to HTML authors and allows for dynamic content, user interaction, and validation without server requests.
The document discusses JavaScript, including its history and differences from Java. It describes JavaScript's uses in modifying HTML documents dynamically and embedding it in HTML. The document outlines JavaScript's object-based nature, primitive data types, variables, operators, and functions. It provides examples of numeric, string, and boolean literals as well as type conversions.
This document provides an introduction to JavaScript including:
- JavaScript is an interpreted, untyped scripting language originally developed for use in web browsers.
- JavaScript is used to specify the behavior of web pages and can dynamically manipulate HTML, CSS, and DOM.
- The standardized version of JavaScript is called ECMAScript. Core JavaScript contains basic language elements and objects that can be extended for different purposes like client-side or server-side JavaScript.
- JavaScript is a prototype-based language that uses dynamic typing and has primitives like numbers, strings, booleans as well as object types. It includes basic syntax elements like variables, operators, and control structures.
JavaScript can change HTML content, attributes, styles, and validate data. It can be placed in the <body> and <head> sections between <script> tags. Functions and events allow JavaScript code to run when events occur. JavaScript can output to alerts, the document, elements, and the console. It uses data types like numbers, strings, Booleans, arrays, and objects. Conditionals like if/else and switch statements allow different code blocks to run based on conditions. Loops like for, for/in, while, and do/while repeat code.
JavaScript is a client-side scripting language that allows web pages to become interactive and dynamic. It can update and modify the content of an HTML page without needing to reload the page. JavaScript code can be embedded directly in HTML pages or placed in separate .js files. Common uses of JavaScript include validating form input, detecting the visitor's browser, creating cookies, and adding interactivity to HTML elements like buttons and links.
JavaScript was originally named Mocha but was renamed LiveScript and then JavaScript. It is a lightweight, interpreted programming language designed for creating network-centric and browser-based applications. JavaScript can be used for client-side scripting through features like popup boxes and event handling, and for server-side scripting by running JavaScript code on the server with Node.js. It includes basic datatypes, operators, control flows, and built-in objects for manipulating the browser and its DOM.
Introduction to JavaScript course. The course was updated in 2014-15.
Will allow you to understand what is JavaScript, what's it history and how you can use it.
The set of slides "Introduction to jQuery" is a follow up - which would allow the reader to have a basic understanding across JavaScript and jQuery.
This document provides an introduction and overview of JavaScript. It discusses that JavaScript is a client-side scripting language that can be inserted into HTML pages and run by web browsers to provide interactive and dynamic features. It covers JavaScript basics like data types, variables, operators, functions, and events. It also explains how to write JavaScript code directly in HTML pages or externally and shows examples of built-in functions and how to create user-defined functions.
JavaScript was designed to add interactivity to HTML pages. It is a scripting language that is usually embedded directly into HTML pages and allows for dynamic text, event handling, reading/writing HTML elements, and validating form data. JavaScript supports both client-side and server-side scripting and was originally developed by Netscape under the name LiveScript before being renamed. It provides programming capabilities to HTML authors and allows for dynamic content, user interaction, and validation without server requests.
The document discusses JavaScript, including its history and differences from Java. It describes JavaScript's uses in modifying HTML documents dynamically and embedding it in HTML. The document outlines JavaScript's object-based nature, primitive data types, variables, operators, and functions. It provides examples of numeric, string, and boolean literals as well as type conversions.
This document provides an introduction to JavaScript. It discusses the purposes of JavaScript including making web pages interactive by manipulating pages or responding to user actions. It covers basic JavaScript syntax including variables, data types, operators, conditional statements, and functions. It also discusses event-driven programming in JavaScript and how to attach JavaScript functions to HTML elements as event handlers.
This document provides an overview of JavaScript fundamentals including a brief history of JavaScript, its uses, language features, inclusion of scripts in HTML documents, and the JavaScript object model. It discusses the window object and properties like location, frames, history. It also covers variables and data types, operators, control structures, arrays, functions, and communicating with the user through prompts, alerts and changing the status bar.
JavaScript is a scripting language that allows adding interactivity to HTML pages. It can be used for client-side form validation and integration with user plugins. JavaScript is case-sensitive and allows variables, functions, conditional statements, and objects. Common uses include pop-up boxes, event handling, and cookies.
JavaScript is a scripting language that can be inserted into HTML pages and used to program the behavior of web pages. It allows web pages to be dynamic and interactive. JavaScript code is placed between <script> and </script> tags and can manipulate HTML elements and write to the document. Variables, functions, conditional statements, and operators allow JavaScript code to run conditionally based on events or user input. JavaScript is case sensitive, uses semicolons, and has both local and global variables. Common data types include numbers, strings, arrays, and objects.
The document discusses key concepts in .NET including value types, reference types, classes, inheritance, interfaces, generics, boxing and unboxing, exceptions, events and delegates.
It explains that value types like integers store data directly while reference types store references to data on the heap. Common reference types include strings, arrays and streams. Classes can inherit from other classes and implement interfaces. Generics allow types to be parameterized. Events and delegates are used for asynchronous notification. Explicit conversion is needed between non-compatible types.
JavaScript was originally created as LiveScript in 1995 and renamed to JavaScript. It is an interpreted scripting language that can be added to HTML pages to provide dynamic interactivity. JavaScript code is executed by the browser's JavaScript engine and does not need to be compiled. It allows manipulating the structure, style, and content of HTML documents, validating form data, detecting browser capabilities, and much more.
This document provides an overview of creating PHP extensions. It discusses PHP's handling of data using zval structures, creating extension files and configuration files, writing helper functions, and the overall layout of the main .c file. The goal is to teach developers how to build custom PHP extensions that add new functionality.
The document discusses different ways to include JavaScript code in HTML documents, including: placing scripts in the <head> or <body> sections; including scripts in both sections; or storing scripts in external .js files and linking to them. It then provides examples and explanations of each approach.
Java Script is one of the most pervasive languages found on the internet and World Wide Web. Java Script is useful in making web pages more interactive. The pages can be made to react to the actions of the users in the form of special effects, both visual and otherwise.
This article is the first part of a series of articles on using JavaScript tools. Today, JavaScript is a very powerful language that can be used to build web apps, mobile apps, and even some pc games — perhaps a bit faster than you would build them otherwise.
New libraries have emerged in the web industry to address the challenges of JavaScript — libraries such as JQuery, Prototype and many others have been released. Today, a popular question asked by many is — should i learn the libraries such as jQuery or learn basic JavaScript. The truth is that the libraries help you to create faster, responsive JavaScript, but there are still times when your basic knowlege of JavaScript will be called into question. It is for this reason that I have created this eBook, to assist newbies learn JavaScript.
JavaScript is a programming language used to make web pages interactive. It can be placed in the <body> and <head> sections of an HTML page. JavaScript code must be inserted between <script> and </script> tags. Functions and events allow JavaScript code to run when events occur, like when a user clicks a button. Scripts can also be placed in external .js files for reuse across pages. JavaScript can output data through alerts, writing to the HTML, or the browser console. Variables are used to store and work with data in JavaScript programs. Comments are used to explain code and prevent execution when needed.
The document discusses JavaScript and some of its key features:
- JavaScript is the programming language of the web browser and was originally developed by Netscape under different names before being standardized.
- JavaScript uses a prototypal object model instead of classes, with objects inheriting directly from other objects via prototypal inheritance chains rather than from classes.
- The "new" keyword is used to create objects but can give the misleading impression of classes; functions can also be used to create objects without "new" by returning the object.
JavaScript is a scripting language that allows adding interactivity to HTML pages. It was originally developed by Netscape as a means to add dynamic content to web pages. JavaScript can be used to create client-side applications, enhance HTML pages with dynamic effects, validate forms, connect to databases, and more. Some key points about JavaScript include that it is embedded directly into HTML, interpreted rather than compiled, loosely typed, object-based, and event-driven. Common JavaScript objects include Window, Document, Location, Form, and more that correspond to HTML elements.
The document discusses generics in .NET. It defines what generics are, provides examples of generic classes and methods, and explains the benefits of using generics such as type safety, performance, and code reuse. It also covers generic type parameters, constraints, and constructed generic types.
JavaScript is a scripting language that adds interactivity to HTML pages. It works in all major browsers and is used to build dynamic web pages. JavaScript can react to events, modify HTML elements, validate forms, detect browsers, and write cookies. It is commonly placed in <script> tags within HTML pages or linked via external .js files. Comments are added to explain JavaScript code and prevent execution.
This document provides an overview of JavaScript including:
- JavaScript is an interpreted programming language that allows adding interactivity to HTML pages.
- It is commonly used for client-side scripting of web pages in browsers.
- Core JavaScript concepts like variables, data types, operators, and functions are introduced.
- Different types of loops in JavaScript like for, for/in, while and do/while loops are explained.
- Best practices for including JavaScript code in HTML files using <script> tags are covered.
JavaScript is the world's most popular programming language. It is used to add interactive effects to web pages. JavaScript code can be inserted into HTML pages between <script> tags. Common JavaScript statements include conditional statements like if/else and loops. Variables are used to store and manipulate data in JavaScript. Common data types include strings, numbers, booleans, arrays, and objects. Functions allow code reuse and organization. Operators are used to assign values, compare values, and perform arithmetic. jQuery is a popular JavaScript library that simplifies DOM manipulation and event handling.
JavaScript Roadmap - The Basics event presentation covers:
- JavaScript Applications
- History of JavaScript
- Basics of JavaScript programming
- Announcements from Codecademy JU chapter
The document discusses JavaScript and its uses. It covers topics like why JavaScript is important for web development, how JavaScript code is inserted into HTML documents using <script> tags, how to define JavaScript functions, and how to place JavaScript code in external files or in the <head> or <body> sections. It also provides examples of using JavaScript to modify HTML elements, displaying output using different methods like innerHTML, document.write(), alert boxes, and the console.
This document provides an overview of computer and web security concepts that will be covered in an IT security course. The course will cover topics such as encryption, digital signatures, firewalls, viruses, and access control methods. It defines computer security as protecting systems from threats to preserve confidentiality, integrity and availability of information and resources. It discusses the need for security due to increasing computer crimes, vulnerabilities, and risks from networks and systems being interconnected. Common security requirements like secrecy, integrity, authenticity, availability and access control are also introduced.
Networking principles involve the transport layer and application layer. The transport layer handles basic communication and reliability, while the application layer provides abstractions like files and services.
The network transfers bits and operates at the application's request, while applications determine what to send, when to send it, where to send it, and the meaning of the bits.
All network applications use a client-server paradigm, where a server waits passively for contact from an active client. A client initiates communication with one server at a time, while a server can handle multiple clients simultaneously. Concurrency allows servers to handle multiple requests without clients waiting.
This document provides an introduction to JavaScript. It discusses the purposes of JavaScript including making web pages interactive by manipulating pages or responding to user actions. It covers basic JavaScript syntax including variables, data types, operators, conditional statements, and functions. It also discusses event-driven programming in JavaScript and how to attach JavaScript functions to HTML elements as event handlers.
This document provides an overview of JavaScript fundamentals including a brief history of JavaScript, its uses, language features, inclusion of scripts in HTML documents, and the JavaScript object model. It discusses the window object and properties like location, frames, history. It also covers variables and data types, operators, control structures, arrays, functions, and communicating with the user through prompts, alerts and changing the status bar.
JavaScript is a scripting language that allows adding interactivity to HTML pages. It can be used for client-side form validation and integration with user plugins. JavaScript is case-sensitive and allows variables, functions, conditional statements, and objects. Common uses include pop-up boxes, event handling, and cookies.
JavaScript is a scripting language that can be inserted into HTML pages and used to program the behavior of web pages. It allows web pages to be dynamic and interactive. JavaScript code is placed between <script> and </script> tags and can manipulate HTML elements and write to the document. Variables, functions, conditional statements, and operators allow JavaScript code to run conditionally based on events or user input. JavaScript is case sensitive, uses semicolons, and has both local and global variables. Common data types include numbers, strings, arrays, and objects.
The document discusses key concepts in .NET including value types, reference types, classes, inheritance, interfaces, generics, boxing and unboxing, exceptions, events and delegates.
It explains that value types like integers store data directly while reference types store references to data on the heap. Common reference types include strings, arrays and streams. Classes can inherit from other classes and implement interfaces. Generics allow types to be parameterized. Events and delegates are used for asynchronous notification. Explicit conversion is needed between non-compatible types.
JavaScript was originally created as LiveScript in 1995 and renamed to JavaScript. It is an interpreted scripting language that can be added to HTML pages to provide dynamic interactivity. JavaScript code is executed by the browser's JavaScript engine and does not need to be compiled. It allows manipulating the structure, style, and content of HTML documents, validating form data, detecting browser capabilities, and much more.
This document provides an overview of creating PHP extensions. It discusses PHP's handling of data using zval structures, creating extension files and configuration files, writing helper functions, and the overall layout of the main .c file. The goal is to teach developers how to build custom PHP extensions that add new functionality.
The document discusses different ways to include JavaScript code in HTML documents, including: placing scripts in the <head> or <body> sections; including scripts in both sections; or storing scripts in external .js files and linking to them. It then provides examples and explanations of each approach.
Java Script is one of the most pervasive languages found on the internet and World Wide Web. Java Script is useful in making web pages more interactive. The pages can be made to react to the actions of the users in the form of special effects, both visual and otherwise.
This article is the first part of a series of articles on using JavaScript tools. Today, JavaScript is a very powerful language that can be used to build web apps, mobile apps, and even some pc games — perhaps a bit faster than you would build them otherwise.
New libraries have emerged in the web industry to address the challenges of JavaScript — libraries such as JQuery, Prototype and many others have been released. Today, a popular question asked by many is — should i learn the libraries such as jQuery or learn basic JavaScript. The truth is that the libraries help you to create faster, responsive JavaScript, but there are still times when your basic knowlege of JavaScript will be called into question. It is for this reason that I have created this eBook, to assist newbies learn JavaScript.
JavaScript is a programming language used to make web pages interactive. It can be placed in the <body> and <head> sections of an HTML page. JavaScript code must be inserted between <script> and </script> tags. Functions and events allow JavaScript code to run when events occur, like when a user clicks a button. Scripts can also be placed in external .js files for reuse across pages. JavaScript can output data through alerts, writing to the HTML, or the browser console. Variables are used to store and work with data in JavaScript programs. Comments are used to explain code and prevent execution when needed.
The document discusses JavaScript and some of its key features:
- JavaScript is the programming language of the web browser and was originally developed by Netscape under different names before being standardized.
- JavaScript uses a prototypal object model instead of classes, with objects inheriting directly from other objects via prototypal inheritance chains rather than from classes.
- The "new" keyword is used to create objects but can give the misleading impression of classes; functions can also be used to create objects without "new" by returning the object.
JavaScript is a scripting language that allows adding interactivity to HTML pages. It was originally developed by Netscape as a means to add dynamic content to web pages. JavaScript can be used to create client-side applications, enhance HTML pages with dynamic effects, validate forms, connect to databases, and more. Some key points about JavaScript include that it is embedded directly into HTML, interpreted rather than compiled, loosely typed, object-based, and event-driven. Common JavaScript objects include Window, Document, Location, Form, and more that correspond to HTML elements.
The document discusses generics in .NET. It defines what generics are, provides examples of generic classes and methods, and explains the benefits of using generics such as type safety, performance, and code reuse. It also covers generic type parameters, constraints, and constructed generic types.
JavaScript is a scripting language that adds interactivity to HTML pages. It works in all major browsers and is used to build dynamic web pages. JavaScript can react to events, modify HTML elements, validate forms, detect browsers, and write cookies. It is commonly placed in <script> tags within HTML pages or linked via external .js files. Comments are added to explain JavaScript code and prevent execution.
This document provides an overview of JavaScript including:
- JavaScript is an interpreted programming language that allows adding interactivity to HTML pages.
- It is commonly used for client-side scripting of web pages in browsers.
- Core JavaScript concepts like variables, data types, operators, and functions are introduced.
- Different types of loops in JavaScript like for, for/in, while and do/while loops are explained.
- Best practices for including JavaScript code in HTML files using <script> tags are covered.
JavaScript is the world's most popular programming language. It is used to add interactive effects to web pages. JavaScript code can be inserted into HTML pages between <script> tags. Common JavaScript statements include conditional statements like if/else and loops. Variables are used to store and manipulate data in JavaScript. Common data types include strings, numbers, booleans, arrays, and objects. Functions allow code reuse and organization. Operators are used to assign values, compare values, and perform arithmetic. jQuery is a popular JavaScript library that simplifies DOM manipulation and event handling.
JavaScript Roadmap - The Basics event presentation covers:
- JavaScript Applications
- History of JavaScript
- Basics of JavaScript programming
- Announcements from Codecademy JU chapter
The document discusses JavaScript and its uses. It covers topics like why JavaScript is important for web development, how JavaScript code is inserted into HTML documents using <script> tags, how to define JavaScript functions, and how to place JavaScript code in external files or in the <head> or <body> sections. It also provides examples of using JavaScript to modify HTML elements, displaying output using different methods like innerHTML, document.write(), alert boxes, and the console.
This document provides an overview of computer and web security concepts that will be covered in an IT security course. The course will cover topics such as encryption, digital signatures, firewalls, viruses, and access control methods. It defines computer security as protecting systems from threats to preserve confidentiality, integrity and availability of information and resources. It discusses the need for security due to increasing computer crimes, vulnerabilities, and risks from networks and systems being interconnected. Common security requirements like secrecy, integrity, authenticity, availability and access control are also introduced.
Networking principles involve the transport layer and application layer. The transport layer handles basic communication and reliability, while the application layer provides abstractions like files and services.
The network transfers bits and operates at the application's request, while applications determine what to send, when to send it, where to send it, and the meaning of the bits.
All network applications use a client-server paradigm, where a server waits passively for contact from an active client. A client initiates communication with one server at a time, while a server can handle multiple clients simultaneously. Concurrency allows servers to handle multiple requests without clients waiting.
PHP is a server-side scripting language commonly used for web development. It allows code to be embedded into HTML pages using tags. When a page request is received by the server, it will execute any PHP code, substitute the output into the HTML page, and send the resulting page to the client. PHP supports different data types including scalars like integers, floats and strings, as well as arrays to store multiple values.
This document provides an overview of HTML and how to create basic web pages using HTML tags. It discusses using Notepad to write HTML code, basic text formatting tags like headings, paragraphs, and line breaks. It also covers inserting images into pages and creating hypertext links to other pages. The document is from an IT course on HTML, presented by instructor Majid Taghiloo.
The document provides an introduction to key concepts about how the web works. It explains that to use the web, a user needs a computer connected to the internet through a modem, network card, or wireless connection. The computer also requires web browser software and must be logged into the web through a service provider. Once logged in, the computer is assigned an IP address to identify its location. When a user enters a URL to request a web page, their IP address is sent along with the request so the page can be routed back to them.
The document summarizes key concepts related to internet applications including the domain name system (DNS), electronic mail, and file transfer. DNS allows users to use domain names instead of IP addresses and works using a distributed client-server model. Electronic mail uses addresses in the format of mailbox@computer to identify mailboxes. Messages can include headers, bodies, and attachments encoded using MIME. Mail is transferred between servers using SMTP.
JavaScript is an object-oriented scripting language used to make webpages interactive. It is lightweight and commonly used as part of web pages. JavaScript can be used to validate user input, provide immediate feedback, and increase interactivity. JavaScript code can output data by writing to HTML elements, using alerts, or writing to the browser console. Key JavaScript concepts include variables, functions, objects, and arrays for storing and manipulating different types of data.
JavaScript is a lightweight, interpreted programming language that runs in web browsers. It was introduced in 1995 to enable dynamic interactivity on web pages. JavaScript is used to add interactive effects and validate forms on web pages. It is an object-based scripting language that is used to make web pages dynamic. Some key features of JavaScript include being event-driven, platform independent, enabling quick development, and being relatively easy to learn. JavaScript uses variables, operators, functions, and objects to manipulate web page elements and interact with users.
JavaScript is a scripting language used to add interactivity to HTML pages. It allows dynamic updating of web page content without reloading the page. JavaScript code can be added inline, embedded, or externally linked in HTML pages. Common JavaScript elements include objects, properties, methods, events, functions, variables, expressions, conditions, loops, and arrays. The DOM (Document Object Model) represents HTML documents and allows JavaScript to access and modify elements dynamically. Cookies are used by JavaScript to store and retrieve information on the client-side.
Malicious Intent: Adventures in JavaScript Obfuscation and DeobfuscationHeadlessZeke
This document discusses JavaScript obfuscation and deobfuscation. It begins with an introduction to the author and an overview of obfuscation. It then covers basic obfuscation techniques like string, number, and whitespace manipulation. Advanced techniques discussed include language idioms, encoding, and polymorphism. The document provides advice for deobfuscation, including getting the code safely, using browsers and plugins, and looking for repeated patterns. It emphasizes that obfuscated code is not always malicious and concludes by noting the challenges of automated analysis.
This afternoon I gave a very short introduction to computer programming at Trade School (tradeschool.ourgoods.org). I used JavaScript to illustrate the process of learning how to program, mainly because there's nothing to install and it has many practical uses.
JavaScript is a scripting language used for client-side and server-side web development. It is a dynamically typed language that is easy to code in and supports features like DOM manipulation, events, functions, and objects. JavaScript can be added to HTML documents in internal <script> tags or externally linked .js files and is used for everything from simple form validation to complex single-page applications.
JavaScript can be used for client-side scripting to add interactivity to web pages. The client-side environment where JavaScript runs is usually a web browser. JavaScript code is transferred from the web server to the user's computer and run directly in the browser. Common uses of JavaScript include adding multimedia elements to pages, creating pages dynamically based on user input, and allowing interaction through events like clicking buttons.
This document outlines the objectives of a lecture on JavaScript. It introduces JavaScript, discusses data types, operators, flow control, functions, events, objects, arrays, and the Document Object Model. It provides examples of JavaScript concepts like functions, events, and objects. The document is intended to teach the basics of JavaScript programming.
The document provides an outline and introduction to JavaScript concepts including variables, functions, conditions, loops, pop-up boxes, objects, and the Document Object Model (DOM). It discusses tasks performed by client-side scripts like form validation, event handling, and dynamic page updates. It also compares client-side and server-side scripting, noting that client-side scripts execute on the browser and allow for interactivity but cannot access local files or databases.
This document discusses JavaScript and its popularity. JavaScript is one of the core languages used to build dynamic web applications. It has enabled features like Google Maps that provide dynamic and interactive experiences to users. JavaScript's cross-platform compatibility allows developers to write code once that runs on different operating systems. It is also used for server-side programming with Node.js. Popular frameworks like React and Angular are built with JavaScript. Overall, JavaScript has become very popular due to its ability to create rich and engaging user interfaces across different platforms and devices.
The document summarizes a JavaScript crash course presentation. It introduces core JavaScript language syntax topics like variables, operators, conditionals, loops, functions and objects. It also discusses embedding JavaScript in HTML using <script> tags and loading external JavaScript files. The document provides references to online JavaScript tutorials and specifications as well as books on JavaScript best practices. It recommends the Firebug plugin for interactive testing of JavaScript in Firefox.
JavaScript New Tutorial Class XI and XII.pptxrish15r890
The document provides an introduction to JavaScript including:
- JavaScript was developed by Branden Eich in 1995 and is a lightweight, interpreted programming language designed for creating network-centric applications.
- JavaScript is dynamic and commonly used for client-side scripting to interact with users and make dynamic web pages. It has object-oriented capabilities.
- The document discusses JavaScript variables, data types, comments, and keywords as well as uses like client-side validation, manipulating HTML, and presentations.
This document outlines the objectives of a lecture on JavaScript. It will introduce JavaScript, including using script tags and linking external JavaScript files. It will cover JavaScript expressions, operators, functions, flow control, objects, arrays, the Document Object Model, forms, cookies and more. The lecture aims to provide an overview of the JavaScript language and how it is used for client-side scripting.
This document provides an introduction to JavaScript, including:
- JavaScript is a scripting language that enhances webpages and makes them more dynamic and interactive. It allows immediate responses without contacting the server.
- JavaScript is interpreted by browsers and is the foundation for complex server-side scripting. It was developed by Netscape, Mozilla Foundation, and Ecma International.
- The document discusses when to use client-side vs server-side programming and provides examples of JavaScript syntax, variables, operators, and control structures like if/else statements and loops.
This document provides an overview of JavaScript, including:
- JavaScript is not related to Java and was originally called LiveScript.
- JavaScript code is run in web browsers by an interpreter built into the browser, not on servers.
- JavaScript can be used to add interactivity to HTML pages by including <script> tags and running code when pages load or in response to user events.
- JavaScript functions and variables can be defined and used to manipulate the DOM and handle user interactions.
This document provides an introduction and overview of JavaScript, including data types, variables, operators, control structures, the Document Object Model (DOM), and debugging techniques. It discusses JavaScript syntax, functions, scopes, arrays, and common language features. It also covers how to include JavaScript in HTML documents, both inline and via external files. The DOM is explained as a way for JavaScript to programmatically access and modify elements in an HTML document.
This document provides an introduction to JavaScript, covering topics such as:
- The scope of the lesson includes an introduction to JavaScript, using JavaScript code, syntax, data types, objects, strings, functions, and standard popup boxes.
- JavaScript is a client-side scripting language that allows interactivity on web pages by modifying HTML content and handling events. It is interpreted by web browsers rather than compiled.
- JavaScript code can be embedded directly in HTML, or linked via external .js files, and is executed when the page loads or in response to events.
JavaScript is a scripting language designed for web pages that is used to add interactivity and dynamic behavior to HTML pages. It was invented in 1995 by Brendan Eich at Netscape and is now the most popular client-side scripting language on the internet. JavaScript code can be included within HTML pages using <script> tags and is interpreted by web browsers rather than compiled. It allows for manipulating HTML elements, writing to documents, validating forms, detecting browsers, and handling events.
2. Outline – Part A
• Overview of JavaScript
i f i
– Versions, embedding, comments
• JavaScript Basics
– Variables and Data Types
– Operators
– Expressions
• JavaScript Control Structures
– Conditional Statements
– Looping Statements
2
3. Introduction
• The growth of the WWW h resulted i a
h h f h has l d in
demand for dynamic and interactive web
sites.
• There are many different kinds of scripting
y p g
languages – JavaScript, …
• This lecture aims at offering in‐depth
in depth
knowledge of JavaScript, discussing the
complexity of scripting and studying various
common examples.
3
4. JavaScript Capabilities
• Improve the user interface of a website
• Make your site easier to navigate
• Easily create pop‐up alert, windows
• Replace images on a page without reload the
p g
page
• Form validation
• Many others …
4
5. JavaScript Versions
• J S i 10
JavaScript 1.0
– Supported by Netscape 2.0 and IE 3.0
• JavaScript 1.1
– Supported by Netscape 3.0 and IE 4.0
• JavaScript 1.2
– Supported by Netscape 4.0 and IE 4.0
• JavaScript 1.3
– Supported by Netscape 4.5 and IE 5.0
• JavaScript 1.5
– Supported by Netscape 6.0 and IE 5.5 and later
5
6. The Future of JavaScript
• ECMA standard brings JavaScript and Jscript together.
– ECMA ‐ An International industry association dedicated to
standardize information and communication systems.
• Both Netscape and Microsoft have pledged that they
will support and develop JavaScript in the future.
• It is future‐proof, and it is not g g to disappear in
p going pp
the near future. ☺
6
7. A Simple Script
<html>
ht l
<head> <title>First JavaScript Page</title> </head>
<body>
<h1>First JavaScript Page</h1>
<script type="text/javascript">
<!--
document.write("<hr>");
document.write("Hello World Wide Web");
document.write( <hr> );
document write("<hr>");
-->
</script>
</body>
/b d
</html>
7
8. Embedding JavaScript
<html>
<head>
<title>First JavaScript Program</title>
</head>
<body>
<script language=“JavaScript” src=“your_source_file.js”></script>
language= JavaScript” src= your_source_file.js”
</body>
/b d
</html>
• A <script> tag can be placed either within
the <head> or <body> tag of an HTML
document.
8
9. JavaScript Source File
<script language=“JavaScript”
language= JavaScript”
src= your_source_file.js”
src=“your_source_file.js”></script>
• SRC – specifies the location of an external script
• TYPE – specifies the scripting language of the script
p p g g g p
• LANGUAGE – specifies the scripting language of the
script
• TYPE and LANGUAGE have a similar function, we use
LANGUAGE to specify the language used in the script
9
10. Need for a source file
• If the J S i code i f i l short, you are
h JavaScript d is fairly h
recommended to include the code in the HTML
document.
document
• To add clarity to an HTML document.
• T share J S i code across multiple HTML
To h JavaScript d li l
documents.
• T h l you hid your J S i code.
To help hide JavaScript d
– Spent lot of time for JavaScript coding.
– Vi
Viewer can only see th l ti of th source fil b t not
l the location f the file but t
the contents.
10
11. Hide JavaScript from incompatible
browsers
<script language=“JavaScript”>
language= JavaScript”
<!–
<!– begin hiding JavaScript
// single-line comment, /* … */ multiple-line comment
single- comment, multiple-
End hiding JavaScript -->
g p -->
</script>
<noscript>
noscript>
Your b
Y browser d
does not support J
JavaScript.
S i
</noscript>
</noscript>
• Not all browsers support JavaScript.
• E g NN1, IE2 character based lynx
E.g. NN1 IE2, character‐based lynx.
11
12. JavaScript confusion
JavaScript Java
Interpreted by the client-side
client- Compiled on the server before
computer executed on the client machine
Dynamic binding object references
binding, Static binding object references
binding,
are checked at runtime must exist at compile time
No need to declare data types
yp Data types must be declared
yp
Code is embedded in HTML Code is not integrated in HTML
Limited by the browser functionality Java applications are standalone
Can access browser objects Java has no access to browser
objects
12
13. Using the alert() Method
<head>
<script language=“JavaScript”>
language= JavaScript”
alert(“An alert triggered by JavaScript”);
</script>
p
</head>
• It is the easiest methods to use amongst alert()
alert(),
prompt() and confirm().
• Y can use i to di l textual i f
You it display l information to
i
the user (simple and concise).
• The user can simply click “OK” to close it.
13
14. Using the confirm() Method
<head>
<script language=“JavaScript”>
language= JavaScript”
confirm(“Are you happy with the class?”);
</script>
p
</head>
• This box is used to give the user a choice either
OK or Cancel.
• I is very similar to the “ l ()” method.
It i i il h “alert()” h d
• You can also put your message in the method.
14
15. Using the alert() Method
<head>
<script language=“JavaScript”>
language= JavaScript”
prompt(“What is your student id number?”);
p
prompt(“What is your name?”,”No name”);
p y
</script>
</head>
• This is the only one that allows the user to type
in his own response to the specific question.
• You can give a default value to avoid displaying
“undefined”.
15
16. Three methods
<script language="JavaScript">
alert("This is an Alert method");
confirm("Are you OK?");
prompt("What is your name?");
prompt( How
prompt("How old are you?","20");
you? "20");
20 );
</script>
16
17. Variables
• J S i allows you to d l
JavaScript ll declare and use variables to
d i bl
store values.
• H to assign a name to a variable?
How i i bl ?
– Include uppercase and lowercase letters
– Digits from 0 through 9
Di i f h h
– The underscore _ and the dollar sign $
– No space and punctuation characters
– First character must be alphabetic letter or underscore –
99Total?, 012345number?, …
– Case‐sensitive
– No reserved words or keywords
y
17
18. Which one is legal?
My_variable
Legal
$my_variable
y_
1my_example
_my_variable
y_
@my_variable
My_var able_example
My variable example
++my_variable
++my_variable
%my variable
my_variable Illegal
#my_variable
~my variable
my_variable
18
myVariableExample
19. Variable on the fly
on‐the‐fly
<head>
<script language=“JavaScript”>
language= JavaScript”
Variable declaration
var id;
id = prompt(“What is your student id number?”);
p p y
alert(id);
name = prompt(“What is your name?”,”No name”);
alert(name);
l ( )
</script>
</head>
• We should use “var” because it is more
easy to keep track of the variables.
19
20. Data Types
• J S i allows the same variable to contain diff
JavaScript ll h i bl i different types
of data values.
• Primitive data types
– Number: integer & floating‐point numbers
– Boolean: logical values “true” or “false”
– String: a sequence of alphanumeric characters
• Composite data types (or Complex data types)
– Object: a named collection of data
– Array: a sequence of values
• Special data types
p yp
– Null: an initial value is assigned
– Undefined: the variable has been created by not yet assigned a value
20
21. Numeric Data Types
• It i an i
is important part of any programming
f i
language for doing arithmetic calculations.
• JavaScript supports:
– Integers: A positive or negative number with no
decimal places.
• Ranged from –253 to 253
g
– Floating‐point numbers: usually written in
exponential notation.
• 3.1415…, 2.0e11
21
22. Integer and Floating‐point number
example
<script language=“JavaScript”>
language= JavaScript”
var i t
integerVar = 100;
V 100;
var floatingPointVar = 3.0e10;
10;
// fl ti -point number 30000000000
floating-
floating i t b
document.write(integerVar);
document.write(integerVar);
document.write(floatingPointVar)
document.write(fl
d floatingPointVar);
P V );
</script>
• The integer 100 and the number 30,000,000,000
will be appeared in the browser window.
pp
22
23. Boolean Values
• A Boolean value i a l i l value of either
l l is logical l f ih
true or false. (yes/no, on/off)
• Often used in decision making and data
p
comparison.
• In JavaScript, you can use the words “true” and
“false” directly to indicate Boolean values
false values.
• Named by the 19th century mathematician
“George Boole”.
“G B l ”
23
24. Boolean value example
<head>
<script language=“JavaScript”>
language= JavaScript”
var result;
result = (true*10 + false*7);
(true
(true*10 false*7
false
alert(“true*10 false*7
alert(“true*10 + false*7 = “, result);
</script>
</head>
• Th expression i converted t
The i is t d to
– (1*10 + 0*7) = 10
24
• They are automatically converted.
25. Strings
• A string variable can store a sequence of
i i bl f
alphanumeric characters, spaces and special
characters.
• String can also be enclosed in single quotation
g g q
marks (‘) or in double quotation marks (“).
• What is the data type of “100”?
100 ?
– String but not number type
• P attention to the special characters.
Pay tt ti t th i l h t
25
26. Strings example
<head>
<script language=“JavaScript”>
language= JavaScript”
document.write(“This
document.write(“This is a string.”);
document.write(“This
document.write(“This string contains ‘quote’.”);
g q
var myString = “My testing string”;
alert(myString);
alert(myString);
</script>
/ i
</head>
• Unlike Java and C, JavaScript does not
have a single character (char) data type.
26
27. typeof operator
<head>
<script language=“JavaScript”>
language= JavaScript”
var x = “hello”, y;
alert(“Variable x value is “ + typeof(x));
typeof(x));
yp
alert(“Variable y value is “ + typeof(y));
typeof(y));
alert(“Variable x value is “ + typeof(z));
typeof(z));
</script>
/ i
</head>
• It is an unary operator.
– Return either: Number, string, Boolean,
, g, ,
object, function, undefined, null
27
28. What is an Object?
• An object is a thing, anything, just as things in
the real world.
– E.g. (cars, dogs, money, books, … )
• In the web browser, objects are the browser
window itself, forms, buttons, text boxes, …
• Methods are things that objects can do.
– Cars can move, dogs can bark.
– Window object can alert the user “alert()”.
• All objects have properties
properties.
– Cars have wheels, dogs have fur.
– Browser has a name and version number.
28
29. Array
• An Array contains a set of d
i f data represented b
d by
a single variable name.
• Arrays in JavaScript are represented by the
Array Object, we need to “new Array()” to
y j , y()
construct this object.
• The first element of the array is “Array[0]”
Array[0]
until the last one Array[i‐1].
• E myArray = new A
E.g. A Array(5)
(5)
– We have myArray[0,1,2,3,4].
29
30. Array Example
<script language=“JavaScript”>
language= JavaScript”
Car = new Array(3);
Array(3
Car[0
Car[0] = “Ford”;
Car[1
Car[1] = “Toyota”;
y
Car[2
Car[2] = “Honda”;
document.write(Car[0 “<br>”);
document.write(Car[0] + “<br>”);
document.write(Car[1 “<br ”)
document.write(Car[1] + “<b >”);
d i (C [ [1 “ br>”);
document.write(Car[2 “<br>”);
document.write(Car[2] + “<br>”);
</script>
• You can also declare arrays with variable length.
– arrayName = new Array();
– Length = 0, allows automatic extension of the length.
30
– Car[9] = “Ford”; Car[99] = “Honda”;
31. Null & Undefined
• An “ d f d” value is returned when you
“undefined” l d h
attempt to use a variable that has not been
defined or you have declared but you forgot to
provide with a value.
• Null refers to “nothing”
• You can declare and define a variable as “null”
null
if you want absolutely nothing in it, but you
just don’t want it to be “undefined”.
don t undefined
31
32. Null & Undefined example
<html>
<head>
<title> Null and Undefined example </title>
<script language=“JavaScript”>
var test1, test2 = null;
test1 test2
alert(“No value assigned to the variable” + test1);
test1
alert(“A null value was assigned” + test2);
test2
</script>
p
</head>
<body> … </body>
</html>
m
32
33. JavaScript Special Characters
l h
Character Meaning
b Backspace
B k
f Form feed
t Horizontal tab
n New line
r Carriage return
Backslash
k l h
’ Single quote
g q
33
” Double quote
35. Arithmetic operators
left_operand “operator” right_operand •
Operator Name Description Example
+ Addition Adds the operands 3+5
- Subtraction Subtracts the right operand 5-3
from the left operand
* Multiplication Multiplies the operands 3*5
/ Division Divides the left operand by the 30 / 5
right operand
% Modulus Calculates the remainder 20 % 5
35
36. Unary Arithmetic Operators
• Binary operators take two operands.
• Unary type operators take only one operand.
y yp p y p
• Which one add value first, and then assign value to the
variable?
Name Example
Post Incrementing operator Counter++
Post Decrementing operator Counter--
Counter--
Pre Incrementing operator ++counter
++counter
Pre Decrementing operator --counter
--counter
36
37. Logical operators
• Used to perform Boolean operations on Boolean
operands
Operator Name Description Example
&& Logical and Evaluate to “true” when both
true” 3>2 &&
operands are true 5<2
|| Logical or Evaluate to “true when either 3>1 || 2>5
operand is true
! Logical not Evaluate to “true” when the
true” 5 != 3
operand is false
37
38. Comparison operators
• Used to compare two numerical values
Operator Name Description Example
== Equal Perform type conversion before checking the “5” == 5
equality
lit
=== Strictly equal No type conversion before testing “5” === 5
!= Not equal “true” when both operands are not equal
true” 4 != 2
!== Strictly not equal No type conversion before testing nonequality 5 !== “5”
> Greater than “true” if left operand is greater than right operand
true” 2>5
< Less than “true” if left operand is less than right operand
true” 3<5
>= Greater than or “true” if left operand is greater than or equal to the
true” 5 >= 2
equal
q right operand
g p
<= Less than or “true” if left operand is less than or equal to the
true” 5 <= 2
38 equal right operand
39. Strict Equality Operators
<script language=“JavaScript”>
scr pt language JavaScr pt
var currentWord=“75”;
currentWord=“75”;
var currentValue=75;
currentValue=75;
var outcome1=(currentWord == currentValue)
outcome1=(currentWord
t ( tW d currentValue);
tV l );
var outcome2=(currentWord === currentValue);
outcome2=(currentWord currentValue);
alert(“outcome1
alert(“outcome1: “ + outcome1 + “ : outcome2: “ + outcome2);
outcome1 outcome2 outcome2
</script>
• Surprised that outcome1 is True!
p
• JavaScript tries very hard to resolve
numeric and string differences
differences.
39
40. String operator
• JavaScript only supports one string
operator for joining two strings.
Operator Name Description Return value
+ String Joins two strings “HelloWorld”
HelloWorld”
concatenation
<script language=“JavaScript”>
var myString = “”
S i “”;
myString = “Hello” + “World”;
alert(myString);
alert(myString);
( y g)
g)
</script>
</script>
40
41. Bit Manipulation
Bi M i l i operators
• Perform operations on the bit representation of
a value, such as shift left or right
value right.
Operator Name Description
& Bitwise AND Examines each bit position
| Bitwise OR If either bit of the operands is 1, the result will be 1
^ Bitwise
Bit i XOR Set the
S t th result bit only if either bit is 1, b t not b th
lt bit, l ith i but t both
<< Bitwise left Shifts the bits of an expression to the left
shift
>> Bitwise signed Shifts the bits to the right, and maintains the sign
right shift
>>> Bitwise zero-fill Shifts the bits of an expression to right
zero-
right shift
41
42. Assignment operators
• Used to assign values to variables
Operator Description Example
= Assigns the value of the right operand to the left operand A=2
+= Add the operands and assigns the result to the left A += 5
operand
-= Subtracts the operands and assigns the result to the left A -= 5
operand
*= Multiplies the operands and assigns the result to the left A *= 5
operand d
/= Divides the left operands by the right operand and assigns A /= 5
the result to the left operand
%= Assigns the remainder to the left operand A %= 2
42
43. The most common problem
<script language=“JavaScript”>
if ( l h = b t ) { … }
(alpha beta)
if (alpha == beta) { … }
</script>
/ i t
• Don’t mix the comparison operator and
Don t
the assignment operator.
• double equal sign (==) and the equal
operator ( )
p (=)
43
45. Precedence Example
Value = (19 % 4) / 1 – 1 - !false
(19
Value = 3 / 1 – 1 - !false
Value = 3 / 1 – 1 - true
Value = 3 – 1 - true
Value
V l =3–2
Value = 1
45
46. Scope of a Variable
• When you use a variable i a JavaScript
h i bl in i
program that uses functions.
• A global scope variable is one that is declared
outside a function and is accessible in any part
yp
of your program.
• A local variable is declared inside a function
and stops existing when the function ends.
46
47. Example of variable data types
variable,
<html><head><title> Billing System of Web Shoppe </title></head><body>
<h1 g
<h1 align="center"> Billing System of Web Shoppe </h1>
g y f pp </h1
<script language="JavaScript">
firstCustomer = new Array();
billDetails = new Array(firstCustomer);
Array(firstCustomer);
var custName, custDob, custAddress, custCity, custPhone;
custName, custDob, custAddress, custCity, custPhone;
var custAmount, custAmountPaid, custBalAmount;
custAmount, custAmountPaid, custBalAmount;
custName=prompt("Enter
custName=prompt("Enter the first customer's name:", "");
custDob=prompt("Enter
custDob=prompt("Enter the first customer's date of birth:", "");
custAddress=prompt("Enter
custAddress=prompt("Enter the first customer's address:", "");
custPhone=prompt("Enter
custPhone=prompt("Enter the first customer's phone number:", "");
custAmount=prompt("Enter
custAmount=prompt("Enter the total bill amount of the first customer:", "");
custAmountPaid=prompt("Enter
custAmountPaid=prompt("Enter the amount paid by the first customer:", "");
custBalAmount = custAmount - custAmountPaid;
custAmountPaid;
firstCustomer[ ]=custName;
firstCustomer[0]=custName;
firstCustomer[ ]=custDob;
firstCustomer[1]=custDob;
]
firstCustomer[ ]=custAddress;
firstCustomer[2]=custAddress;
firstCustomer[ ]=custPhone;
firstCustomer[3]=custPhone;
firstCustomer[ ]=custBalAmount;
firstCustomer[4]=custBalAmount;
document.write("<B>"
document.write("<B>" + "You have entered the following details for first customer:" + "<BR>");
document.write( Name: " + billDetails[0][0] + "<BR>");
document.write("Name:
document write(
write("Name: billDetails[ ][0 <BR> );
document.write("Date
document.write("Date of Birth: " + billDetails[0][1] + "<BR>");
billDetails[ ][1
document.write("Address:
document.write("Address: " + billDetails[0][2] + "<BR>");
billDetails[ ][2
document.write("Phone:
document.write("Phone: " + billDetails[0][3] + "<BR>");
billDetails[ ][3
(custBalAmount == 0) ? document.write("Amount Outstanding: " + custBalAmount):document.write("No amount due")
document.write("Amount custBalAmount):document.write("No
</script></body></html>
/ /b d /h l
47
50. “if” statement
if
if (condition) { statements; }
condition)
• It is the main conditional statement in
JavaScript.
JavaScript
• The keyword “if” always appears in lowercase.
• The condition yields a logical true or false value.
• The condition is true, statements are executed.
50
51. “if” statement example
if
<script language=“JavaScript”>
var chr = “”;
…
if (chr == ‘A’ || chr == ‘O’) {
(chr
document.write(“Vowel
document.write(“Vowel variable”);
}
</script>
“||” operator ‐ increase the speed of the script
51
52. “if … else” statement
if else
if (condition) { statements; }
condition)
else { statements; }
• You can include an “else” clause in an if
statement when you want to execute
some statements if the condition is false.
52
53. Ternary Sh
T Shortcut (
(concise)
i )
<script language=“JavaScript”>
If (3 > 2) {
(3
alert(“True”);
} else {
alert(“False”);
}
(3 > 2) ? alert(“True”) : alert(“False”);
l t(“T ”) l t(“F ls ”)
</script>
• Substitute for a simple “if/else” statement.
53
54. “else if statement
else if”
if (condition) { statement; }
condition)
else if (condition) { statement; }
condition)
else { statement; }
• Allows you to test for multiple expression
for one true value and executes a
particular bl k of code.
ti l block f d
54
55. “if/if else” statement example
if/if…else
<script language=“JavaScript”>
var chr;
chr;
chr = prompt(“Please enter a character : “,””);
if (chr >= ‘A’){
(chr ){
if (chr <= ‘Z’)
(chr
alert( Uppercase );
alert(“Uppercase”);
else if (chr >= ‘a’){
(chr
alert(“Lowercase”);
alert( Lowercase );
}
}
55
</script>
56. “switch” statement
switch
switch (expression) {
expression)
case label1:
label
l b l1
l1
statements; break;
default:
d f lt
statements;
}
• Allows you to merge several evaluation
tests of the same variable into a single
block f t t
bl k of statements.
t
56
57. “switch” statement example
switch
<script language=“JavaScript”>
var chr;
chr;
chr = prompt(“Pls enter a character in lowercase:”,””);
prompt(“Pls
switch(chr){
switch(chr){
case ‘a’ :
alert(“Vowel a”); break;
case ‘‘e’’ :
alert(“Vowel e”); break;
default :
alert(“Not a vowel”);
}
</script>
57
59. “for” statement
for
for (initial_expression; test_exp; change_exp)
initial_expression; test_exp; change_exp)
{ statements; }
t t t
• One of the most used and familiar loops is the
for loop.
• It iterates through a sequence of statements for
a number of times controlled by a condition.
• The change exp determines how much has
change_exp
been added or subtracted from the counter
variable.
59
60. “for” statement example
for
<script language=“JavaScript”>
var counter;
for (counter = 1; counter <= 10; counter++)
10; counter++)
{
document.write(counter*counter
document.write(counter*counter + “ “);
}
</script>
• Display the square of numbers
• Output: 1 4 9 16 25 36 49 64 81 100
60
61. “for/in” statement
for/in
for (counter_variable in object)
{ statements; }
t t t
• When the for/in statement is used, the counter
and termination are determined by the length of
the object.
j
• The statement begins with 0 as the initial value
of the counter variable, terminates with all the
properties of the objects have been exhausted.
– E.g. array no more elements found
61
62. “for/in” statement example
for/in
<script language=“JavaScript”>
var b k (Wh t is the difference if “var book=“”;)
book; (What i th diff “var b k “” )
var booklist = new Array(“Chinese”, “English”, “Jap”);
for (var
f (var counter i b kli t) {
t in booklist
booklist)
t)
book += booklist[counter] + “ “;
}
alert(book);
</script>
62
63. “while” statement
while
initial value declaration;
while (condition) {
hil condition)
diti
statements;
increment/decrement statement;
i t/d t t t t
}
• The while loop begins with a termination condition and
keeps looping until the termination condition is met.
• The counter variable is managed by the context of the
statements inside the curly braces.
63
64. “While” statement example
While
<html>
<head>
<title>While loop example</title>
<script language=“JavaScript”>
var counter = 100;
t 100;
var numberlist = “”;
while (counter > 0) {
numberlist += “Number “ + counter + “<br>”;
“<br>”;
counter -= 10;
10;
}
document.write(numberlist);
document.write(numberlist);
</script> <body> … </body>
/s i t> b d > /b d >
64
</html>
65. “do … while” statement
do while
do {
statements;
t t t
counter increment/decrement;
} while (t
hil termination condition)
i ti condition)
diti
• The do/while loop always executes
statements in the loop in the first iteration
of the loop
loop.
• The termination condition is placed at the
bottom of the loop.
65
67. Outline – Part B
• JavaScript Functions and Events
i i d
– Events Handlers
• Using Object in JavaScript
– Object‐Oriented Programming
Object Oriented
– JavaScript Object Model
– Using Built In objects (Predefined Object)
Built‐In
– Custom Object Types
• E
Error i J S i
in JavaScript
• Exception Handling in JavaScript
p g p
67
68. Functions
• Affunction i a bl k of organized reusable
i is block f i d bl
code (a set of statements) for performing a
single or related action.
• Begins with keyword “function” and the
g y
function name and “( … )”
• Inside the parentheses
– We can pass parameters to the function
– E f ti myfuc(arg1, arg2) { }
E.g. function f ( 1 2) {…}
– Built‐in and user‐defined functions
68
69. Built‐In
Built In Functions
• F
Functions provided b the l
i id d by h language and you cannot change
d h
them to suit your needs.
• Some of the built‐in functions in JavaScript are shown here:
built in
– eval ‐ eval(expr)
• eval evaluates the expression or statements
– isFinite
• Determines if a number is finite
– isNaN
• Determines whether a value is “Not a Number”
– parseInt
• Converts string literals to integers no number
integers, NaN.
NaN
– parseFloat
• Finds a floating‐point value at the beginning of a string.
69
70. User‐Defined
User Defined Functions
• For some functionality, you cannot achieve by
only using the built‐in functions.
y g
• You can define a function as follows
function <function_name> (parameters)
function_name>
{
// code segments;
70
}
71. Function Declarations
• Declaration Syntax
– Functions are declared using the function reserved word
g
– The return value is not declared, nor are the types of the
arguments
– Examples:
function square(x) { return(x * x); }
square(x)
function factorial(n) {
factorial(n)
if (n <= 0) {
return(1
return(1);
} else {
return(n * factorial(n - 1));
}
}
71
72. Events
• Events are the actions that occur as a result of
browser activities or user interactions with the
web pages.
– Such as the user performs an action (mouse click
or enters data)
– W can validate th d t entered b a user i a
We lid t the data t d by in
web form
– Communicate with Java applets and browser plug‐
ins
72
73. Event Categories
• K b d and mouse events
Keyboard d
– Capturing a mouse event is simple
• Load events
d
– The page first appears on the screen: “Loads”, leaves:
“Unloads”, …
Unloads
• Form‐related events
– onFocus() refers to placing the cursor into the text input in
the form.
• Others
– Errors, window resizing.
73
74. Events defined by JavaScript
HTML elements HTML JavaScript Description
tags defined events
Link <a> click Mouse is clicked on a link
dblClick Mouse is double-clicked on a link
double-
mouseDown Mouse button is pressed
mouseUp Mouse button is released
mouseOver
O Mouse
M is moved over a link
i d li k
Image <img> load Image is loaded into a browser
abort Image loading is abandoned
error An error occurs during the image loading
Area <area> mouseOver The mouse is moved over an image map area
mouseOut The mouse is moved from image map to outside
dblClick The mouse is double-clicked on an image map
double-
Form <form> submit The user submits a form
Reset The user refreshes a form
… … … …
74
75. Event Handlers
• When an event occurs, a code segment i
h d is
executed in response to a specific event is
called “
“event handler”.
”
• Event handler names are quite similar to the
q
name of events they handle.
• E g the event handler for the “click” event is
E.g click
“onClick”.
• <HTMLtag eventhandler=“JavaScript Code”>
75
76. Event Handlers
Event Handlers Triggered when
onChange The value of the text field, textarea, or a drop down list
is modified
onClick
Cl k A l k an image or a form element is clicked once
link, f l l k d
onDblClick The element is double-clicked
double-
onMouseDown The user presses the mouse button
onLoad A document or an image is loaded
onSubmit A user submits a form
onReset The form is reset
onUnLoad The user closes a document or a frame
onResize A form is resized by the user
76
77. onClick event Handler
<html>
<head>
<title>onClick Event Handler Example</title>
<script language=“JavaScript”>
p language= JavaScript”
g g p
function warnUser(){ return confirm(“INE2720 students?”); }
confirm(“INE2720
</script>
</head>
/h d
<body>
<a href=“reference html”, onClick=“return warnUser();”>INE2720
href= reference.html onClick=“return warnUser();”>INE2720
onClick=
= >INE2720
>INE
Students access only</a>
</body>
</html>
77
78. onLoad event Handler
<html>
<head>
<title>onLoad and onUnload Event Handler Example</title>
</head>
<body onLoad=“alert(‘Welcome User’);”
onLoad=“alert(‘Welcome User’);”
onUnload=“alert(‘Thanks
onUnload=“alert(‘Thanks for visiting the page’);”>
page’);”>
Load and UnLoad event test.
</body>
</html>
78
79. User E
U Events, Form E
F Example
l
<html><head>
<title>Simple JavaScript Button</title>
<script language= JavaScript ><!
language=“JavaScript"><!--
function dontClick() {
alert("I told you not to click!");
}
// --></script>
</head>
<body>
<h1>Simple JavaScript Button</h1>
<form>
<input type=“button"
value="Don't Click Me"
onClick="dontClick()">
</form>
</body></html>
79
80. onMouseOver and onMouseOut Event
Handlers
<html>
<head>
h d>
<title>onMouseOver and onMouseOut event handler</title>
</head>
/head
<body>
<a href=“link.html”
onMouseOver = “status = ‘Now mouse is over the link’; “
onMouseOut = “status = ‘Mouse has moved out’;”>
A Link Page
</a>
</body>
/body
</html>
80
81. Understanding JavaScript Objects
• One of the most important features of JavaScript,
enables modular programs.
• Objects are based on Classes, variables, functions,
statements are contained in a structure called class.
Class
varA varB
varC varD
FunctionA (…) FunctionB (…)
FunctionC ( )
(…) FunctionD ( )
(…)
81
82. Class and Object
• You can instantiate an object from a class by using
the constructor function.
• JavaScript is said to be an Object‐based programming
language.
• What is property?
– A variable belongs to the object.
• What is method?
– It is a function belongs to the object
object.
– Function‐Valued Properties
82
83. Creating Instances of Objects
f b
• You can use the “new” operator to create instances of
objects of a particular class or object type.
– Variable = new objectType(parameters)
• This objectType() is called constructor.
• E.g. Date is a predefined object type.
– Assign the current date and time to objA
g j
• objA = new Date()
– Assign another date and time to objB
• objB = new Date(99,23,5) 23 May, 99
83
84. Objects and Classes
• Fields Can Be Added On‐the‐Fly
i ld dd d h l
– Adding a new property (field) is a simple matter
of assigning a value to one
– If the field doesn’t already exist when you try to
assign to it, JavaScript will create it automatically.
– For instance:
var test = new Object();
test.field1
test field1 = "Value 1"; // Create field1 property
Value 1 ;
test.field2 = 7; // Create field2 property
84
85. Objects and Classes – Literal Notation
• You Can Use Literal Notation
Y C U Lit l N t ti
– You can create objects using a shorthand “literal” notation of the
form
{ field1:val1, field2:val2, ... , fieldN:valN }
– For example, the f ll
l h following gives equivalent values to object1 and
l l d
object2
var object1 = new Object();
var object2 = new Object();
object1.x = 3;
object1.y = 4;
j y
object1.z = 5;
object2 = { x:3, y:4, z:5 };
85
86. Objects and Classes ‐ Constructor
• A “Constructor” is Just a Function that Assigns to “this”
• JavaScript does not have an exact equivalent to Java s class definition
Java’s
• The closest you get is when you define a function that assigns values
to properties in the this reference
• Calling this function using new binds this to a new Object
• For example, following is a simple constructor for a Ship class
function Ship(x, y, speed, direction) {
this.x = x;
this.y
this y = y;
this.speed = speed;
this.direction = direction;
}
86
87. Constructor,
Constructor Example
var ship1 = new Ship(0, 0, 1, 90);
87
88. Class Methods Example
Methods,
function degreesToRadiansversion of the Ship class that includes a move method
degreesToRadians(degrees) {
Consider a (degrees) •
return(degrees * Math.PI / 180.0);
180.
}
function move() {
var angle = degreesToRadians(this direction);
degreesToRadians(this.direction
this.direction);
direction);
this.x = this.x + this.speed * Math.cos(angle);
this.y = this.y + this.speed * Math.sin(angle);
}
function Ship(x, y, speed, direction) {
this.x = x;
this.y = y;
this.speed = speed;
this.direction = direction;
this.move = move;
hi
}
88
89. Class Methods Result
Methods,
var ship1 = new Ship(0, 0, 1, 90);
ship1.move();
ship1 move();
89
90. Objects and Classes ‐ Arrays
• Arrays
A
• For the most part, you can use arrays in JavaScript a lot like Java arrays.
• Here are a few examples:
var squares = new Array(5);
A (5)
for(var i=0; i<squares.length; i++) {
vals[i] = i * i;
}
// Or, in one fell swoop:
var squares = new Array(0, 1, 4, 9, 16);
var array1 = new Array("fee", "fie", "fo", "fum");
// Literal Array notation for creating an array.
var array2 = [ "fee", "fie", "fo", "fum" ];
• Behind the scenes, however, JavaScript simply represents arrays as objects
with numbered fields
• You can access named fields using either object.field or
object["field"], but numbered fields only via object[fieldNumber]
90
91. Array,
Array Example
var arrayObj = new Object();
arrayObj[0] = "Index zero";
arrayObj[10] = "Index ten";
arrayObj.field1
arrayObj field1 = "Field One";
Field One ;
arrayObj["field2"] = "Field Two";
91
92. Build‐In J S i Objects
B ild I JavaScript Obj
Object Description
Array Creates new array objects
Boolean Creates new Boolean objects
j
Date Retrieves and manipulates dates and times
Error Returns run-time error information
run-
Function Creates new function objects
Math Contains methods and properties for performing mathematical
calculations
l l ti
Number Contains methods and properties for manipulating numbers.
String Contains methods and properties for manipulating text strings
92
94. Error and Exception Handling in
JavaScript
• While executing your code, runtime
hil i d i
exceptions occur.
• How can you write error‐free scripts?
– The onerror event handler
– The Error object
• http://www irt org/xref/Error htm
http://www.irt.org/xref/Error.htm
– The throw statement
– The try … catch … finally block
• Error and Exception are the same.
94
95. onerror Event Handler
• E
Errors may occur d t
due to
– syntax errors
•S
Syntax i the rules of grammar and spelling
is h l f d lli
– runtime errors
• The script tries to perform something the system
(browser) cannot do.
• To capture error event, JavaScript provides the
onerror event handler.
• The onerror event handler is associated with
the window object.
95
96. How to use “onerror” event handler?
onerror
<html>
<head>
<title>onerror event handler example /title
<title>onerror
title example</title>
<script language=“JavaScript”>
Function errorHandler(){
errorHandler(){
alert( an
alert(“an error has ocurred”);
ocurred”);
);
}
window.onerror = errorHandler;
errorHandler;
</script>
</head>
<body>
<script l
i language=“JavaScript”>
“J i ”
document.write(“Hello
document.write(“Hello there;
</script>
</body>
96 </html>
97. Exception Handling in JavaScript
• An exception is an error generated by the script.
• Th code that h dl an exception i called an
The d h handles i is ll d
exception handler that will catch exceptions.
Normal script flow of control
p
The exception is caught
and handled by an
exception handler
If an error is occurred,
An exception will be thrown.
97
98. try … catch … finally
try
{
// normal statements
// might result in an error, throw exceptions
}
catch(errorVariable)
catch(errorVariable)
{
// statements that execute in the exception event
}
finally
{
// After the execution in the catch or try block,
// the statements in the finally block are executed.
h i h fi ll bl k d
98 }
100. Outline – Part C
• Working with Browser Objects
– Document Object Model (DOM)
• Window, document, history, location Objects
• Properties and Methods
–F
Form V lid ti S i t
Validation Script
• Creating Cookies in JavaScript
– Constructing a standard cookie
– Cookie Property
– Interaction with the cookie
– Using JavaScript to manipulate HTTP cookies
100
101. Using Browser Objects
• In the previous lectures, you were introduced to
predefined objects in JavaScript
– Math, String, Object, Boolean, Date, …
• JavaScript also provides you with objects that can
control and manipulate the displays of browsers.
– More dynamic and interactive.
y
• When a browser loads a webpage, it creates a
number of JavaScript objects.
101
102. Document Object Model (DOM)
history
• DOM i an object‐oriented model that d
is bj i d d l h describes h
ib how
all elements in an HTML page are arranged.
• I is used to l
It i d locate any object i your HTML page (
bj in (an
unique address).
• Th
There are diff
different DOM l l
levels
– The Level 0 DOM (DOM0)
– The Level
Th L l 1 DOM (DOM1)
– The Level 2 DOM (DOM2)
– The Level 3 DOM (DOM3)
• Under development
102
103. How the DOM works?
<head><script>
function toggle()
{ document.img.button1.src=“button_on.gif”; }
document.img.button1
</script></head> reaction
action
<body>
<a href=“test.html” onmouseover=“toggle()”> <img name=“button1” src=“button_off.gif”></a>
href=“test.html” onmouseover=“toggle()”> <img name=“button1 src=“button_off.gif”></a>
</body>
Action Event JavaScript DOM Reaction
src=“button_off.gif” onmouseover toggle() document.img.button1 Src=“button_on.gif”
User moves mouse over object (١
Event senses that something happened to the object (٢
JavaScript tells the object what to do (Even handler) (٣
Locates object on the web page (۴
103 Object’s image source is changed (۵
104. Browser Hierarchy Model
window
document frame location history
anchor image form link
button checkbox
radio select
reset textarea
text submit
104
105. The “window” Object
window
• It is the highest‐level object in the JavaScript browser
object hierarchy.
• It is the default object and is created automatically
when a page is loaded.
• Since it is the default object, we may omit writing
window e p c y
do explicitly.
– document.write(“a test message”);
– window.document.write(“a test message”);
• It also includes several properties and methods for us
to manipulate the webpage.
p p g
105
106. Properties and methods of the
“window” Object
Property Description
length An integer value representing the number of frames in the
window
name A string value containing the name of a window
parent A string value containing the name of the parent window
status A string value representing status bar text
Method Description
alert(text) Pop up a window with “text” as the message
text”
close() Closes the current window
open(url) Open a new window populated by a URL.
setTimeout(expression, time) Executes an expression after the elapse of
106 the interval time.
107. Example of using the “window” Object
window
• Opening and closing windows
• Window attributes of the “open()” method
Attribute Description
p
toolbar Creates the standard toolbar
location Creates the location entry field
directories Creates standard directory buttons
status Creates the status bar
menubar Creates the menu bar at the top of a window
scrollbars Creates scrollbars when the document exceeds the window size
resizable Enables the user to resize the window
width Specifies the width of the window
107
height Specifies the height of the window
108. The “document” Object
document
It is one of the important objects in any window or •
frame.
The document object represents a web document or •
a page in a browser window.
When you access multiple sites simultaneously, there •
would be multiple windows ope ed
ou d u pe do s opened.
Each window would have a corresponding window object, –
and each window object would have its own document
j
object.
108
109. Properties and methods of the
“document” Object
Property Description
bgColor A string value representing the background color of a document
alinkColor A string value representing the color for active links
location A string value representing the current URL
g p g
title A string value representing the text specified by <title> tag
Method Description
clear() Clears the document window
write(content)
ite(content) Writes the text of content to a doc ment
W ites te t document
writeln() Writes the text and followed by a carriage return
open() Open a document to receive data from a write() stream
109
close() Closes a write() stream
110. The “history” Object
history
Each time you visit a web page and click on •
h i ii b d li k
the “Back” or “Forward” arrow buttons on your
browser toolbar, you are accessing the history
list.
You can also add similar buttons / links that •
allow users to move backward and forward via
the information stored in the history object.
110
111. Properties and methods of the
“history” Object
Property Description
length An integer value representing the number of links in the
history object
current Contains the URL of the current page
p g
next Contains the URL of the next entry in the history list
previous Contains the URL of the previous entry in the history list
Method Description
back() Sends the user to the previous page in the history list
forward() Sends the user to the next page in the history list
go(x) Sends back or forward by “x” number of pages in the
history list
111
112. The “form” Object
form
• The form object is accessed as a property of the
document object.
• Each form element in a form (text input field, radio
buttons), is further defined by other objects.
• The browser creates a unique “form” object for each
form in a docu e
o document.
• You can access the form object “form1”
– document form1
document.form1
112
113. Form Element Based Objects
Element‐Based
• HTML forms can include eight types of input
elements
– Text fields, Textarea fields
– Radio buttons
– Check box buttons
– Hidden fields
– Password fields
– Combo box select menu
– List select menu
– Each object has its own properties and methods.
113
114. Form Validation Script
<html><head>
<html><head> <body>
<title>Form Example</title> <h1
<h1>Form Example</h1>
Example</h1
<script LANGUAGE="JavaScript">
LANGUAGE= JavaScript > <p>Enter the following information When you press the Display
information.
function validate() { button, the data you entered will be validated, then sent by email.</p>
if (document.form1.yourname.value.length < 1) {
(document.form1
alert("Please enter your full name."); <form name="form1" action="mailto:user@host.com"
name="form1
return false; enctype="text/plain“ onSubmit="validate();">
yp p ();
}
if (document.form1.address.value.length < 3) {
(document.form1 <p><b>Name:</b> <input type=“text" length="20" name="yourname">
length="20" name="yourname">
alert("Please enter your address."); </p>
return f ls ;
t n false; <p><b>Address:</b> <input type=“text" length="30" name="address">
p b Address /b input type text length="30" name="address">
length 30 name address
} </p>
if (document.form1.phone.value.length < 3) {
(document.form1 <p><b>Phone: </b> <input type=“text" length="15" name="phone">
length="15" name="phone">
alert("Please enter your phone number."); </p>
return f l
t false; <p><input type=“submit" value="Submit"></p>
type= submit value= Submit ></p>
}
return true; </form>
} </body>
</script>
/ </html>
</head>
114
115. Application: Using JavaScript to Validate CGI
Forms
1.
1 Accessing F
A i Forms
– The document.forms property contains an array of Form entries
contained in the document
– As usual in JavaScript, named entries can be accessed via name
instead of by number, plus named forms are automatically inserted
as properties in the document object, so any of the following
p p j , y g
formats would be legal to access forms
var fi tF m = d
firstForm document.forms[0];
m t f m [0];
// Assumes <FORM NAME="orders" ...>
var orderForm = document.forms["orders"];
F m um n .f m [ ];
// Assumes <FORM NAME="register" ...>
var registrationForm = document.register;
115
116. Application: Using JavaScript to Validate CGI
Forms, cont.
2. Accessing Elements within Forms
– The Form object contains an elements property that holds an array
of Element objects
– You can retrieve form elements by number, by name from the array,
or via the property name:
var firstElement = firstForm.elements[0];
// Assumes <INPUT ... NAME="quantity">
E " "
var quantityField = orderForm.elements["quantity"];
// Assumes <INPUT ... NAME= submitSchedule >
NAME="submitSchedule">
var submitButton = register.submitSchedule;
116
117. Checking Form Values Individually,
Example
<html><head><title>On-Line Training</title>
<script language=“JavaScript">
<!--
// Wh
When the user changes and leaves t tfi ld check
th h d l textfield, h k
// that a valid choice was entered. If not, alert
// user, clear field, and set focus back there.
function checkLanguage() {
// or document.forms["langForm"].elements["langField"]
var field = document.langForm.langField;
var lang = field.value;
var prefix = lang.substring(0, 4).toUpperCase();
if (prefix != "JAVA") {
alert("Sorry, '" + lang + "' is not valid.n" +
"Please try again ");
Please again. );
field.value = ""; // Erase old value
field.focus(); // Give keyboard focus
}
}
117
118. Checking Form Values Individually,
Example, cont.
// -->
</script></head>
<body><h1>On-Line Training</h1>
y g
<form action="cgi-bin/registerLanguage" name="langForm">
To see an introduction to any of our on-line training
courses, please enter the name of an important Web
programming language below.
<p>
<b>Language:</b>
<input type=“text" name="langField"
onFocus="describeLanguage()" onBlur="clearStatus()"
onChange="checkLanguage()">
<p>
<input type=“submit" value="Show It To Me">
</form>
</body>
</html>
118
120. Checking Values When Form is Submitted,
Example
<html><head><title>Camp Registration</title>
<script language=“JavaScript">
<!--
!
function isInt(string) {
var val = parseInt(string);
return(val > 0);
}
function checkRegistration() {
var ageField = document.registerForm.ageField;
if (!isInt(ageField.value)) {
alert("Age must be an integer.");
return(false);
}
...
// Format looks OK. Submit form.
return(true);
}
// -->
120
</script>
121. Checking Values When Form is Submitted,
Example, cont.
<body><h1>Camp Registration</h1>
<form action="cgi-bin/register“ name="registerForm"
onSubmit="return(checkRegistration())">
( g ())
Age: <input type=“text" name="ageField" onFocus="promptAge()"
onBlur="clearStatus()"><br>
Rank: <input type=“text" name="rankField" onFocus="promptRank()"
onBlur="clearStatus()"><br>
Serial Number: <input type=“text" name="serialField"
onFocus="promptSerial()" onBlur="clearStatus()"><p>
<input type=“submit" value="Submit Registration">
</form>
</body>
</html>
/ht l
121
123. Why we need Cookies?
• The web servers process requests efficiently because
they did not need to maintain any unique
requirements for different clients.
• Web browsers treat every visit to a web page as an
entirely new session, even if users open a different
web page on the same server.
• The client information becomes more important for
commercial purposes.
p p
123
124. Cookie Basics
• When a user closes the browser, the information
contained in a hidden form field will be lost.
• A cookie is used to store information on the user’s
computer even when the user switches off his/her
computer.
• It is a da a that is se from a web se e to a web
s data a s sent o eb server o eb
browser when the user visits a site on a server.
– It is just a .txt file in a user’s computer.
user s
124
125. Features of Cookies
• A cookie can b associated with one or more
ki be i d ih
documents on the web server.
• More than one cookie can be associated with
a document on the web server.
• Every cookie has a NAME‐VALUE pair
associated with it
it.
• Cookies have an expiration date associated
with th
ith them.
125
126. Cookies Applications
• Web page customization for each user
• Form information storage
• Shopping carts for order information
• Store userID and password
• Track how many times the user has visited
• Maintain a past score for each player on a test or
online games
126
127. Application: Using JavaScript to Store and
Examine Cookies
1. Using document.cookies
– Set it (one cookie at a time) to store values
( )
document.cookie = "name1=val1";
document.cookie
document cookie = "name2=val2; expires=" + someDate;
name2 val2; expires
document.cookie = "name3=val3; path=/; domain=test.com";
– Read it (all cookies in a single string) to access
values
127
128. Application: Using JavaScript to Store and
Examine Cookies
2.
2 Parsing Cookies
P i C ki
function cookieVal(cookieName, cookieString) {
var startLoc = cookieString indexOf(cookieName);
cookieString.indexOf(cookieName);
if (startLoc == -1) {
return(""); // No such cookie
}
var sepLoc = cookieString.indexOf("=", startLoc);
var endLoc = cookieString.indexOf(";", startLoc);
if (endLoc == -1) { // Last one has no ";"
endLoc = cookieString.length;
}
return(cookieString.substring(sepLoc+1, endLoc));
}
128
129. Cookie,
Cookie Example
<html><head>
<title>Widgets "R" Us</title>
<script language=“JavaScript">
<!--
!
function storeCookies() {
var expires = "; expires=Monday, 01-Dec-02 23:59:59 GMT";
var first = document widgetForm firstField value;
document.widgetForm.firstField.value;
var last = document.widgetForm.lastField.value;
var account = document.widgetForm.accountField.value;
document.cookie = "first=" + first + expires;
document.cookie = "last=" + last + expires;
document.cookie = "account=" + account + expires;
}
// Store cookies and give user confirmation.
function registerAccount() {
storeCookies();
()
alert("Registration Successful.");
}
129
130. Cookie, Example, cont.
Cookie Example cont
f
function cookieVal(cookieName, cookieString) {
( m , g)
var startLoc = cookieString.indexOf(cookieName);
if (startLoc == -1) {
return(""); // No such cookie
}
var sepLoc = cookieString.indexOf("=", startLoc);
var endLoc = cookieString.indexOf(";", startLoc);
if (endLoc == -1) { // Last one has no ";"
endLoc = cookieString length;
cookieString.length;
}
return(cookieString.substring(sepLoc+1, endLoc));
}
function presetValues() {
var firstField = document.widgetForm.firstField;
var lastField = document.widgetForm.lastField;
var accountField = document widgetForm accountField;
document.widgetForm.accountField;
var cookies = document.cookie;
firstField.value = cookieVal("first", cookies);
lastField.value = cookieVal("last", cookies);
accountField.value cookieVal( account
accountField value = cookieVal("account", cookies);
}
// --></script></head>
130
131. Cookie, Example, cont.
Cookie Example cont
<body onLoad="presetValues()">
onLoad= presetValues() >
<h1>Widgets "R" Us</h1>
<form action="servlet/cwp.Widgets" name="widgetForm"
f ti " l t/ Wid t " " id tF "
onSubmit="storeCookies()">
First Name: <input type=“text" name="firstField"><br>
F N “ " "f F ld" b
Last Name: <input type=“text" name="lastField"><br>
Account Number: <input type=“text" name="accountField"><br>
Widget Name: <input type=“text" name="widgetField"><br>
<input type=“button" value="Register Account" onClick="registerAccount()">
<input type=“submit" value="Submit Order
input type submit value Submit Order">
</form>
</body>
</html>
131
133. Outline – Part D
• I t d i DHTML
Introducing
– Styles and Layers
– Dynamic Positioning
– Moving objects in 3D
– Internet Explorer Filters
l il
• Using DHTML and CSS Tools
• Cool JavaScript Sites
• JavaScript and DHTML Reference
p
• Summary
133
134. Dynamic HTML
• Everyone is a Web Designer.
– Learning DHTML, CSS and JavaScript is your next step into
the web design world.
• “DHTML” is a term used by some vendors to describe
the combination of HTML, style sheets and scripts
that allows documents to be animated.
• Web pages can be made to respond to users’ actions.
• Problem: How to achieve “Dynamic”?
Dynamic ?
134
135. DHTML advantages / disadvantages
• Supported b most b
d by browsers
• Small file sizes (faster than Flash)
( )
• No plug‐ins required
• Easy to learn (learn HTML, JavaScript)
HTML
• Faster web experience (change the page
content without l
h load new pages) )
• Browser and OS incompatibilities
p
– The implementation of CSS, DOM varies from
browser to browser
135
136. What makes a web site dynamic?
• I
Interactivity – adapt and react to the visitor’s actions
i i d d h ii ’ i
as quick as possible.
• S h i i – b i together relevant i f
Synchronicity bring h l information
i
from a variety of sources.
• Fl ibili – give the visitor diff
Flexibility i h i i different ways to fi d find
information in the site.
• Ad
Adaptability – adjusts to cater to i di id l visitor’s
bili dj individual i i ’
needs.
• A i i – uses motion and sound to d
Activity i d d draw user’s ’
attention to changes on the site.
136
137. The Role of each component in DHTML
• With CSS, we can change the style of any
ih h h l f
HTML elements.
• With DOM, we can have a map on every
elements in the HTML page.
p g
• With JavaScript, we can access and have
operations on the elements in the DOM tree
tree.
• With event handler, we can execute the
predefined scripts at any ti
d fi d i t t time.
137
138. Cross‐Browser
Cross Browser DHTML
Netscape 4.x Cross-Browser
Cross- Internet Explorer
DHTML 4.x
JavaScript CSS1 CSS2
CSS1, CSS2, Visual Filters
Style Sheets CSS-
CSS-Positioning allow you to apply
(JSS) JavaScript
p visual effects to
Netscape DOM text or graphics
Layers
y Data Binding g
(positioning,
visibility)
y)
138
139. Open a new browser window
• Pop‐up windows are useful for navigation
pp
controls, advertisements, supplementaryy
contents.
• You can open a window close the window or
window, window,
toggle the window.
139
140. Dynamic Technique:
Change CSS Styles
• You can change or add to any CSS property
defined for
d fi d f any object on the screen.
bj h
onMouseOver()
140
141. Change Background Color
<html><head>
<script language="JavaScript">
function bgChange(bg)
{ document.body.style.background=bg; }
</script></head>
<body><b>Mouse over these table cells, and the background color will change</b>
<table width="300" height="100">
<tr>
<td onmouseover="bgChange('red')"
onmouseout="bgChange('transparent')" bgcolor="red">
</td>
<td onmouseover="bgChange('blue')"
onmouseout="bgChange('transparent')" bgcolor="blue">
</td>
<td onmouseover="bgChange('green')"
onmouseout="bgChange('transparent')” bgcolor="green">
</td>
</tr>
</table>
</body></html>
141
143. Dynamic Positioning
• It means the HTML elements can be
positioned by using JavaScript
JavaScript.
• The element is moved by manipulating
any of the “top”, “left”, “right” and
top left right
“bottom” CSS properties.
• The more table you use the slower your
use,
page displays.
• Positioning elements with CSS is more
accurate than tables and the results are
displayed much faster
faster.
143
144. Moving Objects from Point to Point
• Using CSS, you can change the position of
an object on the screen.
bj h
144
145. Moving Objects in 3 D
3‐D
• By specifying the z‐index, we can put the
objects i 3 D manner.
bj t in 3‐D
145
146. Moving the browser window
• You can set an initial position of multiple windows.
146
147. IE DHTML Visual Controls
• The blurOn() Filter causes the image to
blur
bl on th screen.
the
147
148. IE Transition Filters
• Produce transitions between web pages.
Transition Reference #
Box In 0
Box Out 1
Circle out 3
Wipe up 4
Wipe down 5
Wipe right
Wi i ht 6
Wipe left 7
Random Dissolve 12
Random 23
148
149. Adding last modified Date
<html>
<head>
<title>Enter the title of your HTML document here</title>
</head>
<body>
<script language=“JavaScript”>
document.write( Page
document write(“Page last modified: “ + document lastModified)
document.lastModified)
</script>
</body>
</html>
149
150. Creating a Sliding Menu
• Allow visitors to pull out menus or put them away.
150
151. Follow the Mouse Pointer
• The mouse pointer is part of the user interface
that gives designer controls.
g g
151
152. Application: Using JavaScript to Make Pages
Dynamic
• Modifying Images Dynamically
– The document.images property contains an
g p p y
array of Image objects corresponding to each
IMG element in the current document
– To display a new image, simply set the SRC
property of an existing image to a string
representing a different image file
152
153. Modifying Images Example
Images,
• Th f ll i f
The following function changes the fi i
i h h first image i a d
in document
function changeImage() {
document.images[0].src = "images/new-image.gif";
}
• Referring to images by name is easier:
<img src="cool-image.jpg" name="cool"
im " l im jp " n m " l"
width=75 height=25>
function improveImage() {
document.images["cool"].src = "way-cool.jpg";
}
153
154. Modifying Images: A Clickable Image Button,
Example
<script language=“JavaScript">
<!--
imageFiles = new Array("images/Button1-Up gif",
Array( images/Button1-Up.gif
"images/Button1-Down.gif",
"images/Button2-Up.gif",
"images/Button2-Down gif");
images/Button2-Down.gif );
imageObjects = new Array(imageFiles.length);
for(var i=0; i<imageFiles.length; i++) {
imageObjects[i] = new Image(150 25);
Image(150,
imageObjects[i].src = imageFiles[i];
}
function setImage(name, image) {
document.images[name].src = image;
}
154
155. Modifying Images: A Clickable Image Button,
Example
function clickButton(name grayImage) {
clickButton(name,
var origImage = document.images[name].src;
setImage(name, grayImage);
var resetString =
"setImage('" + name + "' '" + origImage + "')"
" tI ('" "', i I "')";
setTimeout(resetString, 100);
}
// --></script>
p
</head>...
<a href="location1.html"
onMouseOver="clickButton('Button1', 'images/Button1-Down.gif')">
<img src="images/Button1-Up.gif" name="Button1"
img src images/Button1 Up.gif name Button1
width=150 height=25></A>
<a href="location2.html"
onMouseOver="clickButton('Button2', 'images/Button2-Down.gif')">
<img src="images/Button2 Up gif" name= Button2
src= images/Button2-Up.gif name="Button2"
width=150 height=25></A>
...
155
156. Highlighting Images Under the Mouse,
Example
<html>
ht l>
<head> <title>High Peaks Navigation Bar</title>
<script language=“JavaScript">
<!—
// Given "Foo", returns "images/Foo.gif".
Foo , images/Foo.gif .
function regularImageFile(imageName) {
return("images/" + imageName + ".gif");
}
// Given "Bar", returns "images/Bar-Negative.gif".
function negativeImageFile(imageName) {
return("images/" + imageName + "-Negative.gif");
}
156
157. Highlighting Images Under the Mouse,
Example, cont.
// Cache image at specified index. E.g., given index 0,
// take imageNames[0] to get "Home". Then preload
// images/Home.gif and images/Home-Negative.gif.
function cacheImages(index) {
regularImageObjects[index] = new Image(150, 25);
regularImageObjects[index].src = regularImageFile(imageNames[index]);
negativeImageObjects[index] = new Image(150, 25);
negativeImageObjects[index].src = negativeImageFile(imageNames[index]);
}
imageNames = new Array("Home", "Tibet", "Nepal", "Austria", "Switzerland");
regularImageObjects = new Array(imageNames.length);
negativeImageObjects = new Array(imageNames.length);
// Put images in cache for fast highlighting.
for(var i=0; i<imageNames.length; i++) {
cacheImages(i);
}
157
158. Highlighting Images Under the Mouse,
Example, cont.
...
function highlight(imageName) {
document.images[imageName].src = negativeImageFile(imageName);
}
function unHighlight(imageName) {
document.images[imageName].src = regularImageFile(imageName);
}
// -->
</script></head>
<body>
<table>
<tr><td><a href="Tibet.html" target="Main"
onMouseOver="highlight('Tibet')" onMouseOut="unHighlight('Tibet')">
<img src="images/Tibet.gif" name="Tibet“ width=150 height=25 border=0>
</a>
...
158