JavaScript Testing - Eugene Liang Yuxian - E-Book

JavaScript Testing E-Book

Eugene Liang Yuxian

0,0
23,30 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

In Detail

JavaScript is an important part of web development in today's Web 2.0 world. While there are many JavaScript frameworks in the market, learning to write, test, and debug JavaScript without the help of any framework will make you a better JavaScript developer. However, testing and debugging can be time consuming, tedious, and painful. This book will ease your woes by providing various testing strategies, advice, and tool guides that will make testing smooth and easy. This book shows you the most essential features of JavaScript, which you will be using in your daily development, testing, and debugging tasks. You will learn to use the most basic functions of JavaScript to perform ad hoc testing quickly and efficiently. This book is organized in an easy to follow, step-by-step tutorial style to maximize your learning. You will first learn about the different types of errors you will most often encounter as a JavaScript developer. You will also learn the most essential features of JavaScript through our easy to follow examples.As you go along, you will learn how to write better JavaScript code through validation. Learning how to write validated code alone will help you improve tremendously as a JavaScript developer and most importantly, to write JavaScript code that runs better, faster, and with less bugs.As our JavaScript program gets larger, we need better ways of testing our JavaScript code. You will learn how to go about various testing concepts and how to use them in your test plan. After which, you will learn how to implement the test plan for your code. To accommodate more complex JavaScript code, you will learn more about the built-in features of JavaScript to identify and catch different types of JavaScript error. Such information helps to spot the root of the problem so that you can act on it. Finally, you will learn how to make use of the built-in browser tools and other external tools to automate your testing process.

Learn how to test and debug JavaScript through example-driven tutorials.

Approach

This book is organized such that only the most essential information is provided to you in each chapter so as to maximize your learning. Examples and tutorials are given in an easy to follow, step-by-step manner so that you can see how the testing process is being carried out and how the code is being written. The source code also contains detailed explanation so that you know what the code is doing. Multiple screenshots are used in places that matter so that you have a visual sense of what is happening.

Who this book is for

Beginner JavaScript developers looking for essential ways to write, test, and debug JavaScript for different purposes and situations.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 360

Veröffentlichungsjahr: 2010

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



JavaScript Testing

Beginner's Guide

JavaScript Testing

Beginner's Guide

Copyright © 2010 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author nor Packt Publishing and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: August 2010

Production Reference: 1130810

Published by Packt Publishing Ltd.

32 Lincoln Road

Olton

Birmingham, B27 6PA, UK.

ISBN: 978-1-849510-00-4

www.packtpub.com

Cover Image by Vinayak Chittar ( <[email protected]> )

Credits

Author

Liang Yuxian Eugene

Reviewers

Chetan Akarte

Kenneth Geisshirt

Stefano Provenzano

Aaron Saray

Mihai Vilcu

Acquisition Editor

Steven Wilding

Development Editor

Tarun Singh

Technical Editors

Paramanand N. Bhat

Pooja Pande

Copy Editors

Lakshmi Menon

Janki Mathuria

Editorial Team Leader

Akshara Aware

Project Team Leader

Priya Mukherji

Project Coordinator

Vincila Colaco

Indexer

Hemangini Bari

Proofreader

Dirk Manuel

Production Coordinator

Shantanu Zagade

Cover Work

Shantanu Zagade

About the Author

Liang Yuxian Eugene enjoys solving difficult problems creatively in the form of building web applications by using Python/Django and JavaScript/JQuery. He also enjoys doing research related to the areas of recommendation algorithms, link analysis, data visualization, data mining, information retrieval, business intelligence, and intelligent user interfaces. He is currently pursuing two degrees, Business Administration and Computer Science at National Cheng Chi University (NCCU) at Taipei, Taiwan. Eugene has recently started a personal blog at http://www.liangeugene.com.

I want to thank all of the great folks at Packt Publishing for giving me the opportunity to write this book. This book would not be possible without the help, advice and timely correspondence of Steven Wilding, Tarun Singh, Vincila Colaco and Priya Mukherji of Packt Publishing.

