You are on page 1of 28

Web Development Javascript Notes

Page 1 of 28

TABLE OF CONTENTS
Javascript......................................................................................................................................... 4 Introduction to JavaScript ........................................................................................................... 5 Where to put the JavaScript ................................................................................................... 5 JavaScript Statements ............................................................................................................. 6 Comments ............................................................................................................................... 6 Objects ........................................................................................................................................ 7 String Object ........................................................................................................................... 7 Date Object ............................................................................................................................. 7 Array Object ............................................................................................................................ 8 Math Object ............................................................................................................................ 8 variables ...................................................................................................................................... 9 Declaring Variables ................................................................................................................. 9 JavaScript Arithmetic .............................................................................................................. 9 Conditional Statements ............................................................................................................ 10 If Statement .......................................................................................................................... 10 IfElse Statement ................................................................................................................. 10 Switch Statement .................................................................................................................. 10 Loops ......................................................................................................................................... 11 For Loops ............................................................................................................................... 11 While Loop ............................................................................................................................ 11 Do While Loop ....................................................................................................................... 11 Events ........................................................................................................................................ 12 JavaScript Message boxes ......................................................................................................... 13

Alert Box................................................................................................................................ 13 Confirm Box........................................................................................................................... 13 Prompt Box ........................................................................................................................... 14 Parsing Strings to Numbers................................................................................................... 14 functions ................................................................................................................................... 15 Defining a function................................................................................................................ 15 Passing Parameters to a Function......................................................................................... 15 Return a value from a Function ............................................................................................ 15 browser objects ........................................................................................................................ 17 Window Object ..................................................................................................................... 17 History Object ....................................................................................................................... 17 Location Object ..................................................................................................................... 18 Introduction to the document object model (DOM) ................................................................ 19 HTML DOM Nodes ................................................................................................................ 20 DOM Node Access................................................................................................................. 21 DOM Node List ...................................................................................................................... 23 validating forms ........................................................................................................................ 25 validation theory ................................................................................................................... 25 Validation Techniques........................................................................................................... 26

JAVASCRIPT
JavaScript is THE scripting language of the Web. What can JavaScript do? JavaScript gives HTML designers a programming tool - HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages JavaScript can put dynamic text into an HTML page - JavaScript statement like this: document.write ("<h1>" + name + "</h1>") can write a variable text into an HTML page JavaScript can react to events - JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element JavaScript can read and write HTML elements - JavaScript can read and change the content of an HTML element JavaScript can be used to validate data - JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing JavaScript can be used to detect the visitor's browser - JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser JavaScript can be used to create cookies - JavaScript can be used to store and retrieve information on the visitor's computer

Are Java and JavaScript the same thing? No. Read the history on Javascript.

INTRODUCTION TO JAVASCRIPT In order to insert JavaScript into XHTML, the <script> tag is used.

Note: The document.write command is a standard JavaScript command for writing output to a page.
WHERE TO PUT THE JAVASCRIPT

When placed within the <body> tag, the JavaScript is automatically run by the browser when the page is loaded. Scripts that should only be executed when they are called are placed in functions. Functions, which are covered later, are placed within the <head> tag. This enables all functions to be stored in the same place and they will not interfere with the page content. The example above uses Inline JavaScript, meaning the script is actually contained within the markup. This works well for this one page, but if you want to run the same script on multiple pages, you can use External JavaScript so the script doesnt have to be rewritten every time its needed. External JS is saved in a file with a .js extension, and is referenced within the <head> tag.

JAVASCRIPT STATEMENTS

JavaScript is a sequence of statements to be executed by the browser. Note: Unlike XHMTL, JavaScript is case sensitive. Watch your capitalization closely! Markup can be inserted within output statements: Notice the semi-colons. While not required, its good practice to use semi-colons within JavaScript.

COMMENTS

Comments should be added to the JavaScript in order to make the code more readable. Single line comment:

Multi-line comments:

OBJECTS JavaScript is an Object Oriented Programming language. JavaScript Objects can be used to perform a variety of tasks. Note: Be sure to visit the reference links for full documentation on all JavaScript objects.
STRING OBJECT

The String Object can be used to manipulate text. Some examples of using the string object:

DATE OBJECT

The Date Object is used to work with dates and times.

ARRAY OBJECT

The Array object is used to store multiple values within a single variable. Declaring and using arrays is very similar to other programming languages (i.e. VB, Java, Python, etc)

MATH OBJECT

The Math Object allows the use of mathematical tasks. Note: The Math Object is a built in object and its not required to instantiate the object as done for the Date object.

VARIABLES
DECLARING VARIABLES

To declare a variable in JavaScript, the var statement is used.

The above declares an empty variable named donkey. You can also assign values to the variables when you declare them:

JAVASCRIPT ARITHMETIC

There are many JavaScript Operators that are used to assign, add, subtract, multiply, divide, modulus, increment, and decrement values within variables. Some examples:

Note: adding a string and number will make the result a String.

CONDITIONAL STATEMENTS
Conditional statements are used to perform different actions based on different conditions. There are a few conditional statements used in JavaScript.

IF STATEMENT

IFELSE STATEMENT

SWITCH STATEMENT

LOOPS Loops execute a block of code a specified number of times, or while a specified condition is true.
FOR LOOPS

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

WHILE LOOP

The While Loop loops through a block of code while a specified condition is true.

DO WHILE LOOP

The DoWhile Loop is a variation of the while loop. The loop will execute a block of code once and then it will repeat as long as a specified condition is true.

EVENTS JavaScript events are actions that are captured by JavaScript. All elements of a web page have certain events that can trigger a piece of JavaScript code. Some examples of events: A mouse click A web page or image loading Mousing over a hot spot on the web page Selecting an input field in an HTML form Submitting an HTML form A keystroke

In this example the checkEmail function is called when text within the email input is changed. Functions are covered in a later section.

JAVASCRIPT MESSAGE BOXES JavaScript has three kinds of popup boxes: Alert box, Confirm box, and Prompt Box.
ALERT BOX

An alert can be used if you want to ensure information gets to the user. When an alert pops up, the user will have to click OK to proceed. This JavaScript:

Would produce this:

Use caution with Alerts. They can be handy for debugging, but can be annoying to users.
CONFIRM BOX

A confirm box is often used if you want the user to verify or accept something. When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.

PROMPT BOX

A prompt box is often used if you want the user to input a value before entering a page. When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null. The prompt function takes two values, the message within the box, and the default text for the text field within the Prompt box.

PARSING STRINGS TO NUMBERS

A key thing to remember with Prompt boxes is that any data returned from them is a String. If you are expecting numbers to be returned from the user, you must parse the Strings into number format using either the parseInt function, or the parseFloat function.

FUNCTIONS To keep the browser from executing a script while the page loads, we can put our script into a function that will be executed when called. Note: If using Inline script, remember that functions must be contained within the <head> tag.
DEFINING A FUNCTION

Defining a function in JavaScript is similar to other languages.

The function can be called within the markup. The example below uses the onClick event of the input type button.

PASSING PARAMETERS TO A FUNCTION

Values can be passed to a function for use within that block of code.

RETURN A VALUE FROM A FUNCTION

The return statement is used to specify the value that is returned from the function.

Note: A function can only return one value.

BROWSER OBJECTS Browser objects are a part of JavaScript that allows JavaScript to interface and interact with the browser itself.
WINDOW OBJECT

The window object represents an open window in a browser. Almost everything within the browser is a property or method of the window object. Some examples of window object methods:

HISTORY OBJECT

The history object is part of the window object and is accessed through the window.history property. Some examples of history object methods:

LOCATION OBJECT

The location object contains information about the current URL. Some examples of location object properties:

INTRODUCTION TO THE DOCUMENT OBJECT MODEL (DOM) The Document Object Model (DOM) is a convention for representing and interacting with objects in XHTML and XML documents. The DOM presents an HTML document as a treestructure. This is an overview of the basics of the DOM and its role in how we can access the elements and their properties with JavaScript. The DOM is covered in more detail with the XML course. The DOM is separated into three different parts/levels: Core DOM standard model for any structured document XML DOM standard model for XML documents HTML DOM standard model for HTML documents

The DOM defines the objects and properties of all document elements, and the methods to access them. A layout of the DOM, from Wikipedia:

HTML DOM NODES

In the DOM, everything within an HTML document is a DOM node. The nodes are broken down as: The entire document is a document node Every HTML element is an element node The text in the HTML elements are text nodes Every HTML attribute is an attribute node Comments are comment nodes

The HTML DOM views the HTML document as a tree-structure (also called a node-tree). All nodes can be accessed through the tree. Their contents can be modified or deleted, and new elements can be created.

The nodes in the node-tree have a hierarchical relationship to each other. Parent, child and sibling terms are used to describe the relationships between the nodes.

DOM NODE ACCESS

Within the DOM, you can access every node within an HTML document. There are three ways we can access a node: 1. Using the getElementById() method 2. Using the getElementsByTagName() method 3. By navigating the node tree, using the node relationships
getElementById()

The getElementById() method returns the element with the specified ID, not matter what the element type is.

getElementsByTagName()

The getElementsByTagName() method returns all elements with a specified tag name.

The next example only returns the nodeList of all <p> elements that are children of the element with the id of main.

DOM NODE LIST

The getElementsByTagName() method returns a node-list. A node-list is an array of nodes.

Notice the innerHTML property. With it we can access the contents of an element. We can also modify those contents.

VALIDATING FORMS One of JavaScripts biggest advantages is the ability to validate form data at the front-end. Front-end validation takes strain off the server that processes the form data.
VALIDATION THEORY

There are many techniques to validating forms. A common standard is to wait until the user has finished entering data into the form before attempting any validation. We know the user has submitted the form when the onSubmit() event has been triggered.
Action attribute

The action attribute specifies where to send form-data.

post & get methods

The two ways to transfer data from a form to another source are the Get and Post methods. The get method appends the form-data to the url. The post method sends the form-data as an HTTP post transaction. A good basic rule is when youre sending form-data to a server you should be using the post method. Read more about the differences between the get and post methods.

onSubmit()

The onSubmit() event occurs when the user has clicked on the Submit button in a form. We can handle the event by directing the processing to a validation script.

onReset()

The onReset() event occurs when the user clicks on the Reset button of a form. All form elements are restored to their default values. Its good practice to ensure the user wanted to clear the form and didnt click the button by accident.

VALIDATION TECHNIQUES

We can use the DOM to navigate the markup, and get the values we need to validate by drilling down to the text node of an element. For example:

Using IDs for all elements within a form makes it easy to access the elements within the form.
Validating text fields

Text fields can be tested for multiple conditions. Testing for blank spaces or an empty field:

Testing the length of a fields value:

Validating numeric fields

Input types of text are just that; text. JavaScript doesnt know if the value is a number or just a regular string. Its our job to make that determination. In order to check if a string is an actual number, we can use the isNaN() function (case sensitive). If the function returns a value of true then the text is a number, and a false if the text is not a number.
Using select() and focus() to improve usability

When we detect that the user made an error in a field, its good practice to highlight the text in error (using select() ) and then setting focus to the field in error (using focus() ).

Inline Form Validation

If the user has entered invalid data on a form, we could always use an Alert box to notify them of the error. Unfortunately, display message boxes to users can be invasive. This technique is rarely still used. A more modern technique to displaying errors to users is using inline form validation. We can insert <div> tags within our form markup that can act as our error messages.

Notice that both <div>s use the same class of fielderror but have unique ids. Next lets look at the CSS side of this solution.

We create a class of fielderror and set its display property to none. The error text will be red and bold as well.

Now all we need is our script. If we find a field in error, we make the corresponding <div> visible, and insert some error text.

You might also like