1621ICT Web Design and Development
HTML5 and CSS3 Illustrated
Unit L:
Programming Web Pages with Javascript
Objectives • Explore the Document Object Model
• Add content using a script
• Trigger a script using an event handler
• Create a function
• Store and compare data in variables
• Generate Web page content dynamically
• Script fallback options with Modernizr
• Integrate an existing script 2
Scripts • HTML and CSS enable you to create and
manipulate a limited set of Web page elements
• You can increase the range of actions that you can perform on Web page elements by writing and including scripts with your Web pages
Eg. The script we have added to enable Internet Explorer to recognise the <nav> element
<!--[if lt IE 9]>
<script src="scripts/semantic.js"></script>
<![endif]--> 3
Scripts • Javascript is a scripting language that enables you
to change or enhance a Web page in various ways
• With Javascript you can look up and potentially change data associated with various parts of a HTML document
• In order for Javascript to access the various parts of a HTML document, a standardised way to represent the HTML document is required
• This standardised representation of a HTML document is called the Document Object Model (DOM)
4
Exploring the Document Object Model
• The Document Object Model (DOM) creates a hierarchical arrangement known as a DOM tree
• In the DOM, each part of the HTML document is represented by a node
• A DOM node can be an HTML element (Eg. <p>), an attribute (Eg. src=".."), or text (Eg. "That is a HUGE dog!")
5
Exploring the Document Object Model
• There are several types of information associated with a DOM node:
• Objects • Properties • Methods
• You use a combination of objects, properties, and methods to specify an item in the DOM that you want to access
• You specify these items in order from most general (top of the DOM tree) to most specific (bottom of the DOM tree) 7
Exploring the Document Object Model
• A DOM object corresponds to a HTML element (Eg. <p>)
• To retrieve data from a Web Page (or change it) requires writing code to identify the specific object that you need
• One way to do look up a specific object is to use its id attribute
• For elements without an id attribute you can specify where in the DOM the element is located using parent-child relationships
8
Exploring the Document Object Model
• Each DOM node is associated with a standard set of information
• Each such piece of information is known as a property
• Standard properties for objects include • Text content associated with the object • Name of the object • Names of any associated attributes
• Each attribute represents its own node and is associated with its own properties (including its value) 9
Exploring the Document Object Model
• Commonly used properties
• Commonly used methods
11
Property Refers to Example innerHTML The content of an object The text in a paragraph
element value The current value of another
property The value of the href property of an a element
Method Associated action write Add text content and/or HTML code to a Web page
document getElementById Locate an element with a given id value in the DOM
tree alert Opens a small alert box that displays a customised
message
Exploring the Document Object Model • A DOM method is an action that can be performed
for a node
• For example, you can use the getElementById() method to access data associated with any HTML element that has an id attribute
• Most method names are followed by parentheses () between which you specify information specific to that method (actual parameters)
Eg. getElementById("logo") 12
Exploring the Document Object Model
• You use a combination of objects, properties, and methods to specify a particular element in DOM
• Each reference to a DOM node begins with the document object
• Eg. document
• Objects, properties, and methods are listed in sequence, separated by a period (this is called dot notation)
13
Exploring the Document Object Model
• Next, you specify one or more methods or objects to move you to a specific place in the DOM
• For example, if you want to find the element with the id="logo" you could use the method getElementById("logo")
• Dot notation is used to connect all parts of the statement into a single string
• Eg. document.getElementById("logo") 14 Document object Method
Method parameter
Exploring the Document Object Model • The getElementById method can
specify which node Eg. document.getElementById("logo")
• If you want a value to work with, the innerHTML property can get the value of the specified node
Eg. document.getElementById("logo").innerHTML
• You can also use the innerHTML property to change the value of the specified node
Eg. document.getElementById("logo").innerHTML=("text")
15
Adding Content Using a Script • Scripts can be used to add content to a
Web page
• Each script is placed inside <script> </script> tags
• Spaces outside of quoted text are ignored
• A single script instruction is called a statement
• Some goals can be achieved with one statement scripts
16
Adding Content Using a Script
• You can specify the element that you want using the getElementById method and its get its value using the innerHTML property
• In case the user does not have Javascript installed (or has disabled it), you can use the HTML <noscript> </noscript> element to use as a fallback
• You should ensure that any functionality that is available as a script is also available via other means (ie. using <noscript>)
17
Adding Content Using a Script
19
HTML document
Script to add text into the paragraph with id="message"
paragraph with id="message"
Triggering a Script Using an Event Handler
• Using a script to add content to a Web page when it first opens is something that you can do more easily with HTML
Eg. Just add the HTML code directly instead of using a script to do it
• You can make scripts much more flexible and powerful by
linking them with a user action
• A number of actions, known as events, are defined for Web pages and their elements
• You can provide code that will be executed when a specific event happens
21
<p id="message">Thanks for contacting Lakeland Reeds Bed & Breakfast</p>
Triggering a Script Using an Event Handler
• An event is a user action defined for Web pages • An event can be linked to a script
• An event handler is a HTML attribute that specifies a type of user action for an event • An event handler is used to indicate the
code that should execute in response to a specific type of user action
• Events and event handlers allow Web pages to respond to user activities
22
Triggering a Script Using an Event Handler
• Basic events and event handlers
23
Event Event handler
Description
click onClick Main mouse button is clicked and released focus onFocus An element is selected blur onBlur An element is no longer selected mouseover onMouseOver The mouse pointer moves over an element mouseout onMouseOut The mouse pointer moves off an element keydown onKeyDown A key on the keyboard is pressed keyup onKeyUp A key on the keyboard is released submit onSubmit Form contents are submitted reset onReset Form fields are reset to their defaults
Triggering a Script Using an Event Handler
24
Note no text below "Contact us"
Browser preview before changes
Triggering a Script Using an Event Handler
25
HTML document
Script to add text into the paragraph with id="message" using the onClick event handler for the button. Note: No need for script tags.
Triggering a Script Using an Event Handler
26
Note added text below "Contact us"
Browser preview after submit button pressed
Creating a Function • As your javascript becomes more complex it is
useful to group multiple lines of code into a bundle and give it a name
• You can then refer to the whole bundle with the name instead of having to type out all the individual lines of code each time that you want to use it
• Javascript has functions which are bundles of individual lines of code that have been grouped together and given a name (function name)
27
<script>
function myFunction() { document.getElementById("message").innerHTML=("Thank you");
}
</script>
Creating a Function • In Javascript, a function is a bundle of script
code with a name assigned to it • Code lines in the function are called as a single unit
and executed one after another • Any characters after // are treated as comments
• The syntax of a Javascript function is as follows: function name() { statement(s); }
Note the punctuation ({ } and ;) is similar to a CSS style rule An example Javascript function:
28
Creating a Function • A Javascript function can be stored in an
external file
• To use a function in an external file, use the HTML src attribute in the script tag to indicate the location of the script
• We have seen an example of this before when working with the nav element and older versions of Internet Explorer
Eg.
29
<!--[if lt IE 9]>
<script src="scripts/semantic.js"></script>
<![endif]-->
Creating a Function
31
Javascript document – Thank you function
Statement to add text into the paragraph with id="message"
Creating a Function
32
HTML document
External function to add text into the paragraph with id="message" using the onClick event handler for the button
Storing and Comparing Data in Variables • Javascript has variables that are used to store a
value that needs to be remembered • Variables can be used in subsequent statements
• Javascript has operators which are symbols that are used to compare or change the values of objects or properties • The assignment operator (=) sets a value • The comparison operators (such as == and !=)
determine the equivalence of two values • Logical operators (&& , ||) logically connect multiple
variables in a comparison 33
Storing and Comparing Data in Variables
• Some example JavaScript operators
34
Operator type
Operator Description Example
Comparison == Is equal to If (a == b)
!= Is not equal to If(a != b) Logical && And If (a == b && c == d)
|| Or If (a == b || c == d) ! Not If (a == b) && ! (a == c)
Assignment = assignment var name = "aName"
Storing and Comparing Data in Variables
• One potential use of variables is to store the information that a user entered into a form
• The value in the variable can then be checked to see if it meets the requirements for that field
• If it does not meet the requirements then an alert can be generated and the form submission can be stopped 35
Adding Content Using a Script
36
Javascript document – Check Required Fields function
Store the value in the nameinput field into a variable called name
If the user did not enter a name then show an alert and return false to stop the form submission
If the user did enter a name then update the page using the writeThankYou method, reset the form fields and return true to allow the form to be submitted
Note: The default action for pressing the submit button is to submit the form. Using Javascript to return true (it worked) tells the browser to use the default response (in this case submit the form). Returning false (it did not work) tells the browser not to use the default response (in this case do not submit the form)
Adding Content Using a Script
37
HTML document
External function to check the data entered into the form – only checks name
Adding Content Using a Script
39
Name field is filled out – no error message when submitting the form
Browser preview
Generating Web Page Content Dynamically • JavaScript can be used to reconfigure Web
pages based on user activities or inputs
• This is done by accessing, storing, manipulating, and writing values that have been supplied by the user
• You can create Web pages that are customised in response to user inputs
Eg. You could specify a user’s name, taken from a form field, when displaying a thank-you or greeting message 40
Generating Web Page Content Dynamically • In the next example, we will personalise the Web
page based on what the user has entered for their first name when they submit the form
• We will slightly modify our existing two Javascript functions called checkRequiredFields() and writeThankYou()
• We will take the name that the user entered into the form in checkRequiredFields() and pass it as a parameter to writeThankYou(name)
• The HTML file remains unchanged 41
Generating Web Page Content Dynamically
42
Javascript document – Passing a value to another function
Function writeThankYou takes an input parameter called person and uses it to build a text string to display
Pass the name variable to function writeThankYou so that its value can be used in that function
Store the value in the nameinput field into a variable called name
Generating Web Page Content Dynamically
43
Personalised thank you based on Name field
Browser preview
Scripting Fallback Options with Modernizr
• Fallback options for some newer CSS and HTML features can be provided using JavaScript code
• You can use Modernizr script elements to identify whether the current browser supports specific attributes Eg. Modernizr.input.placeholder will be added to
the DOM by modernizr only if the current browser supports the placeholder attribute for an input element
• Use conditional clauses, such as if statements, to cause fallback statements to be executed only if the desired feature is not supported by current browser 44
Scripting Fallback Options with Modernizr
45
Javascript document – Set default values for text fields
Call function addPlaceholders automatically when the Web page opens
Use Javascript to set default values for name and email fields
If this browser does not support placeholders
Integrating an Existing Script • Many scripts for common tasks exist on
the Web • Developers maintain Web sites where such
scripts can be downloaded and are explained
• It is possible to customise an existing script to perform a task rather than write a totally new one
Make sure any script that you download comes from a reliable source and be sure you know exactly what it does before using it
47
Summary
• The Document Object Model (DOM) is a way of referring to parts of a Web page
• Script code is created by combining DOM objects, properties, and methods, often using the dot notation
• Code for a single instruction in a script is known as a statement
• Scripts can be used to add contents to a page 48
Summary • Scripts can be triggered in response to
events
• Event handlers are used to link a script with a specific event
• A function is a block of code which is called as a single unit and has a name assigned to it • A function has a specific syntax • A function is used to simplify the structure
of a script 49
Summary • Operators and variables are used to
create more complex scripts
• JavaScript can be used to dynamically generate Web page content • This can be done in response to user
actions or input
• JavaScript can be used to provide fallback options for older browsers
• Scripts for many common tasks are available on the Web 50