I want to thank Professor Johannes K. Chiang (Department of Management of Information Systems, NCCU) and Professor Li Tsai Yen (Department of Computer Science, NCCU) for their unwavering generosity in providing both personal and professional advice to me whenever I needed it.

I want to thank my family and friends for their continued support.

Last but not the least, I want to thank Charlene Hsiao for her kind understanding and tireless support for me.

About the Reviewers

Chetankumar D. Akarte has been working in PHP, JavaScript and .Net for the last five years. He has worked extensively on both small scale and large scale PHP and .Net ecommerce, social networking, Wordpress and Joomla based web projects. Over the years, Chetan has been actively involved in the "Xfunda Developers Community". He has regularly blogged on Microsoft .NET technology at http://www.tipsntracks.com.

Chetan completed a Bachelor of Engineering degree in Electronics from the Nagpur University, India in 2006. He likes contributing to newsgroups, and forums. He has also written some articles for Electronics For You, DeveloperIQ, and Flash & Flex Developer's magazines.

Chetan lives in Navi Mumbai, India. You can visit his websites at http://www.xfunda.com and http://www.tipsntracks.com, or get in touch with him at <[email protected]>.

I would like to thank my sister Poonam and brother-in-law Vinay for their consistent support and encouragement. I would also like to thank Packt Publishing for providing me with the opportunity to do something useful, and especially my Project Coordinator Vincila Colaco for all of the valuable support.

Kenneth Geisshirt is a chemist by education and a geek by nature. He has been programing for more than 25 years—the last six years as a subcontractor. In 1990 Kenneth first used free software, and in 1992 turned to Linux as a primary operating system (officially Linux user no. 573 at the Linux Counter). He has written books about Linux, PAM, and Javascript and many articles on open source software for computer magazines. Moreover, Kenneth has been a technical reviewer of books on Linux network administration and the Vim editor.

Stefano Provenzano is an Italian senior consultant and professional software engineer. Stefano has worked on several projects in different fields of computer science 3D realtime engines for PC and Playstation games, visual simulation and virtual prototyping, web applications, and system integration. In 2006, Stefano started his own software development and consulting company, Shin Software. Currently, Stefano is developing CRM and INTRANET applications by using PHP and Javascript.

I want to thank my wife Irene and my little son Davide.

Aaron Saray found love when he was eight. It was in the shapely form of a Commodore 64. From then on, he continued to devote his time to various programing languages from BASIC to Pascal, PHP to Javascript, HTML to CSS. Aaron is both an author of a PHP Design Patterns book and a technical editor of other PHP and Javascript books. He has also worked as a professional in the Web Development field for almost a decade, and comes with a solid history to provide his vast experience to the review of this book. You can find more about his work at his technical blog by visiting http://aaronsaray.com/blog.

As each book project becomes complete, I learn more about my industry and myself. I want to specifically thank my best friend for consistently reminding me that life is always better with balance.

Mihai Vilcu has had exposure to top technologies in testing for both automated and manual testing. "Software testing excellence" is the motto that drives Mihai's career". This includes functional and non-functional testing. Mihai was also involved over several years in large scale testing projects.

Some of the applications covered by Mihai in his career include CRMs, ERPs, billing platforms, rating, collection and business process management applications.

As software platforms are used intensely in many industries, Mihai has performed testing in fields like telecom, banking, healthcare, software development, and others.

Feel free to contact Mihai for questions regarding testing on his email: <[email protected]>, or directly on his website at www.mvfirst.ro.

Preface

JavaScript is an important part of web development in today's Web 2.0 world. Although there are many JavaScript frameworks in the market, learning to write, test, and debug JavaScript without the help of any framework will make you a better JavaScript developer. However, testing and debugging can be time-consuming, tedious and painful. This book will ease your woes by providing various testing strategies, advice, and tool guides that will make testing smooth and easy.

