JavaScript Specialist Lesson 1: Introduction to JavaScript Objectives • List key JavaScript characteristics, including object-based nature, events, platform-independence, and differences between scripting languages and programming languages • Identify common programming concepts, including objects, properties and methods • Describe various JavaScript versions and flavors, including ECMA standards, JScript and similarities with proprietary scripting languages • Distinguish between server-side and client-side JavaScript applications, including JavaScript interpreters and rendering engines • Describe acceptable coding practices, including appropriate use of comment tags and the <noscript> tag Introduction to Scripting • JavaScript – A scripting language for adding dynamic interactivity to Web pages – Generally used on the client side but can also be used on the server side • Origins of JavaScript JavaScript Characteristics • • • • • • JavaScript is a scripting language JavaScript is object-based, not object-oriented JavaScript is event-driven JavaScript is platform-independent JavaScript enables quick development JavaScript is relatively easy to learn JavaScript and Common Programming Concepts • • • • Objects Properties Values Methods JavaScript Flavors and Versions • JavaScript vs. Java • JavaScript, JScript and ECMA • JavaScript vs. VBScript – Visual Basic and VBScript • JavaScript versions Server-Side vs. Client-Side Applications • Server-side applications of JavaScript • Client-side applications of JavaScript – Embedding JavaScript into X/HTML – The HTML 4.0 type attribute – The language attribute and deprecated code – Script versioning for your browser – External scripts – The <noscript> tag Annotating Your Code with Comments • Single-line comment indicator (//) • Multiple-line comment indicator (/*...*/) Summary List key JavaScript characteristics, including object-based nature, events, platform-independence, and differences between scripting languages and programming languages Identify common programming concepts, including objects, properties and methods Describe various JavaScript versions and flavors, including ECMA standards, JScript and similarities with proprietary scripting languages Distinguish between server-side and client-side JavaScript applications, including JavaScript interpreters and rendering engines Describe acceptable coding practices, including appropriate use of comment tags and the <noscript> tag Lesson 2: Working with Variables and Data in JavaScript Objectives • Use attributes and methods to communicate with users, including the type attribute, and the alert(), prompt() and confirm() methods • Define variables • Use data types, including null and undefined • Obtain user input and store it in variables • Report variable text to the client window • Distinguish between concatenation and addition • Use expressions • Use operators, including string concatenation ( += ), strict comparison ( === , !==) and mathematical precedence • Implement inline scripting • Implement simple event handlers, including onload() and onunload() • Define keywords and reserved words Using JavaScript to Communicate with the User • • • • • • Giving the user a message: The alert() method Using semicolons in JavaScript Getting data from the user: The prompt() method Concatenation Requesting confirmation: The confirm() method Writing X/HTML dynamically: The document.write() method Using Data More Than Once: Variables • • • • What is a variable? Variable data types Literals Naming variables – Case-sensitivity in JavaScript • Declaring variables • Concatenating variables • Working with variables JavaScript Expressions • • • • • • Assignment Arithmetic String Logical Comparison Conditional Operators • • • • • The + operator The = and == operators The === and !== operators The ++ and -- operators Mathematical precedence Inline Scripting, Simple User Events, and Basic Event Handlers • Inline scripting – Placing JavaScript code within an X/HTML tag, rather than between the file's <body> </body> tags • The onunload event handler • The onload event handler Keywords and Reserved Words • JavaScript keywords • JavaScript reserved words Summary Use attributes and methods to communicate with users, including the type attribute, and the alert(), prompt() and confirm() methods Define variables Use data types, including null and undefined Obtain user input and store it in variables Report variable text to the client window Distinguish between concatenation and addition Use expressions Use operators, including string concatenation ( += ), strict comparison ( === , !==) and mathematical precedence Implement inline scripting Implement simple event handlers, including onload() and onunload() Define keywords and reserved words Lesson 3: Functions, Methods and Events in JavaScript Objectives • • • • • • • • • • Use methods as functions Define functions Use data type conversion methods Call functions Pass arguments to functions, including argument creation, return values and the calculateAvg() function Return values from functions Distinguish between global and local variables Use the conditional operator Identify user events and event handlers Use built-in functions and cast variables Introduction to Functions • Function – A named block of code that can be called when needed – In JavaScript, a function can return a value Defining a Function • • • • Calling statement Argument Inserting functions into X/HTML pages Good coding practice Calling a Function • • • • Passing arguments to functions Returning values from functions Operator precedence Global vs. local variables User Events and JavaScript Event Handlers • Event Objects – button – reset – submit – radio – checkbox – link – form – text – textarea – select – image – area – window • User Events – abort – blur – click – change – error – focus – load – mouseOver – mouseOut – reset – select – Submit – unLoad • Event Handlers – onabort – onblur – onclick – onchange – onerror – onfocus – onload – onmouseover – onmouseout – onreset – onselect – onsubmit – onunload Methods as Functions • Using built-in functions • Casting variables Summary Use methods as functions Define functions Use data type conversion methods Call functions Pass arguments to functions, including argument creation, return values and the calculateAvg() function Return values from functions Distinguish between global and local variables Use the conditional operator Identify user events and event handlers Use built-in functions and cast variables Lesson 4: Controlling Program Flow in JavaScript Objectives • • • • • • Use the if... statement Use the while... statement Use the do...while statement Use the for... statement Use the break and continue statements Use the switch... statement Controlling Decisional Program Flow • Control the execution of JavaScript statements • Control structure – In programming, a statement that uses a comparison operator to make decisions based on Boolean values, or a statement that causes code to execute repeatedly (i.e., loop) The if...else Statement • • • • A single condition Multiple conditions Using if for conditional program flow Multiple conditions in the same expression The while Statement • The while statement – Used to execute a block of code for as long as (while) a certain test condition is true • The isNaN method – Used to determine whether a given value is a valid number The do...while Statement • The do...while statement – Does not check the conditional expression until after the first time through the loop, guaranteeing that the code within the curly braces will execute at least once The for Statement • The for statement – Repeats a group of statements for some particular range of values The break Statement • The break statement – Used to exit a loop that would otherwise continue to execute The continue Statement • The continue statement – Used to force the flow of control back to the top of a loop • Using continue in a while loop The switch Statement • The switch statement – Compares a value against other values, searching for a match Summary Use the if... statement Use the while... statement Use the do...while statement Use the for... statement Use the break and continue statements Use the switch... statement Lesson 5: The JavaScript Document Object Model (DOM) Objectives • Use JavaScript to manipulate the Document Object Model (DOM) • Use the window object of the DOM • Manipulate properties and methods of the document object within the DOM • Use the with statement • Use the image object of the DOM, including image rollover creation • Use the history object of the DOM • Evaluate and change URL information with the location object of the DOM • Use the navigator object of the DOM The JavaScript Document Object Model (DOM) The window Object • The window object – Represents the frame of the browser and the mechanisms associated with it • Opening additional windows • Dot notation revisited • The status property • The onmouseover and onmouseout event handlers The document Object • The document object – Provides the properties and methods to work with the current document • The bgColor and fgColor properties • The title property • The lastModified property • Referencing remote window and document objects The with Statement • The with statement – Combines several properties and/or methods with a single object The image Object • The image object – Allows you to manipulate images in browsers • Handling image object events • JavaScript and image maps The history Object • The history object – Allows the user to move backward or forward through the stored history of your Web page The location Object • The location object – Allows you to specify URLs in a script The navigator Object • The navigator object – Determines the brand and version of the browser in use – Identifies the user's operating system • Redirecting the browser with the navigator and location objects Summary Use JavaScript to manipulate the Document Object Model (DOM) Use the window object of the DOM Manipulate properties and methods of the document object within the DOM Use the with statement Use the image object of the DOM, including image rollover creation Use the history object of the DOM Evaluate and change URL information with the location object of the DOM Use the navigator object of the DOM Lesson 6: JavaScript Language Objects Objectives • Use the String object to test user input • Evaluate strings, including use of the length property, and use of the indexOf(), lastIndexOf(), substring() and charAt() methods • Identify basic regular expressions and the RegExp object • Use the Array object to create more efficient code • Identify uses for the Date and Math objects Introduction to JavaScript Language Objects • Language objects – The String object – The Math object – The Array object – The RegExp object The String Object • The String object – Text, numbers, or any combination of characters that functions as text • String object formatting methods • String object special characters • The prototype property of the String object • Common syntax errors with the String object • Additional String object methods Evaluating Strings • • • • The length property of the String object The indexOf()method of the String object The lastIndexOf() method of the String object The substring() method of the String object – The substr() method • The charAt() method of the String object • Form validation using string methods JavaScript Regular Expressions • Regular expression – Searches for specified patterns in text • The RegExp object – Used to create regular expressions • Creating regular expressions • More methods of the String object • Patterns with alphanumeric characters The Array Object • The Array object – Used when a single variable needs to be able to reference multiple values • The join() method of the Array object • The reverse() method of the Array object • The sort() method of the Array object • The Array object length property The Date Object • The Date object – Used for date and time information • Methods of the Date object Setting and Extracting Time Information • Setting and extracting time information follows the same procedures as setting and extracting date information • Uses the Date object The Math Object • The Math object – Used to create advanced mathematical calculations • Methods and properties of the Math object • Using the Math object Summary Use the String object to test user input Evaluate strings, including use of the length property, and use of the indexOf(), lastIndexOf(), substring() and charAt() methods Identify basic regular expressions and the RegExp object Use the Array object to create more efficient code Identify uses for the Date and Math objects Lesson 7: Developing Interactive Forms with JavaScript Objectives • Identify and use form controls, including X/HTML form elements • Refer to form objects, including form, radio, select, button, text, textarea and checkbox • Define the form object • Use the button object • Use the checkbox object • Evaluate text with the text and textarea objects • Process radio object options • Capture choices from a select list with the select object • Conduct form validation, including valid X/HTML code Interactive Forms • The ability to retrieve and verify data from the user through an X/HTML form • From a Web developer's perspective, the most common need for JavaScript Overview of Form Elements X/HTML form elements • • • • • button checkbox hidden password radio • • • • • reset select submit text textarea Corresponding JavaScript objects Referring to Form Elements • You can refer to a form element in the form object's elements array in two ways: – By its name – By its index number The form Object • The form object – Represents an X/HTML form in JavaScript – Available when <form> tags are present in the X/HTML document • Properties, methods and event handlers of form object The button Object • The button object – Provides a basic push-button type of user interface element on an X/HTML page • Properties, methods and event handlers of button object The checkbox Object • The checkbox object – An input object in the shape of a small square (called a check box) that can be selected, or "checked," on or off – Users can select as many as they like or all check boxes in a group (not mutually exclusive) • Properties, methods and event handlers of checkbox object The text and textarea Objects • The text object – Displays a single line of text • The textarea object – Displays multiple, scrolling lines of text • Properties, methods and event handlers of text and textarea objects • Checking user input The radio Object • The radio object – Small round button that can selected on or off – Used to select one option from among two or more mutually exclusive options • Properties, methods and event handlers of radio object The select Object • The select object – A drop-down selection list or a list box of items used in an X/HTML form – Allows you to choose one item from a list of mutually exclusive items • Properties, methods and event handlers of the select object • Working with selection lists • Multiple-selection list box – Allows you to choose as many items as they like from a list (not mutually exclusive) Form Validation • Benefits of client-side form validation: – Increased validity of form submissions – Increased end-user satisfaction – Conservation of bandwidth • Form validation tips Summary Identify and use form controls, including X/HTML form elements Refer to form objects, including form, radio, select, button, text, textarea and checkbox Define the form object Use the button object Use the checkbox object Evaluate text with the text and textarea objects Process radio object options Capture choices from a select list with the select object Conduct form validation, including valid X/HTML code Lesson 8: JavaScript Security Objectives • Distinguish between the browser and the operating system in relation to the elements responsible for security • Discuss browser security issues relevant to JavaScript • Define signed scripts • Perform client-side browser detection and determine browser compatibility • Identify common issues and procedures for creating secure JavaScript code • Define cross-site scripting and the associated security risks • Define the functions of cookies and manipulate them effectively • Assign a cookie using JavaScript • Use cookies and passwords to restrict entry to a page Introduction to JavaScript Security Issues • JavaScript is an open scripting language • JavaScript does not protect data passed between browser and server • JavaScript does not protect the Web site owner • For true security, ensure that your Web pages use SSL/TLS (HTTPS) and that your server has all the checks in place Browser vs. Operating System • Browser vs. operating system – The operating system allows the computer to interface directly with users – The browser connects your operating system to the unprotected network that is the Internet • Securing operating systems and browsers Browser-Specific Security Issues • • • • Example issues with older browsers Example issues with recent browsers Helper application problems What users and developers can do Browser Compatibility and Client-Side Detection • • • • Standards-based browsers Problems with browser detection Alternative coding for browser compatibility Browser detection and security Script Blocking • How script blocking affects developers • Blocking JavaScript from your browser Differences in document.write Among Browsers • The document.write method – Provides the simplest way to use JavaScript to write text onto a Web page – Incompatibility issues with XHTML and Internet Explorer • What JavaScript developers can do Malicious and Accidental Coding • Every developer makes some mistakes while coding • Ill-advised or malicious users sometimes upload such scripts to the Web deliberately • Locking the browser with an infinite loop Frame-to-Frame URL Changing • How frames work – Cloaking – Inline frames • Browser restrictions – Same origin policy • What JavaScript developers can do Signed Scripts • Signed script – A script validated by a certificate authority that can request extended privileges and abilities • How signed scripts work • Creating a signed script Cross-Site Scripting (XSS) • Cross-site scripting (XSS) – A security vulnerability in which an attacker embeds malicious script into a link that appears to be from a trusted site • How XSS works • Types of XSS • Code and servers in XSS • What JavaScript developers can do • OWASP and XSS Cookies and Security in JavaScript • • • • • • What are cookies? How are cookies sent? Who can send cookies? Why use cookies? Storing cookies Cookies and specific browsers • Users deleting or disabling cookie files • Assigning a cookie with JavaScript • Testing for cookie presence • Clearing a cookie • Users controlling cookies in the browser • Cookies and passwords Creating Secure JavaScript Code • Test, test, test your scripts • Keep current in your knowledge about JavaScript and its security • Do not use deprecated code • Use proper encoding and validation practices • Know the code you are using before putting it on a Web site • Write your code consistently • Comment your code liberally • Keep security patches up-to-date • Keep your operating system up-to-date Summary Distinguish between the browser and the operating system in relation to the elements responsible for security Discuss browser security issues relevant to JavaScript Define signed scripts Perform client-side browser detection and determine browser compatibility Identify common issues and procedures for creating secure JavaScript code Define cross-site scripting and the associated security risks Define the functions of cookies and manipulate them effectively Assign a cookie using JavaScript Use cookies and passwords to restrict entry to a page Lesson 9: Custom JavaScript Objects Objectives • • • • • Create a custom JavaScript object Define properties and methods of custom objects Create new object instances Create client-side arrays using custom objects Create functions and methods for manipulating clientside arrays • Use the prototype property Creating Custom Objects • Array objects, custom objects and databases • Advantages of custom objects • Custom object demonstration Creating a JavaScript Object: The Constructor • Constructor – A special function that enables you to create instances of custom objects – Defines the properties and methods of your object Creating an Instance of a Custom Object • To instantiate and then populate the properties of each new instance with actual data, you must declare variables • The prototype property – Used to add new properties or methods to JavaScript objects Creating Object Methods • You can create as many methods for your object as you need (or as many as memory allows) • You can make them as simple or as sophisticated as you like Creating Functions for Your Objects • • • • The findItem() function The showAll() function Full source code for this client-side array Complex custom objects Summary Create a custom JavaScript object Define properties and methods of custom objects Create new object instances Create client-side arrays using custom objects Create functions and methods for manipulating clientside arrays Use the prototype property Lesson 10: Changing X/HTML on the Fly Objectives • Identify steps and methods for changing X/HTML "on the fly," including the getElementById, getElementsByName and getElementsByTagName methods of the DOM • Modify attributes in X/HTML using DOM elements • Modify values in X/HTML using DOM elements • Use the innerHTML element Changing X/HTML on the Fly • "On the fly" – Changes can be made when needed, even during the execution of a page or process • X/HTML basics • Why change X/HTML on the fly? Using the getElementByID Method • The getElementById method – Allows you to access and change all the properties of object elements • The innerHTML property – Allows you to set and retrieve the contents of a specified element Using the getElementsByName Method • The getElementsByName method – Allows you to access all elements with the specified name Using the getElementsByTagName Method • The getElementsByTagName method – Allows you to access all elements with the specified tag name Modifying Attributes within the DOM • getAttribute() – Allows you to retrieve the corresponding value of an attribute • setAttribute() – Allows you to dynamically modify the value of an element's attribute • removeAttribute() – Allows you to remove entire X/HTML attributes from an element Appending Text to the DOM • The appendChild method – Enables you to add elements to the end of the page, before the closing </body> tag, without overwriting the existing page content Summary Identify steps and methods for changing X/HTML "on the fly," including the getElementById, getElementsByName and getElementsByTagName methods of the DOM Modify attributes in X/HTML using DOM elements Modify values in X/HTML using DOM elements Use the innerHTML element Lesson 11: JavaScript Libraries Objectives • Identify and evaluate the benefits and drawbacks of using predefined libraries and plug-ins, such as jQuery, Spry, Dojo, MooTools and Prototype • Identify steps for using libraries (such as jQuery) and available plug-ins, including jQuery-friendly X/HTML and X/HTML optimization for faster JavaScript manipulation • Identify steps for loading and referencing external scripts and pre-made external scripts JavaScript Libraries • Code library – A collection of fully formed external scripts that are designed to make JavaScript simpler to use • Why use a code library? Choosing a Code Library • Reputable code libraries – jQuery – Spry – Prototype – Dojo – MooTools External and Pre-Made Scripts • External script – A script placed in a separate file that is run by linking it to the X/HTML page • Library plug-ins – Plug-ins vs. pre-made scripts • Separation of scripting • Loading external scripts Loading Your First Library • To use a JavaScript library – Choose the library you want to use – Download it – Set it up – Begin using the code it contains in your X/HTML pages Using JavaScript Library Plug-ins • Plug-in – A program in a JavaScript library that performs a particular function or extends functionality toward a particular result – Typically developed by third parties and offered for free on the Web • Why use plug-ins? Best Practices with JavaScript Libraries • Optimizing your X/HTML for libraries • jQuery-friendly XHTML Copyright Issues and JavaScript • Copyright gives a work's creator the right to specify the work's use • Requirements for copyright eligibility for code: – The code must form a complete function – The script or program must be a unique work – The work must generate revenue • Copyleft and copycenter Summary Identify and evaluate the benefits and drawbacks of using predefined libraries and plug-ins, such as jQuery, Spry, Dojo, MooTools and Prototype Identify steps for using libraries (such as jQuery) and available plug-ins, including jQuery-friendly X/HTML and X/HTML optimization for faster JavaScript manipulation Identify steps for loading and referencing external scripts and pre-made external scripts Lesson 12: JavaScript and AJAX Objectives • Define fundamental AJAX elements and procedures • Diagram common interactions among JavaScript, XML and XHTML • Identify key XML structures and restrictions in relation to JavaScript • Explain how the XMLHttpRequest object interacts with XML • Use the XMLHttpRequest object to retrieve data • Describe typical AJAX-based requests • Identify key server response issues related to AJAX-based requests • Use JavaScript to communicate with databases • Identify alternatives to XML-based AJAX Introduction to AJAX • AJAX (Asynchronous JavaScript and XML) – A technology that combines functionality from JavaScript and XML to allow a Web page to reload only a specified portion, rather than the entire page, in response to a request • The XMLHttpRequest object – A JavaScript object that is used to request either XML data or plaintext data from a Web server Introduction to XML • XML (Extensible Markup Language) – A meta-language that enables the developer to create unique tags for structuring Web documents based on context rather than appearance • Valid XML – Is well-formed and references a DTD • Well-formed XML – Conforms to strict, specific syntax rules Interactions Among JavaScript, XML and XHTML • Common interactions in AJAX • Relating XML structures and restrictions to JavaScript – Key structures – Restrictions • How XMLHttpRequest interacts with XML Using AJAX Scripts • There are three basic JavaScript functions in a typical AJAX request: – A function that creates an HTTP request – A function that calls and submits the HTTP request – A function that handles the data returned to the page AJAX and Servers • Typical AJAX-based requests – Returning server variables from the server to the client – Parsing XML and data – Sending entire pages of information in a native language to the server for interpretation and retrieval • Server response issues with AJAX – Partial responses – Unfinished responses AJAX and Databases • Relational databases – Relationships in databases • Using AJAX with a database • Security issues with AJAX and databases Usability Issues with AJAX • • • • • Bookmarking Search engines Back button Script blocking ActiveX blocking Combining AJAX with Libraries • AJAX – Works well with data and server-side applications – Works well with JavaScript libraries Alternatives to XML-based AJAX • Java applets • Adobe Flash • Microsoft Silverlight Summary Define fundamental AJAX elements and procedures Diagram common interactions among JavaScript, XML and XHTML Identify key XML structures and restrictions in relation to JavaScript Explain how the XMLHttpRequest object interacts with XML Use the XMLHttpRequest object to retrieve data Describe typical AJAX-based requests Identify key server response issues related to AJAX-based requests Use JavaScript to communicate with databases Identify alternatives to XML-based AJAX Lesson 13: Debugging and Troubleshooting JavaScript Objectives • List common steps for debugging JavaScript code including reviewing code and testing code in different browsers • Describe and use various native and supplemental debugging tools, including enabling/disabling display • Test code in multiple display platforms, including mobile devices What Is Debugging? • Debugging – Troubleshooting and repairing code that does not work properly or at all • Bug – An error in the code • Steps for debugging JavaScript code Tools for Debugging Code • Browsers that offer native debugging include: – Microsoft Internet Explorer – Google Chrome – Apple Safari • Supplemental debugging tools: – Firebug add-on for Firefox – Microsoft Script Debugger – Speed Tracer in the Google Web Toolkit – Opera Dragonfly – 1st JavaScript Editor – Rhino Debugger – SplineTech JavaScript Debugger Testing Code in Various Browsers • Browsers can appear to behave differently for several reasons: – Monitor resolution – Video card quality and settings – Browser version – Script interpretation – The end user's CPU speed and RAM – Mobile devices • User considerations Debugging Logical Errors • Maintenance debugging – Code repairs performed after a site has been launched into production • Watchpoint – An alert, placed in JavaScript code to check on the program at certain points, and to ensure the actual output matches the expected output JavaScript and Mobile Devices • PDAs, smartphones, iPhones, Blackberries, etc. • Most past-version mobile devices are Web-enabled and many are JavaScript-compatible • Almost all new mobile devices offer online access and handle JavaScript • Main issues with mobile devices: – Small and limited display – Different methods of user interaction (finger touches and swipes, stylus clicks) – Various screen resolutions – Various operating systems Summary List common steps for debugging JavaScript code including reviewing code and testing code in different browsers Describe and use various native and supplemental debugging tools, including enabling/disabling display Test code in multiple display platforms, including mobile devices JavaScript Specialist Introduction to JavaScript Working with Variables and Data in JavaScript Functions, Methods and Events in JavaScript Controlling Program Flow in JavaScript The JavaScript Document Object Model (DOM) JavaScript Language Objects Developing Interactive Forms with JavaScript JavaScript Security Custom JavaScript Objects Changing X/HTML on the Fly JavaScript Libraries JavaScript and AJAX Debugging and Troubleshooting JavaScript