This book is organized in an easy-to-follow, step-by-step tutorial style, in order to maximize your learning. You will first learn about the different types of errors that you will most often encounter as a JavaScript developer. You will also learn the most essential features of JavaScript through our easy-to-follow examples.

As you go along, you will learn how to write better JavaScript code through validation; learning how to write validated code alone will help you improve tremendously as a JavaScript developer and, most importantly, help you to write JavaScript code that runs better, faster, and with less bugs.

As our JavaScript program gets larger, we need better ways of testing our JavaScript code. You will learn about various testing concepts and how to use them in your test plan. After which, you will learn how to implement the test plan for your code. To accommodate more complex JavaScript code, you will learn more about the built-in features of JavaScript, in order to identify and catch different types of JavaScript error; such information helps to spot the root of the problem so that you can act on it.

Finally, you will learn how to make use of the built-in browser tools and other external tools to automate your testing process.

What this book covers

Chapter 1, What is JavaScript Testing?, covers JavaScript's role and the basic building blocks in web development, such as HTML and CSS. It also covers the types of errors that you will most commonly face.

Chapter 2, Ad Hoc Testing and Debugging in JavaScript, covers why we perform ad hoc testing for our JavaScript programs, and JavaScript's most commonly-used features, by writing a simple program, This program will be used as an example to perform ad hoc testing.

Chapter 3, Syntax Validation, covers how to write validated JavaScript. After completing this chapter, you will have improved your skills as a JavaScript developer and, at the same time, understood more about the role of validation in testing JavaScript code.

Chapter 4, Planning to Test, covers the importance of having a plan to test, and the strategies and concepts we can use when we are performing testing. This chapter also covers the various strategies and concepts for testing, and we will perform a simple test plan to see what it means to plan to test.

Chapter 5, Putting the Test Plan Into Action, follows Chapter 4, as we apply the simple test plan that we have developed. Most importantly, we will get our hands dirty by uncovering bugs, taking note of them and fixing the bugs by applying the theories that we learnt in Chapter 4.

Chapter 6, Testing More Complex Code, covers sophisticated ways to test our code. One way of testing the code is to use the built-in error objects provided by JavaScript. This chapter also covers how to use the console log, how to write your own messages, and how to trap your errors.

Chapter 7, Debugging Tools, addresses the point where our code gets too large and complex to be tested by using manual methods. We now engage the help of debugging tools provided by popular browsers in the market, including Internet Explorer 8, FireFox 3.6, Chrome 5.0, Safari 4.0 and Opera 10.

Chapter 8, Testing Tools, moves into how you can automate your testing by using testing tools that are free, cross-browser and cross-platform. It also covers how to test your interface, automate tests, and perform assertion and benchmarking tests.

What you need for this book

A basic text editor such as Notepad++.

Browsers like Internet Explorer 8, Google Chrome 4.0, Safari 4.0 and newer, FireFox 3.6.

JavaScript version 1.7 or later.

Other software covered includes Sahi, JSLitmus, QUnit.

Who this book is for

This book is for beginner JavaScript programmers or beginner programmers who may have little experience in using JavaScript, with HTML and CSS.

Conventions

In this book, you will find several headings appearing frequently.

To give clear instructions of how to complete a procedure or task, we use:

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title in the subject of your message.

If there is a book that you need and would like to see us publish, please send us a note via the SUGGEST A TITLE form on www.packtpub.com, or send an e-mail to <[email protected]>.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book on, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Note

Downloading the example code for this book

You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. What is JavaScript Testing?

First of all, let me welcome you to this book. If you've picked up this book, I would assume that you are interested in JavaScript testing. You most probably have experienced JavaScript, and want to enhance your skills by learning how to test your JavaScript programs.

JavaScript is most often associated with the web browser and is one of the key tools for creating interactive elements on web pages. However, unlike server-side languages like PHP, Python and so on, JavaScript fails silently in general (although browsers like IE provides warning messages at times); there are no error messages to inform you that an error has occurred. This makes debugging difficult.

In general, we will be learning about the basic building blocks for JavaScript testing. This will include the basics of HTML (Hyper-text Markup Language), CSS (Cascading Style Sheets ) and JavaScript. After this, you will learn about various techniques to make HTML, CSS, and JavaScript work together; these techniques are the building blocks of what you are going to learn in other chapters.

To be more specific, this is what we will learn about in this chapter:

The basics of HTML, CSS, and JavaScriptThe syntax of HTML, CSS, and JavaScriptHow to select HTML elements by using CSS and JavaScriptWhy do web pages need to work without JavaScript?What is testing and why do you need to test?What is an error?Types of JavaScript errors

Examples shown in this chapter are simplistic—they are designed to allow you to see the major syntax and built-in methods or functions that are being used. In this chapter, there will be minimal coding; you will be asked to enter the code. After that, we'll briefly run through the code examples and see what is happening.

With that in mind, we'll get started right now.

Where does JavaScript fit into the web page?

Every web page consists of the following properties—content, appearance, and behavior. Each of these properties is controlled by Hyper Text Markup Language (HTML), Cascading Style Sheets (CSS), and JavaScript, respectively.

HTML Content

HTML stands for Hyper Text Markup Language. It is the dominant markup language for web pages. In general, it controls the content of a web page. HTML defines web pages (or HTML documents) through semantic markups such as<head>, <body>, <form>, and<p> to control headings, the body of a document, forms, paragraphs, and so on. You can see HTML as a way to describe how a webpage should look like.

HTML makes use of markup tags, and these tags usually come in pairs. The syntax of HTML is as follows:

<name-of-html-tag> some of your content enclosed here </name-of-html-tag>

Notice that the HTML tags are enclosed by angular brackets; the HTML tag pair starts off with <name-of-html-tag> and ends with </name-of-html-tag>. This second HTML tags are known as the closing tags and they have a forward slash before the HTML tag.

Some of the common html elements include the following:

<head> </head><body> </body><title> </title><p> </p><h1> </h1><a> </a>

For a complete list of html elements, please visit http://www.w3schools.com/tags/default.asp.

Time for action—building a HTML document

We are going to create an HTML document by making use of some of the HTML tags and syntax that we have seen above. (The example you see here can be found in the source code folder of Chapter 1, with the document titled chapter1-common-html.html)

Let's start by opening your favorite text editor or tool such as Microsoft Notepad, and creating a new document.Enter the following code into your new document and save it.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>This is a sample title</title> </head> <body> <h1>This is header 1</h1> <h2>This is header 2</h2> <h3>This is header 3</h3> <p>This is a paragraph. It can be styled by CSS</p> <hr> <div style="position:absolute; background-color:black; color:#ffffff;top:10px;right:10px;border:solid 3px yellow; height:200px; width:200px;">Your content here</div> <div> <div>I am enclosed within a <i>div</i> tag. And it can be styled on a document level. <ol> <li>This is an ordered list and it is centered</li> <li>apple</li> <li>orange</li> <li>banana</li> </ol> <ul> <li>This is an unordered list. And it can be styled by CSS.</li> <li>apple</li> <li>orange</li> <li>banana</li> </ul> </div> <div>I am enclosed within a <i>div</i> tag. And it can be styled by CSS. <ol> <li>This is an ordered list and it is centered</li> <li>apple</li> <li>orange</li> <li>banana</li> </ol> <ul> <li>This is an unordered list. And it can be styled by CSS</li> <li>apple</li> <li>orange</li> <li>banana</li> </ul> <a href="#">This is a link. And it can be styled by CSS </a> </div> </div> </body> </html>
Finally, open the document in your browser and you will see an example similar to the following screenshot:
Take note of the black box on the upper-right corner. It is a simple example of CSS at work. This will be explained shortly.

What just happened?

You have just created an HTML document by using the more common HTML elements and HTML syntax.

Each HTML tag has a specific purpose, as you can see from the result in the browser. For example, you must have noticed that<h1>This is header 1</h1> produced the largest text in terms of font-size,<h2>This is header 2</h2> produced the second largest text in terms of font size, and so forth.

<ol> </ol> represents an ordered list, while<ul> </ul> stands for an unordered list (list with bullet points).

You should have noticed the use of<div> </div>. This is used to define a section within an HTML document. However, the effects and power of the<div> </div> can only be seen in the next part of this chapter.

But wait, it seems that I have not done a complete introduction of HTML. That's right. I have not introduced the various attributes of HTML elements. So let's have a quick overview.

Styling HTML elements using its attributes

In general, the core attributes of HTML elements are the class, id, style, and title attribute. You can use these attributes in the following manner:

<div id="menu" class="shaded" style="..." title="Nice menu"> Your content here </div>

Notice that all four attributes could be used at the same time. Also, the sequence of the attributes does not matter.

But we have not done any styling yet. The styling only takes place in the style attribute. To see an example, enter the following code between the<body> and</body> tag in the previous code.

<div style= "position:absolute; background-color:black;color:#ffffff; top:10px;right:10px;border:solid 3px yellow; height:200px; width:200px;">Your content here </div>

You should be able to see a 200px by 200px black box with yellow border in the upper-right corner of your browser window (as shown in the previous screenshot). Here's a screenshot that shows only the black box:

In general, the inline style that you have specified manipulates the stylistic properties of the style attribute, to make it look the way you want it to.

Only the style attribute allows you to style the HTML element. But this method is only used for specifying inline style for an element.

In case you are wondering what the<title> tag does, it is essentially an attribute that specifies extra information about an element. This is most often used within the<head> tag. If you open up any HTML document that contains a<title> tag, you will find the contents of this tag in the tab of your browser or title of your browser window.

What about id attribute and class attribute? We'll cover these briefly in the next section.

Specifying id and class name for an HTML element

In general, the id attribute and class attribute allows the HTML element to be styled by giving the CSS (Cascading Style Sheets, which we will be covering later in this chapter) a way to refer to these elements. You can think of the id attribute and class attribute as a 'name', or a way to identify the corresponding HTML element such that if this 'name' is referred by the CSS, the element will be styled according to the CSS defined for this particular element. Also, the id attribute and class attribute are often referred to by JavaScript in order to manipulate some of the DOM (Document Object Model) attributes, and so on.

There is one important idea that you must understand at this point of the chapter: the id attribute of each HTML element has to be unique within an HTML file, whereas the class attribute doesn't.

Cascading Style Sheets

CSS stands for Cascading Style Sheet. A CSS is used to control the layout, appearance, and formatting of the web page. CSS is a way for you to specify the stylistic appearance of the HTML elements. Via CSS, you can define the fonts, colors, size, and even layout of the HTML elements.

If you noticed, we have not added any form of CSS styles to our HTML document yet; in the previous screenshots, what you see is the default CSS of our browser (apart from the black box on the upper-right), and most browsers have the same default CSS if no specific CSS is defined.

CSS can be internal or external; an internal CSS is embedded in a HTML document using the<style> tag, whereas an external CSS is linked to by using the<link> tag, for example:

<link rel="stylesheet" type="text/css" href="style.css">.

In general, using internal CSS is considered to be a bad practice and should be avoided. External CSS is widely favored over internal CSS because it allows us to save more time and effort as we can change the design of the website by just making changes to a .css file instead of making individual changes to each HTML document. It also helps in improving performance, as the browser will only need to download one CSS and cache it in memory.

The most important point for this section is the use of CSS selectors and the syntax of the CSS.

The CSS selectors work as follows: for selecting IDs, the name of the ID is preceded by a hash character. For a class selector, it is preceded by a dot. In the code that you will be seeing later, you will see that both ID and class selectors are used (they are also commented in the source code). Here's a quick preview of the selectors:

/* this is a id selector */ #nameOfID { /* properties here*/ } /* this is a class selector */ .nameOfClass { /* properties here*/ }

The syntax of the CSS is as follows: selector { declaration } . The declaration consists of a semicolon-separated list of name or value attribute pairs, in which colons separate the name from the value.

Remember that we've mentioned the id attribute and class attribute in the preceding section? Now you will see how id attributes and class attribute are being used by CSS.

Time for action—styling your HTML document using CSS

Now we are going to style the HTML document that we created in the preceding section, by using CSS. For simplicity, we'll use an internal CSS. What will happen in this section is that you will see the CSS syntax in action, and how it styles each HTML element by making use of the id attribute and class attribute of the respective HTML element. Note that both id and class selectors are used in this example.

Note

The completed version of this example can be found in the source code folder of Chapter 1, with the file name: chapter1-css-appearance.html

Continuing from the previous example, open up your text editor and insert the following code after the</title> tag:
<style type="text/css"> body{ background-color:#cccccc; } /* Here we create a CSS selector for IDs by a name preceded by a hash character */ #container{ width:750px; /* this makes the width of the div element with the id 'container' to have a width of 750px */ height:430px; border:1px solid black;solid 1px black; } /* #[nameOfElement] */ #boxed1{ background-color:#ff6600; border:2px solid black; height:360px; width:300px; padding:20px; float:left; margin:10px; } #boxed2{ HTML documentstyling, CSS usedbackground-color:#ff6600; border:2px solid black; height:360px; width:300px; padding:20px; float:left; margin:10px; } #ordered1{ font-size:20px; color:#ce0000; text-align:center; } #unordered1{ font-size:12px; color:#000f00; } #ordered2{ font-size:20px; color:#ce0000; text-align:center; } #unordered2{ font-size:12px; color:#000f00; } #unordered2.nice{ font-size:16px; } .intro{ color:black; font-weight:bold; } a:link {color:#FF0000;} /* unvisited link */ a:visited {color:#00FF00;} /* visited link */ a:hover {color:#FF00FF;} /* mouse over link */ a:active {color:#0000FF;} /* selected link */ </style>
After adding the CSS code above, you will need to add class and id attributes to your HTML elements. Here's the stuff you'll need to add:
<! - Some code omitted above -- > <body> <! - Some code omitted -- > <p class="intro">This is a paragraph. I am styled by a class called "intro"</p> <hr> <div id="container"> <div id="boxed1">I am enclosed within a <i>div</i> tag. And I can be styled on a document level. <ol id="ordered1"> <li>This is an ordered list and it is centered</li> <li>apple</li> <li>orange</li> <li>banana</li> </ol> <ul id="unordered1"> <li>This is an unordered list.</li> <li>apple</li> <li>orange</li> <li>banana</li> </ul> <a class="link" href="#">I am a link that is styled by a class</a> </div> <div id="boxed2">I am enclosed within a <i>div</i> tag. And I am styled on a local level. <ol id="ordered2"> <li>This is an ordered list and it is centered</li> <li>apple</li> <li>orange</li> <li>banana</li> </ol> <ul class="nice" id="unordered2"> <li>This is an unordered list and I have a class defined</li> <li>apple</li> <li>orange</li> <li>banana</li> </ul> <a class="link" href="#">I am a link that is styled by a class</a> </div> </div> </body> </html>

The class and id attributes that need to be added are highlighted in the code snippet above. If you are not sure if you have done it correctly, open up chapter1-css-appearance.html and have a look.

Now save the file and open it in your browser. You should see that your HTML document now looks different to how it was before it was styled by CSS. Your output should be similar to the example shown in following screenshot:

What just happened?

You have just applied CSS to the HTML document that you created in the previous section. Notice that you have used both the id selector and class selector syntax. Within each selector, you should also see some stylistic attributes.

The HTML elements in this example are similar to the previous example, except that the HTML elements now have id and class names.

In the following sub-sections, I'll continue to explain the techniques used for referring to the various HTML elements, and how we styled the elements by using their stylistic attributes.

Referring to an HTML element by its id or class name and styling it

We referenced various HTML elements by its id or class name. Consider the following code snippet in the above example:

<! some code omitted above--> <p class="intro">This is a paragraph. I am styled by a class called "intro"</p> <! some code omitted --> <div id="boxed">This is enclosed within a <i>div</i> tag. And it is styled on a local level. <ol id="ordered1"> <li>This is an ordered list and it is centered</li> <li>apple</li> <li>orange</li> <li>banana</li> </ol> <ul class="nice" id="unordered1"> <li>This is an unordered list and has a class defined</li> <li>apple</li> <li>orange</li> <li>banana</li> </ul> <a class="link" href="#">This is a link that is styled by a class</a> </div>

The highlighted code refers to the HTML elements where ids and class name attributes are being used. Notice that some of the HTML elements have both ids and class name attributes while some do not.

Now consider the CSS snippet which is found in the example:

#boxed1{ background-color:#ff6600; border:2px solid black; height:360px; width:300px; padding:20px; float:left; margin:10px; }

The #boxed1 selector refers to the<div> with the id #boxed1 in the HTML document. Notice that the<div> with the id #boxed1 is styled according to the name and value attribute pairs within the declaration. If you make some changes to the value attribute and refresh your browser, you will notice changes to the #boxed1 element as well.

Now, consider the following CSS snippets:

.intro{ color:black; font-weight:bold; }

And:

a:link {color:#FF0000;} /* unvisited link */ a:visited {color:#00FF00;} /* visited link */ a:hover {color:#FF00FF;} /* mouse over link */ a:active {color:#0000FF;} /* selected link */

The previous two code snippets are what we call class selectors, which have a slightly different syntax than the id selectors. For instance the .intro class selector selects the<p> with class name "intro" while the a:link , a:visited, a:hover, and a:active selectors refer to the four states of an anchor pseudo class.

Until now, we have covered how CSS selectors work to select HTML elements in an HTML document. But we have not covered the situation where an HTML element has both id and class attributes; we'll explain it now.

Differences between a class selector and an id selector

Although id selectors and class selectors appear to be the same, there are subtle differences. For instance, the id selector is used to specify a single HTML element, whereas the class selector is used to specify several HTML elements.

For example, you may try changing the anchor element<a class="link" href="#"> to<a class="intro" href="#"> and you would notice that the link is now bold.

Note

If an HTML element has a style attribute that is controlled by both the stylistic attributes of an id and class selector, then the style attributes in the class selector will take precedence over those in the id selector.

Other uses for class selectors and id selectors

In the following section, you will learn that the id and class name of an HTML element play an important role in providing interactivity on a web page. This is done by using JavaScript, where JavaScript makes a reference to an HTML element either by its id or class name, after which various actions such as DOM manipulation are performed on the HTML element that is referenced.

Complete list of CSS attributes

The examples given here are not complete. For a complete reference to CSS, you may visit http://www.w3schools.com/css/css_reference.asp.

JavaScript providing behavior to a web page

In this section we'll cover some of the key aspects of JavaScript. In general, if HTML provides content for an HTML document and CSS styles the HTML document, then JavaScript breathes life into an HTML document by providing behavior to the webpage.

The behavior can include changing the background colour of an HTML document dynamically, or changing the font size of the text, and so on. JavaScript can even be used to create effects such as animating slideshows, and fade-in and fade-out effects.

In general, the behaviors are event-based, and are achieved by manipulating the DOM in real-time (at least from the users' point of view).

In case you are fairly new to JavaScript, JavaScript is an interpreted programing language with object-oriented capabilities. It is loosely-typed, which means that you do not need to define a data type when declaring variables or functions.

In my opinion, the best way to understand the language features of JavaScript is through an example. Now, it's time for action.

Time for action—giving behavior to your HTML document

We are going to apply JavaScript to an HTML document (styled with CSS). In general, the HTML elements and CSS are not changing as compared to the previous example, except that you will see HTML buttons added to the HTML document.