Html5 Nextgen Web-Intl
Html5 Nextgen Web-Intl
Dear Learner,
We congratulate you on your decision to pursue an Aptech course. Aptech Ltd. designs its courses using a sound instructional design model from conceptualization to execution, incorporating the following key aspects: Scanning the user system and needs assessment Needs assessment is carried out to find the educational and training needs of the learner Technology trends are regularly scanned and tracked by core teams at Aptech Ltd. TAG* analyzes these on a monthly basis to understand the emerging technology training needs for the Industry. An annual Industry Recruitment Profile Survey# is conducted during August - October to understand the technologies that Industries would be adapting in the next 2 to 3 years. An analysis of these trends & recruitment needs is then carried out to understand the skill requirements for different roles & career opportunities. The skill requirements are then mapped with the learner profile (user system) to derive the Learning objectives for the different roles. Needs analysis and design of curriculum The Learning objectives are then analyzed and translated into learning tasks. Each learning task or activity is analyzed in terms of knowledge, skills and attitudes that are required to perform that task. Teachers and domain experts do this jointly. These are then grouped in clusters to form the subjects to be covered by the curriculum. In addition, the society, the teachers, and the industry expect certain knowledge and skills that are related to abilities such as learning-to-learn, thinking, adaptability, problem solving, positive attitude etc. These competencies would cover both cognitive and affective domains.
A precedence diagram for the subjects is drawn where the prerequisites for each subject are graphically illustrated. The number of levels in this diagram is determined by the duration of the course in terms of number of semesters etc. Using the precedence diagram and the time duration for each subject, the curriculum is organized.
Design & development of instructional materials The content outlines are developed by including additional topics that are required for the completion of the domain and for the logical development of the competencies identified. Evaluation strategy and scheme is developed for the subject. The topics are arranged/organized in a meaningful sequence.
The detailed instructional material Training aids, Learner material, reference material, project guidelines, etc.- are then developed. Rigorous quality checks are conducted at every stage. Strategies for delivery of instruction Careful consideration is given for the integral development of abilities like thinking, problem solving, learning-to-learn etc. by selecting appropriate instructional strategies (training methodology), instructional activities and instructional materials. The area of IT is fast changing and nebulous. Hence considerable flexibility is provided in the instructional process by specially including creative activities with group interaction between the students and the trainer. The positive aspects of Web based learning acquiring information, organizing information and acting on the basis of insufficient information are some of the aspects, which are incorporated, in the instructional process. Assessment of learning The learning is assessed through different modes tests, assignments & projects. The assessment system is designed to evaluate the level of knowledge & skills as defined by the learning objectives. Evaluation of instructional process and instructional materials The instructional process is backed by an elaborate monitoring system to evaluate - on-time delivery, understanding of a subject module, ability of the instructor to impart learning. As an integral part of this process, we request you to kindly send us your feedback in the reply prepaid form appended at the end of each module.
*TAG Technology & Academics Group comprises of members from Aptech Ltd., professors from reputed Academic Institutions, Senior Managers from Industry, Technical gurus from Software Majors & representatives from regulatory organizations/forums. Technology heads of Aptech Ltd. meet on a monthly basis to share and evaluate the technology trends. The group interfaces with the representatives of the TAG thrice a year to review and validate the technology and academic directions and endeavors of Aptech Ltd.
1
Scanning the user system and needs assessment Evaluation of Instructional Processes and Material
Assessment of learning
Preface
HyperText Markup Language (HTML) is the markup language popularly used by developers to design Web sites. It is the language for the World Wide Web. It is used for building Web sites that can be as large as a corporate Web site or as small as a single page classroom project. This book covers basic to advanced concepts of HTML5. The book begins with an explanation of basic HTML tags and attributes. It also explains the structure of Web pages using HTML. Then, it proceeds to explain the concept of Cascading Style Sheets (CSS). CSS is a technology that helps Web site designers to provide a consistent formatting across large Web sites by separating the content from its styles. Thus, CSS is used to control the look of the Web page by specifying the styles such as color, font, and font size for the HTML content. It can also be used to control the placement of items on a page. The book also explains JavaScript, which is a scripting language used for adding interactivity to Web pages. JavaScript allows programs in an HTML page to respond to users actions. These responses could be validating the users input, fetching and displaying the requested page, and so on. Finally, the book concludes with explanations of jQuery and HTML5 mobile application support. jQuery is a short and fast JavaScript library that simplifies the client side scripting of HTML, animation, event handling, traversing, and developing AJAX based Web applications. The knowledge and information in this book is the result of the concentrated effort of the Design Team, which is continuously striving to bring to you the latest, the best and the most relevant subject matter in Information Technology. As a part of Aptechs quality drive, this team does intensive research and curriculum enrichment to keep it in line with industry trends and learner requirements. We will be glad to receive your suggestions. Please send us your feedback, addressed to the Design Centre at Aptechs corporate office, Mumbai.
Design Team
Table of Contents
Sessions
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. Introduction to the Web Introduction to HTML5 Formatting Text Using Tags Creating Hyperlinks and Anchors Introduction to CSS3 Formatting Using Style Sheets Displaying Graphics and CSS3 Animation Creating Navigational Aids and Division-Based Layout Creating Tables HTML Forms HTML5 Audio and Video Introduction to JavaScript Operators and Statements Loops and Arrays Functions and Objects Building a Mobile Web Application Canvas and JavaScript HTML5 Web Storage HTML5 Geolocation and APIs 1 23 39 63 75 109 139 171 205 235 271 293 333 367 397 443 483 521 557
Session
1
Introduction to the Web
1.1 Introduction
HyperText Markup Language (HTML) was introduced in the year 1990. Since then, there has been continuous evolution in the technology leading to introduction of new versions. Some features were introduced in specifications, whereas others were introduced in software releases. HTML 4 was recommended as a standard by W3C in 1997. HTML5 is the next version of HTML and will be the new standard. HTML 4.01 was the previous version of HTML which was released in 1999. Since then, there have been constant evolutions and additions to the World Wide Web (WWW). Majority of the browsers support HTML5 elements and Application Programming Interfaces (APIs).
LAN refers to a computer network in a small geographical area such as office, home, or school. MAN refers to a network that covers a city. WAN refers to a network that connects LANs and MANs across the globe.
Concepts
of 590
Session
1
Introduction to the Web
of 590
Concepts
Session
1
Introduction to the Web A Web page is a file that contains information and instructions to display the information to the users. Figure 1.2 shows the relation between Web and Internet.
Concepts
of 590
Session
3.
1
Introduction to the Web
The Web server processes the request and sends the Web page as a response to the browser as shown in figure 1.3.
of 590
Concepts
Session
1
Introduction to the Web
1.1.6 Technologies
Dynamic Web sites can include Web pages containing static as well as dynamic content. The main advantage of using dynamic Web page is that, it allows customizing the content and its appearance in the browser. A dynamic Web site interacts with the database to generate dynamic content. A database is a collection of organized data. This data can be stored and retrieved using the technologies used in creating dynamic Web sites. Some of the technologies used for creating dynamic Web sites are as follows:
JavaScript
JavaScript is a scripting language developed by Netscape for creating dynamic Web pages. It is used to develop interactive Web pages by adding programming to HTML.
Cascading Style Sheets (CSS)
CSS are style sheets that specify the formatting of a Web page for both static and dynamic Web pages. The formatting options include font, color, background, spacing, positioning, and borders. It is used in combination with JavaScript to format Web pages dynamically.
Extensible HTML (XHTML)
Concepts
XHTML is a language that combines HTML with Extensible Markup Language (XML). XML allows defining your own data in a structured format, which can be displayed in any browser. When you use XHTML with JavaScript, the required user-defined data is displayed each time the Web page is loaded in the browser.
Dynamic HTML (DHTML)
Dynamic HTML (DHTML) uses JavaScript and CSS to make dynamic Web pages. It allows you to transform the look and feel of Web pages. It allows Web pages to respond to the users actions and enables focus on the content changes in the browser. V 1.1 Aptech Limited
of 590
Session
1
Introduction to the Web
1.2 History
HTML is a markup language used primarily to create hypertext Web pages, which are published on the Web and displayed in any Web browser. A markup language is a set of notations that specifies how the content should look in the browser. HTML is derived from Standard Generalized Markup Language (SGML), which is the mother language of HTML. SGML is a markup language that defines the structure of other markup languages. HTML has evolved over the years with the introduction of improved set of standards and specifications. HTML 1.0 was the first version of HTML introduced in 1993. At that time, there were very less people involved in designing Web sites. HTML 2.0 was introduced in 1995 and included the complete HTML 1.0 specifications with additional features. The other versions are as follows:
HTML 3.0
HTML 3.0 specifications included new features for the Netscape Navigator browser as it became very popular. The new improvements did not work on any other browsers such as Internet Explorer. Therefore, this specification was abandoned.
HTML 3.2
Additional browser-specific features revolutionized the need for standardization of HTML. Therefore, the World Wide Consortium (W3C) organization was formed to specify and maintain the HTML standards. HTML 3.2 was the first specification introduced by W3C in January 1997 and was fully supported by all the Web browsers.
HTML 4.0
W3C introduced HTML 4.0 in December 1997 with the motive for facilitating support for CSS, DHTML, and JavaScript. However, HTML 4.0 prevailed for a short period and was revised, which led to HTML 4.01 specification in 1999.
HTML5
HTML5 is cooperative project between the W3C and the Web Hypertext Application Technology Working Group (WHATWG). W3C was busy working with XHTML 2.0 and WHATWG was working with Web forms, new HTML features, and applications. In 2006, the two groups decided to work together and develop a new version of HTML. Some basic rules for HTML5 that were established are as follows: Introduction of new features should be based on HTML, CSS, DOM, and JavaScript More markup should be used to replace scripting
of 590
Concepts
Session
1
Introduction to the Web HTML5 must be device independent Need for external plug-ins, such as Flash, to be reduced Better error handling capabilities Development process should be completely visible to the public
Concepts
of 590
Session
1
Introduction to the Web
Figure 1.4: Layout of a Web Page in HTML5 The Header on the top usually has the logo, name, subtitles, and short descriptions of the Web site or Web page. After that is the Navigation Bar that includes a menu that contains links for navigation. Web users can navigate to different pages or documents using the navigation bar. The most relevant content is generally shown in the middle of the page. The content presented in the Main Information part of the layout usually has a top priority. It can have a list of products, description of products, blogs, or any other important information. The Side Bar shows a list of links that lead to certain items that may be present internally on the Web site or on an external link. For example, in a blog, the last column offers a list of links that can lead to the blog entries, information about the author, and so on. These two sections are extremely flexible. Web designers can perform variety of actions, such as inserting more rows or splitting the columns, to edit the Web page as required. The footer at the bottom is used to represent general information about the Web site. This can include the author or the company name, links regarding rules, terms and conditions, location maps, and any other additional data.
of 590
Concepts
Session
1
Introduction to the Web HTML5 adds new capabilities to the previous version of HTML. It is a revised code build on the basis of HTML 4. HTML5 provides major improvement through better interactivity, multimedia services, and application handling. For example, you can directly play a video or audio on any browser without the need to install external plug-ins such as Flash or Silverlight. XHTML was a version of HTML 4 that was created along with XML. It was a rigid, standardsbased language that allowed no room for errors. XHTML was supposed to be the next version of HTML 4 but due to interoperability problems, it took a backseat and HTML5 would be the next standard for Web site development.
Concepts
HTML5 is a family of technologies that gives whole new options for building Web pages and applications.
10 of 590
Session
1
Introduction to the Web
HTML5 is made up of a family of technologies. HTML consists of markups, improved CSS with CSS3 that provides added options to style your pages. There is also JavaScript and a new set of JavaScript APIs that are available in HTML5. The process generally followed for HTML5 is as follows: 1. 2. 3. 4. The browser loads the document, which includes HTML markup and CSS style. After the browser loads the page, it also creates an internal model of the document that contains all the elements of HTML markup. The browser also loads the JavaScript code, which executes after the page loads. The APIs give access to audio, video, 2D drawing with the canvas, local storage, and other technologies that are required to build apps.
11 of 590
Concepts
Session
1
Introduction to the Web HTML5 allows Web applications to be executed offline by storing the files and other resources required in the application cache. Web application data is saved locally using Web SQL databases.
Concepts
Session
1
Introduction to the Web
A CSS is a rule-based language, which specifies the formatting instructions for the content specified in an HTML page. Its purpose is to separate HTML content from its formatting so that Web page designers would not worry about the formatting and layout. This is because they can define the layout and formatting of the content in a separate file saved with an extension of .css. In the .css file, the formatting instructions for an element are referred to as a rule set. Each rule defines how the content specified within an element should be displayed in a Web browser. While displaying the HTML page, the browser identifies the .css file for the page and applies the rules for the specified elements. You can merge the rules from different .css files or can edit them. This task of combining and matching rules from different files is referred to as cascading. Figure 1.6 shows an example of CSS.
Multiple HTML pages can use a CSS document. CSS provides some useful benefits that make it an ideal choice to specify the appearance of the content in an HTML page. These benefits are as follows:
Code Reusability: CSS saves time by specifying the formatting options of an element
Less HTML Code: CSS helps in reducing the file size of HTML documents by
Session
1
Introduction to the Web
Device Independence: CSS is designed for different devices to provide the same
The rendering engine is a software that applies the formatting instructions to the Web page and displays the formatted content on the screen. Figure 1.7 shows the working of CSS.
Concepts
Session
1
Introduction to the Web
1.8 JavaScript
JavaScript helps to build dynamic Web pages by ensuring maximum user interactivity. JavaScript is a scripting language that supports object-oriented programming style. This means that it provides objects for specifying functionalities. An object has a unique identity, state, and behavior. JavaScript being a light-weight programming language is embedded directly into HTML pages. JavaScript is also free for use by all. It is the most popular scripting language and is supported by the major browsers.
Besides the points mentioned JavaScript can also perform the following functionalities: JavaScript helps Web designer to insert code snippets into the HTML pages without the need to have in-depth programming knowledge. JavaScript can be used to execute events on certain user actions such as on click of a HTML element, page load, and so on. HTML elements can be manipulated by using JavaScript. The browser information of a Web site visitor can be collected by using JavaScript.
15 of 590
Concepts
Session
1
Introduction to the Web
1.9 jQuery
jQuery is a JavaScript library which is supported on multiple browsers. It simplifies the designing of client-side scripting on HTML pages. The jQuery library is based on modular approach that allows the creation of powerful and dynamic Web applications. The use of jQuery on HTML pages enable developers to abstract the low-level interaction code with pre-defined library developed on top of the JavaScript. This also helps to keep the client-side script short and concise. Some of the features of jQuery library are as follows: 1. 2. 3. 4. Easier to understand syntax that helps to navigate the document Event handling Advanced effects and animation Developing AJAX-based Web applications
applications.
jQuery is a preferred library used by developers, as it is easy to understand than JavaScript. Also, the features of jQuery enable the development of rich Web applications in a shorter period.
Concepts
16 of 590
Session
1
Introduction to the Web HyperMark MarkHyper
2.
Which of the following statements about evolution of Web and dynamic Web sites are true? (A) (B) (C) (D) (E) A Web server is a computer that allows you to make Web pages available on the Internet. MAN is a computer network that covers a small area such as office or school. HTTP is a protocol used for requesting Web pages over the Internet. A Web browser is a software that processes user requests and responds with the requested page to the Web server. A dynamic Web page is a Web page that can be created using CSS and JavaScript.
3.
Which of the following is a new tag in HTML5? (A) Head (B) Header (C) (D) Body Title
4.
Which of the following is a rule-based language? (A) CSS (B) jQuery (C) (D) JavaScript Geolocation
5.
jQuery is a JavaScript library which is supported on _____ browsers. (A) Single (B) Multiple (C) (D) Dual Non-individual
17 of 590
Concepts
Session
1
Introduction to the Web
1.11.1 Answers
1. 2. 3. 4. 5. A A, C, E B A B
Concepts
18 of 590
Session
1
Introduction to the Web
Summary
HTML5 is cooperative project between the World Wide Web Consortium (W3C) and the Web Hypertext Application Technology Working Group (WHATWG). The new features of HTML5 would include tags such as <canvas>, <article>, <nav>, <header>, <footer>, <section>, <audio>, <video>, and so on. Some of the technologies used for creating dynamic Web sites are JavaScript, CSS, XHTML, and DHTML. A Cascading Style Sheet (CSS) is a rule-based language, which specifies the formatting instructions for the content specified in an HTML page. JavaScript is a scripting language that allows you to build dynamic Web pages by ensuring maximum user interactivity. jQuery is a JavaScript library which is supported on multiple browsers. It simplifies the designing of client-side scripting on HTML pages. The major browsers, such as Chrome, Firefox, Opera, Safari, Internet Explorer, and so on, are trying to add the new HTML5 features to the latest versions of the browsers.
19 of 590
Concepts
Session
1
Introduction to the Web
Try it Yourself
1. 2. 3. View the Web site of Aptech Global Leaning Solutions (www.aptech-worldwide.com). Identify the header and footer on the Web site. Create a layout of the basic structure of the body of the Web site.
Concepts
20 of 590
Session
1
Introduction to the Web (Workshop)
Note - Please refer to the respective lab deliverable for demonstrations and guided
simulations.
Labs
22 of 590
Introduction to HTML5
This session explains the basic tags that are present in HTML5. This session also lists the different data types, attributes, and entities of HTML5. Finally, the session explains the advantages of using HTML5 in mobile application development. In this Session, you will learn to:
Explain the elements constituting an HTML tag Describe DOCTYPE declarations Explain the basic tags in HTML List the different data types, attributes, and entities of HTML5 Describe container and standalone tags Explain the role of HTML5 in mobile devices
Session
2
Introduction to HTML5
2.1 Introduction
All elements in HTML5 are organized using tags. The basic tags in HTML5 include html, head, title, meta, link, script, and body. The DOCTYPE must be provided before inserting the basic tags in HTML5. There are different data types, attributes, and entities that can be applied to the tags present in HTML5. All the tags are either classified into container tags or standalone tags. This classification is based on the use of the end tag for a certain HTML element. HTML5 is also the preferred language for mobile application development because of its various benefits. This session explains the basic tags that are present in HTML5. This session also lists the different data types, attributes, and entities of HTML5. Finally, the session explains the advantages of using HTML5 in mobile application development.
2.2 Elements
An element organizes the content in a Web page hierarchically, which forms the basic HTML structure. It consists of tags, attributes, and content. Tags denote the start and end of an HTML element. A start tag includes an opening angular bracket (<) followed by the element name, zero or more space separated attributes, and a closing angular bracket (>). Attributes are name/value pairs that describe the element and content format. An end tag is written exactly as the start tag, but the forward slash (/) precedes the element name. Figure 2.1 shows an element in HTML tag.
Concepts
24 of 590
Session
2
Introduction to HTML5
2.3 Doctype
The DOCTYPE element informs the browser the HTML version number of your document. It is the first declaration in the HTML5 document before any other HTML code is written. By using a DOCTYPE, the browser is able to be more precise in the way it interprets and renders your pages. It is highly recommended to use a DOCTYPE at the beginning of all HTML documents. The new HTML5 DOCTYPE declaration is as follows:
<!DOCTYPE html>
Not only is this syntax valid for the DOCTYPE for HTML5, but it is also the DOCTYPE for all future versions of HTML. This DOCTYPE is compatible even with the older browsers. The following example shows the use of the new document type specification.
Example: <!DOCTYPE html>
The HTML element is the root element that marks the beginning of an HTML document. It contains the start and end tag in the form of <HTML> and </HTML> respectively. It is the largest container element as it contains various other elements.
HEAD
25 of 590
Concepts
The HEAD element provides information about the Web page such as keywords and language used, which is not displayed on the Web page. Keywords are important terms existing in a Web page used by the search engines to identify the Web page with respect to the search criterion.
Session
2
Introduction to HTML5
TITLE
The TITLE element allows you to specify the title of the Web page under the <TITLE> and </TITLE> tags. The title is displayed on the Title bar of the Web browser. The TITLE element is included within the HEAD element.
META
The meta tag is used for displaying information about the data. In HTML5, the content meta tag which was used for specifying the charset or character encoding has been simplified. The new <meta> tag is as follows:
<meta charset=utf-8 />
UTF-8 is the most commonly used character coding that supports many alphabets. UTF-8 is also being promoted as the new standard. There are several other attributes associated with the meta tag that can be used to declare general information about the page. This information is not displayed in the browser. Meta tags provide search engines, browsers, and Web services the information that is required to preview or acquire a summary of the relevant data of your document. In HTML5, it is not very important to self-close tags with a slash at the end. Though self-enclosing is recommended for compatibility reasons.
LINK
The <link> tag is used to define the association between a document and an external resource. It is used to link stylesheets. Its type attribute is used to specify the type of link such as text/css which points out to a stylesheet.
<link type=text/css rel=stylesheet href=first.css>
The type attribute is not included in HTML5. The reason is that CSS has been declared as the default and standard style for HTML5. So, the new link is as follows:
<link rel=stylesheet href=first.css> SCRIPT
Concepts
With HTML5, JavaScript is now the standard and default scripting language. Hence, you can remove the type attribute from the script tags too. The new script tag is as follows:
<script src=first.js></script>
26 of 590
Session
Example:
2
Introduction to HTML5
The BODY element enables you to add content on the Web page specified under the <BODY> and </BODY> tags. Content can include text, hyperlinks, and images. You can display the content using various formatting options such as alignment, color, and background. Figure 2.2 shows the basic HTML elements.
27 of 590
Concepts
Session
2
Introduction to HTML5 The important basic HTML data types are as follows:
Text Strings
Specifies the spacing among HTML elements. Length values can be in Pixels, Length, or MultiLength. Pixels refer to the smallest dot on the screen. Length is specified as a percentage value of Pixels or available space on the screen. MultiLength can be specified as Pixels or percentage.
Content Types
Specifies the type of content to be displayed on a Web page. Examples of content types include text/html for displaying text using HTML format, image/gif for displaying image of a .gif format, and video/mpg for displaying a video file of .mpg format. Figure 2.3 shows the different data types.
Concepts
28 of 590
Session
2
Introduction to HTML5
2.6 Attributes
HTML attributes helps to provide some meaning and context to the elements. Some of the global attributes used in HTML5 elements are as follows:
class Specifies classnames for an element. contextmenu Specifies the context menu for an element. dir Specifies the direction of the text present for the content. draggable Specifies the draggable function of an element. dropzone Specifies whether the data when dragged is copied, moved, or linked,
when dropped.
style Specifies the inline CSS style for an element. title Specifies additional information about the element.
OR
&#entity_number;
Output
< > &
Description
non-breaking space less than greater than ampersand euro copyright
Entity Name
< > & € ©
Entity Number
  < > & € ©
29 of 590
Concepts
Session
2
Introduction to HTML5
Concepts
30 of 590
Session
2
Introduction to HTML5
HTML5 is compatible with most operating system platforms. The mobile applications developed on HTML5 can run on browsers of Android, iOS, Blackberry, Windows Phone, and other mobile operating systems. The development cost for creating applications in HTML5 is low. Applications based on location and maps will have greater support in HTML5. The plan is to support such applications on browsers, hence making them platform independent. Third-party programs are not required in HTML5. Hence, media functions such as audio and video have better functionality and improved support in HTML5.
31 of 590
Concepts
Session
2
Introduction to HTML5
2.
Which of the following DOCTYPE is used in HTML5? (A) HTML (B) Standalone (C) (D) Emphasis Formatted
3.
What does URI stand for? (A) Uniform Resource Informer (B) Uniform Resource Identifier (C) (D) Uniform Reply Identifier Uniform Recourse Information
4.
Which of the following attribute in HTML5 specifies the text direction? (A) class (B) contextmenu (C) (D) dir style
5.
Which of the following is the mobile-based operating system developed by Apple? (A) Symbian (B) iOS (C) (D) Windows 7 Android
Concepts
32 of 590
Session
2
Introduction to HTML5 A A B C B
2.10.1 Answers
1. 2. 3. 4. 5.
33 of 590
Concepts
Session
2
Introduction to HTML5
Summary
An element organizes the content in a Web page hierarchically, which forms the basic HTML structure. The DOCTYPE element tells the browser the type of your document. A data type specifies the type of value assigned to the attributes and the type of content that is to be displayed on the Web page. Entities are special characters that are reserved in HTML. A container element includes the start tag, contents, sub-elements, and the end tag. A standalone element consists of the start tag and attributes followed by the end tag as /> without any content. HTML5 provides features such as drag-and-drop functionality, video embedding in an application, and even offline capabilities for mobile devices.
Concepts
34 of 590
Session
2
Introduction to HTML5
Try it Yourself
1. Samantha wants to create a Web site for her new Orchestra Group named We Five. She wants to design the Web page that will allow the search engine to get the required information. In order for the search engine to get the required information, the page should have the following details: a. b. Doctype State the type of Doctype in the tag. HTML i. ii. Head Title Provide the name of the orchestra group in the tag.
iii. Meta Provide keywords that would be applicable to the orchestra group Web site. c. Body Provide a small introduction about the orchestra group in the body section.
35 of 590
Concepts
Session
2
Introduction to HTML5 (Workshop)
Note - Please refer to the respective lab deliverable for demonstrations and guided
simulations.
Labs
38 of 590
Session
3
Formatting Text Using Tags
3.1 Introduction
The text content of the Web page, form an important part of a Web site. This text content must not only be informative but also attractive. It must be easy to read and must have short and crisp sentences for easy understanding of the Web user. To attract the attention of the user, headings must be appropriately provided. Also, text formatting options such as bold, italics, subscript, superscript, and so on must be applied on the text. Bullets can be also used to list the text in a systematic manner. The background color and background image of a Web page can be specified using HTML.
3.2 Headings
The heading elements define headings for contents such as text and images. They specify a hierarchical structure of a Web page by grouping the contents into different headings. HTML defines six levels of heading that ranges from H1 to H6. The H1 element specifies the top-level heading, which is displayed with the largest size. The H6 element specifies the lowest-level heading, which is displayed with the smallest size. Code Snippet 1 demonstrates how to specify the six levels of heading in an HTML page.
Code Snippet 1: <!DOCTYPE html> <html> <head> <title>Headings</title> </head> <body> <h1>H1 Heading</h1> <h2>H2 Heading</h2> <h3>H3 Heading</h3> <h4>H4 Heading</h4> <h5>H5 Heading</h5> <h6>H6 Heading</h6> </body>
Concepts
</html>
The heading under the H1 tags will be displayed with the largest size. Each subsequent heading will be displayed in a size lower than its previous heading.
40 of 590
Session
3
Formatting Text Using Tags
The heading under the H6 tags will be displayed with the lowest size. Figure 3.1 shows the different types of headings.
3.2.1 HGROUP
The <hgroup> element is a new element defined in HTML5. It is used to group titles and their subtitles. The element is used to group a set of h1h6 elements. These are used for headings that have multiple levels that can include subheadings, alternative titles, taglines, and so on. The main advantage of using the <hgroup> tag is to create a document outline. Code Snippet 2 shows the use of the <hgroup> tag.
Code Snippet 2: <hgroup> <h1>Title of Post One </h1> <h2>Subtitle of Post One </h2> </hgroup>
3.3 Formatting
The content format determines how the content will appear in the browser. For example, when you visit a Web site, some text appears in a specific format such as bold or underlined. This means that the formatted content makes an HTML page look readable and presentable. In HTML, formatting is applied to the text by using formatting elements, which are container elements.
41 of 590
Concepts
Session
3
Formatting Text Using Tags The commonly used HTML formatting elements are as follows:
B
The B element displays the text in bold. The text that needs to be displayed in bold is enclosed between <b> and </b> tags.
I
The I element displays the text in italic. The text that needs to be displayed in italic is enclosed between <i> and </i> tags.
SMALL
The SMALL element makes the text appear smaller in a browser. The text that needs to be displayed smaller is enclosed between <small> and </small> tags.
U
The U element applies an underline to the text. The text that needs to be underlined is enclosed between <u> and </u> tags. Code Snippet 3 demonstrates the use of the basic formatting elements.
Code Snippet 3: <!DOCTYPE html> <html> <head> <title>Formats</title> </head> <body> <h2>Using HTML Formatting Elements</h2><br> <b>This text is displayed in bold.</b><br> <i>This text is displayed in italic.</i><br> <u>This text is underlined.</u><br> <small>This text is displayed smaller.</small> </body> </html>
Concepts
42 of 590
Session
3
Formatting Text Using Tags
Figure 3.2: Basic Text Formats You might want to display some text or characters above or below the baseline of its adjacent text. Further, you might want to strike through some text to indicate that it is deleted. Therefore, HTML provides you with some more formatting elements. These formatting elements are as follows:
DEL
The DEL element encloses text, which has been deleted from the document. The text to be deleted is placed in the <del> and </del> tags.
INS
The INS element encloses text, which has been inserted in the document. The text to be inserted is placed in the <ins> and </ins> tags. The INS element can be used with DEL element to inform the user about the deleted text, which is replaced by the new text.
STRONG
The STRONG element emphasizes the text as compared to its surrounding text. The text to be emphasized is placed in the <strong> and </strong> tags.
SUB
The SUB element displays the text as subscript. The text to be displayed as subscript is enclosed in <sub> and </sub> tags.
43 of 590
Concepts
Session
3
Formatting Text Using Tags
SUP
The SUP element displays the text as superscript. The text to be displayed as superscript is enclosed in <sup> and </sup> tags. Code Snippet 4 demonstrates the use of DEL, INS, STRONG, SUB, and SUP elements.
Code Snippet 4: <!DOCTYPE html> <html> <head> <title>Updating and Shifting Text</title> </head> <body> <h3>Updating, Emphasizing, and Shifting Text</h3> This is an example of <del>deleted</del> <ins>inserted </ins> text.<br/> This is an example of <strong>Strong</strong> text.<br/> This is an example of <sub>subscript</sub>text.<br/> This is an example of <sup>superscript</sup> text.<br/> </body> </html>
Concepts
Session
3
Formatting Text Using Tags
Note - The <font> tag present in HTML 4 has been removed in HTML5. To change the font
size, style, color, and so on, the style attribute must be used in CSS3. This will be covered in later sessions.
Tag
<em> <dfn> <code> <samp> <cite>
Description
Used for emphasized text Used for a definition term Used for a computer code Used for sample output from a computer program Used for a citation Table 3.1: Predefined Tags
</blockquote>
45 of 590
Concepts
When one door closes, another opens; but we often look so long and so regretfully upon the closed door that we do not see the one which has opened for us. -Alexander Graham Bell
Session
3
Formatting Text Using Tags
3.5 Lists
A list is a collection of items, which might be organized in a sequential or unsequential manner. You can use a list to display related items that belong to a particular category. For example, to display the types of computers, such as mainframe, microcomputer, and laptops, you would organize these items one below the other under the Types of Computers category. Similarly, HTML allows you to display related items in a list on a Web page. A list in HTML can contain paragraphs, line breaks, images, links, and other lists. The items within a list are displayed on a Web page one below the other using bullets. HTML supports three types of lists. These are as follows: Ordered Unordered Definition
Concepts
46 of 590
Session
3
Formatting Text Using Tags
HTML provides two elements for creating an ordered list. These are as follows: OL: Creates an ordered list. LI: Specifies an item and it is a sub-element of the OL element.
Code Snippet 6 demonstrates the use of OL and LI tags to display weekdays as an ordered list.
Code Snippet 6: <!DOCTYPE html> <html> <head> <title>Days in a Week</title> </head> <body> <h2>Days in a Week:</h2> <ol> <li>Sunday</li> <li>Monday</li> <li>Tuesday</li> <li>Wednesday</li> <li>Thursday</li> <li>Friday</li> <li>Saturday</li> </ol> </body> </html>
47 of 590
Concepts
Session
3
Formatting Text Using Tags Figure 3.5 shows an example of an ordered list.
Figure 3.5: Ordered List Different numbering styles, such as roman numerals or alphabetic bullets, can be applied to an ordered list. Table 3.2 shows the different numbering styles that can be specified in an ordered list.
decimal
Propertys Value
Example
1, 2, 3, ... a, b, c, ... A, B, C, ... i, ii, iii, ... I, II, III, ...
Table 3.2: Different Numbering Styles The list-style-type property is used to specify a numbering style for the ordered list. It is the property of the style attribute, which is specified within the <ol> tag.
Concepts
48 of 590
Session
3
Formatting Text Using Tags
Code Snippet 7 demonstrates the use of list-style-type property for adding a numbering style to a numbered list.
Code Snippet 7: <ol style=list-style-type:lower-roman> <li>Sunday</li> <li>Monday</li> <li>Tuesday</li> <li>Wednesday</li> <li>Thursday</li> <li>Friday</li> <li>Saturday</li> </ol>
The list-style-type property of the style attribute in the code is set to lower-roman. The property and its value are separated by a colon. This means that the days of the week will be displayed sequentially by applying the lower-cased Roman numbers as bullets. Figure 3.6 shows the lower-roman style.
49 of 590
Concepts
Session
3
Formatting Text Using Tags For example, to list the features of a product, you would create an unordered list. Each item in an unordered list is displayed using symbolic bullets such as circles and squares. These bullets are similar to the bullets provided by Microsoft Office Word. HTML provides the UL element to create an unordered list. Code Snippet 8 demonstrates how to display the features of a product as an unordered list.
Code Snippet 8: <!DOCTYPE html> <html> <head> <title>Features of EasyPad</title> </head> <body> <h2>Features of EasyPad</h2> <ul> <li>Opens many files at a time</li> <li>Unlimited undo and redo</li> <li>Reads and writes both Windows and Unix files</li> </ul> </body> </html>
Concepts
50 of 590
Session
3
Formatting Text Using Tags
Figure 3.7: Unordered List The UL element contains the <ul> tag and multiple li sub-elements. The <ul> tag marks the beginning of the unordered list. Each of the li sub-elements starts with the <li> tag followed by a feature of the EasyPad product. Each feature will be displayed with the default symbolic bullet, which is a small black disc. The list-style-type property specifies the type of bullet to be applied to an unordered list. There are three types of bullets defined for the unordered lists in HTML. These bullet types are namely, disc, square, and circle. The default value is disc, which is applied to the unordered list, even if the list-style-type property is not specified.
51 of 590
Concepts
Session
3
Formatting Text Using Tags Code Snippet 9 demonstrates how to apply the square bullet to an unordered list.
Code Snippet 9: <!DOCTYPE html> <html> <head> <title>Wild Animals</title> </head> <body> <h2>Wild Animals</h2> <ul style=list-style-type:square> <li>Lion</li> <li>Tiger</li> <li>Leopard</li> <li>Wolf</li> </ul> </body> </html>
The list-style-type property of the style attribute is set to square. This means that the unordered list of wild animals will be displayed using the square bullet as shown in figure 3.8.
Concepts
Session
3
Formatting Text Using Tags
A definition list refers to a collection of terms with their corresponding descriptions. For example, you can display a glossary on a Web page by creating a definition list, which will contain the terms and their descriptions. A definition list appears with the term indented on the left followed by the description on the right or on the next line. By default, the description text appears on the next line and is aligned with respect to the term. You can specify a single line or multiple lines of description for each term. HTML provides three elements to create a definition list. These elements are as follows:
DL
Is a container element that consists of the DT and DD sub-elements. It specifies that a definition list will be created using these elements.
DT
Specifies the definition or description of the term. Consider a scenario, where you want to create a Web page that will display the types of nouns with their descriptions. To do this, you must create a definition list. The steps to create a definition list are as follows: 1. 2. 3. Specify the DL element to indicate that you want to create a definition list. Use the DT element to specify the term such as Common Noun. Use the DD element to specify the description of the term.
53 of 590
Concepts
Session
3
Formatting Text Using Tags Code Snippet 10 demonstrates the way to create a definition list.
Code Snippet 10: <!DOCTYPE html> <html> <head> <title>Types of Nouns</title> </head> <body> <h2>Types of Nouns</h2> <dl> <dt><b>Common Noun:</b></dt> <dd>It is a name of an object in general, such as pencil, pen, paper, and so on.</dd> <dt><b>Proper Noun:</b></dt> <dd>It is the unique name of a person or a place. </dd> </dl> </body> </html>
Concepts
54 of 590
Session
3
Formatting Text Using Tags
where, color_name - Specifies the background color with a color name (such as red) hex_number - Specifies the background color with a hex code (such as #ff0000)
55 of 590
Concepts
rgb_number - Specifies the background color with an rgb code (such as rgb(255,0,0))
Session
3
Formatting Text Using Tags Code Snippet 11 demonstrates how to specify a background color for an HTML document.
Code Snippet 11: <html> <body bgcolor=#E6E6FA>
<h1>Hello world!</h1>
</html>
Another way to specify a background color for a Web page is by using the style=background-color: color attribute. This attribute must be added to the <body> tag. An example for applying a background color using the style attribute is as follows:
Example: <body style=background-color: yellow>
The color name yellow can also be replaced by the hex code or the rgb code. The default text color of the page is specified as the foreground color. The foreground color can be specified by using the style=color: color attribute. An example for applying a background and foreground color using the style attribute is as follows:
Example: <body style=background-color: navy; color: yellow>
Concepts
</html>
56 of 590
Session
3
Formatting Text Using Tags
Which of the following formatting element emphasizes the text as compared to its surrounding text? (A) B (B) Strong (C) (D) I U
2.
Which of the following tag is used to specify a definition term? (A) <em> (B)
<code>
(C) (D)
<dfn> <blockquote>
3.
Which of the following are the two elements used for creating an ordered list? (A) OL (B) UL (C) (D) LI DF
4.
The ___________ tag is used to apply preformatted text content to a Web page. (A) <pre> (B)
<em>
(C) (D)
<dfn> <a>
5.
_____________ fonts are used for programming code scripts, instruction texts, and ASCII characters. (A) Spaced (B) Monospaced (C) (D) Hyperspaced
57 of 590
Concepts
Preformatted
Session
3
Formatting Text Using Tags
3.8.1 Answers
1. 2. 3. 4. 5. B B A, C A B
Concepts
58 of 590
Session
3
Formatting Text Using Tags
Summary
The heading elements define headings for contents such as text and images. The <hgroup> element is used to group titles and their subtitles. Monospaced fonts are used for programming code scripts, instruction texts, and ASCII characters. The <pre> tag is used to apply preformatted text content to a Web page. To define a long quotation or block quotation, the <blockquote> tag can be used. A list is a collection of items, which might be organized in a sequential or nonsequential manner. HTML supports three types of lists namely, ordered, unordered, and definition. HTML provides background properties that specify the background color and image for the Web pages.
59 of 590
Concepts
Session
3
Formatting Text Using Tags
Try it Yourself
1. Create a Web page and insert the content provided containing the same formatting style as shown.
Sample Content
A multi-tier enterprise application consists of two types of objects: application logic components and persistent data objects. Application logic components represent actions and define methods that perform common tasks such as calculating the order price, customer credit card billing, and so on. Session beans model the application logic components as they contain the logic to perform the application tasks. It is easy and simple to manage the business data present in large organizations as objects rather than as relational rows in a database. Business data when treated as objects are easy to handle and manage as they are compact in nature. Entities
Java 2 Standard Edition (J2SE) environment. The differences between an Entity
are
not
associated
with
only
EJBs
and
can
be
used
in
Entities have a client-visibility and a persistent identity that is distinct from their object reference. Each entity is distinct from the other because of their identities. Clients can use identities to pass the reference of an entity to other applications. However, this is not possible with Session beans. Entity bean cannot be accessed remotely, whereas Session beans can be accessed locally as well as remotely. Entitys lifetime is not dependent on the applications lifetime. Entity bean have a much longer lifetime than a clients session as it depends on how long the data is present in the database. Entities represent data in a storage that is permanent as well as fault-tolerant and hence, they are long lasting and can survive application server or database crash. This data can be reconstructed in the memory. Hence, it can be said that entity is an in-memory representation of persistent data that: Can be loaded from persistent store and its field populated with the stored data Can be modified in-memory to change the data values Can be saved and correspondingly database is updated
Concepts
2. 3.
Apply bold formatting for the required words as shown in the sample content. Apply an unordered bullet list to the text as shown in the sample content.
60 of 590
Session
3
Formatting Text Using Tags (Workshop)
Note - Please refer to the respective lab deliverable for demonstrations and guided
simulations.
Labs
62 of 590
Session
4
Creating Hyperlinks and Anchors
4.1 Introduction
A Web site is a collection of Web pages, which facilitate sharing information on the Internet. There should be some mechanism to allow the user to navigate through the Web pages of a Web site. It should also allow the user to view the Web pages of other Web sites, if required. These tasks can be achieved by creating hyperlinks in HTML.
4.2 Hyperlinks
A hyperlink is referred to as a link. It refers to linking to another Web page or to a section in the same Web page. The A (anchor) element is used to create a hyperlink. You can specify a text or an image as a hyperlink. When you move the mouse over such content, the cursor changes into a hand with its index finger pointing towards the content. This means that clicking them will take you to the respective link. To specify the linked page section or linked Web page, you must use the attributes of the A element. Table 4.1 lists the attributes of the A element.
href
Attribute
Description
Specifies the URL of the Web page to be linked or the value of the name attribute. Indicates the language of the destination URL. Specifies the section of the Web page, which is to be linked. Table 4.1: Attributes of the A Element
hreflang name
The basic syntax to provide a hyperlink is always the same. The <a> tag is used to provide a hyperlink. This contains the href= attribute that would contain the link to a URL or path of a Web page. An example of a href attribute code is as follows:
<a href= http://www.aptech-worldwide.com/>
The description and reference text that will serve as a hyperlink must be provided before closing the <a> tag by using </a>.
Concepts
64 of 590
Session
Example: <html> <head> </head> <body>
4
Creating Hyperlinks and Anchors
<a href=http://www.aptech-woldwide.com/> Click to view the Aptech Web site</a> </body> </html>
The target attribute of the A element specifies the location where the linked Web page will open when a link is clicked.
Session
4
Creating Hyperlinks and Anchors You can assign values to the target attribute. Table 4.2 lists some of the values of the target attribute.
_blank _self _top
Value
Description
Loads the target URL in a new blank window. Loads the target URL in the same window as that of the current Web page. Loads the target URL in the complete area of window. Table 4.2: Values of the target Attribute
Relative paths are links that are provided when the files of a Web page are in the same folder as the page displaying the link. The syntax of a relative path is as follows:
Syntax: <a href=aboutus_aboutaptechworldwide.html>Aptech Web site</a>
To link to the files present in the subfolder, you need to provide the path to the subfolder. For example, if the file aboutus_aboutaptechworldwide.html is in a subfolder named about-us then the syntax is as follows:
Syntax: <a href=about-us/aboutus_aboutaptechworldwide.html>Aptech Web site</a>
Files that are present in folders that are one level up can also be linked using a relative path. The syntax to link to a file one level up is as follows:
Syntax: <a href=../aboutus_aboutaptechworldwide.html>Aptech Web site </a>
Concepts
66 of 590
Session
4
Creating Hyperlinks and Anchors
To automatically add a subject line in the new e-mail message, the ?subject= attribute must be inserted after the e-mail address. Code Snippet 2 shows the way to add a subject line to a hyperlinked e-mail address.
Code Snippet 2: <a href=mailto:[email protected]?subject=E-mail to Customer Care>Customer Care</a>
67 of 590
Concepts
Session
4
Creating Hyperlinks and Anchors
(C) (D)
<b> <em>
2.
Which of the following value loads the target URL in the same window of the current Web page? (A) _blank (B)
_self
(C) (D)
_top _bottom
3.
Which of the following paths has links that contain the complete address to get to a Web page? (A) Absolute (B) Non-Absolute (C) (D) Relative Non-Relative
4.
To automatically add a subject line in the new e-mail message, the ________ attribute must be inserted after the e-mail address. (A) ?subject= (B)
?subjectline=
(C) (D)
5.
The ______ attribute of the A element specifies the location where the linked Web page will open when a link is clicked. (A) subject (C) (D)
target pageopen
Concepts
(B)
object
68 of 590
Session
4
Creating Hyperlinks and Anchors A B A A C
4.6.1 Answers
1. 2. 3. 4. 5.
69 of 590
Concepts
Session
4
Creating Hyperlinks and Anchors
Summary
A hyperlink is referred to as a link. It refers to linking to another Web page or to a section in the same Web page. The A (anchor) element is used to create a hyperlink. The target attribute of the A element specifies the location where the linked Web page will open when a link is clicked. Absolute paths are links that contain the complete address to get to a Web page. Relative paths are links that are provided when the files of a Web page are in the same folder as the page displaying the link. To add an e-mail to a hyperlink, the href= attribute must be followed by mailto:email address. Hyperlinks can also be used to link to files and documents such as zipped files (.zip), executable files (.exe), documents (.doc), PDF reader files (.pdf), and so on.
Concepts
70 of 590
Session
4
Creating Hyperlinks and Anchors
Try it Yourself
1. Solution Anywhere is an open source software development organization headquarters
at Chicago, USA. The company wants to make its presence felt worldwide by creating a Web site which will highlight the activities performed by the organization. The organization also provides all the software that are available as a freeware. You as a Web site developer for the organization have been asked to create the following four separate Web pages for the organization: a. b. c. d. Home About Us Downloads Contact Us
2. 3. 4.
Link all four Web pages to each other using hyperlinks on all four pages. In the Downloads page, provide a .EXE file along with a downloadable PDF or Document help file. In the Contact Us page, provide an e-mail address that is hyperlinked. This e-mail link must open a new e-mail with the Subject line as New E-mail.
71 of 590
Concepts
Woe to him who teaches men faster than they can learn
Session
4
Creating Hyperlinks and Anchors (Workshop)
Note - Please refer to the respective lab deliverable for demonstrations and guided
simulations.
Labs
74 of 590
Introduction to CSS3
This session explains the concept of CSS along with the CSS structure and rules. It also explains the different approaches that can be employed by the user for defining the styles and linking the stylesheets. In this Session, you will learn to:
Identify the new functions of CSS3 Explain the different types of selectors Explain nested tags Define Classes and IDs for applying styles Explain the process to apply styles to hyperlink
Session
5
Introduction to CSS3
5.1 Introduction
CSS is a style sheet language used for informing the browser how to present a document. It uses markup language for describing the presentation semantics of a document. In other words, an HTML document defines the content of the file whereas the CSS file defines how HTML elements are to be displayed.
CSS3 is divided into multiple documents called modules. Each of these modules have new capabilities or extends the features present in CSS2. Drafting of CSS3 started when publication of the original CSS2 recommendation was released. The first CSS3 drafts were released on June 1999. CSS3 extends variety of new ways to create an impact with any designs, with quite a few important changes. The CSS3 logo is displayed in figure 5.1.
Concepts
76 of 590
Session
5
Introduction to CSS3
5.2.1 Modules
Since CSS3 is available as modules and is still evolving, there are many modules having different stability and status. Out of the fifty modules published by the CSS working group, only three modules are released as recommendations and they are as follows: CSS Color Level 3 CSS Namespaces Selectors Level 3
The following modules are stable and in recommendation stage: Media Queries CSS style Attributes
The following modules are in testing phase and in recommendation stage: CSS Backgrounds and Borders Level 3 CSS Image Values and Replaced Content Level 3 CSS Marquee CSS Multi-column Layout CSS Speech CSS Mobile Profile 2.0 CSS TV Profile 1.0
The following modules are in refining phase and in working draft stage: CSS Transforms CSS Transitions CSS Values and Units Level 3 CSS Print Profile
77 of 590
Concepts
Session
5
Introduction to CSS3 The following modules are in revising phase and in working draft and recommendation stage: CSS Animations CSS Flexible Box Layout CSS Fonts Level 3 CSS Paged Media Level 3 CSS Text Level 3 CSS Basic User Interface Level 3 CSS Writing Modes Level 3 CSSOM View
The following modules are in exploring phase and in working draft stage: CSS Cascading and Inheritance Level 3 CSS Conditional Rules Level 3 CSS Grid Layout CSS Grid Template Layout CSS Line Grid CSS Lists Level 3 CSS Tables Level 3 Selectors Level 4 CSS Object Model
Concepts
The following modules are in rewriting phase and in working draft stage: CSS Line Layout Level 3 V 1.1 Aptech Limited
78 of 590
Session
CSS Ruby
5
Introduction to CSS3
The following modules are in abandoned phase and in working draft stage: Behavioral Extensions to CSS CSS Hyperlink Presentation
Figure 5.2: CSS Syntax You can have various combinations to specify rules for HTML elements. First, you can specify multiple property-value pairs for a selector, which are separated by a semicolon (;) within the declaration block. Second, you can specify multiple selectors for a single property by grouping the selectors. To group the selectors, the selectors are separated by commas followed by a declaration block of properties and values. Third, you can specify properties for multiple selectors. Here, the comma-separated selectors are followed with multiple property-value pairs.
79 of 590
Concepts
Session
5
Introduction to CSS3 Figure 5.3 shows multiple properties and selectors.
Concepts
80 of 590
Session
5
Introduction to CSS3
Relative Length
em ex px
Description
Specifies the font size (height) of a particular font. The em unit is relative to the value of the font-size property of the selector. Specifies the x-height of a particular font. The x-height value is approximately half the font size or the height of the lowercase letter x. Specifies the size in pixels, which is relative to the screen of the device.
Table 5.1: Relative Length Units Figure 5.4 shows relative lengths.
81 of 590
Concepts
Session
5
Introduction to CSS3
Absolute: Absolute lengths are specified when the Web page designer is aware of
the physical properties of the output device. These are specific and fixed values. Table 5.2 lists the absolute lengths.
in cm mm pt pc
Absolute Length
Description
Specifies the size in inches, where 1 inch = 2.54 centimeters. Specifies the size in centimeters. Specifies the size in millimeters. Specifies the size in points, where 1 point = 1/72th of an inch. Specifies the size in picas, where 1 pica = 12 points. Table 5.2: Absolute Lengths
Concepts
82 of 590
Session
5
Introduction to CSS3
Figure 5.6: Use of Percentage in Defining the Style In the figure, the CSS code specifies the styles for the H1 element. The font-size property is set to a value of 120%. This means that the size of the header will appear 20% greater than its current size. The line-height property is set to the value 200%. This means that the height of the line will be double the value of the font-size property.
83 of 590
Concepts
Session
5
Introduction to CSS3 Figure 5.7 shows an internal style.
Figure 5.7: Internal Style In figure 5.7, inside the <style> tag, CSS styles for <h1>, <h2>, and <footer> tags are defined. This can be re-used in the same Web page multiple times.
Concepts
84 of 590
Session
5
Introduction to CSS3
Figure 5.8: External CSS Code Explanation for the code shown in figure 5.8 is as follows:
background-color: gray;
Specifies the font style of the textual content as italic. Figure 5.9 shows an example of HTML code using an external CSS style sheet.
Figure 5.9: HTML Code using an External CSS Style Sheet Explanation for the code shown in figure 5.9 is as follows:
<LINK
Specifies that the HTML page is linked to another object. Specifies that the linked object is a style sheet.
type=text/css href=body.css/>
85 of 590
Concepts
rel=stylesheet
Session
5
Introduction to CSS3
Note - An inline style sheet holds the highest priority, which means that the style specified
for the same element in any other style sheet will be ignored. The browser-specific styles are applied to a Web page when there are no styles specified for a Web page.
5.4 Selectors
Selectors refer to the HTML elements with the styles the users want to apply to them. The three different types of CSS selectors are as follows: Type selector Class selector ID selector Universal selector
Concepts
86 of 590
Session
5
Introduction to CSS3
A class selector matches elements, whose class attribute is set in an HTML page and applies styles to the content of all those elements. For example, if there are span and div elements in a Web page with their class attributes set, the style specified for the class selector will be applied to both the elements. A class selector starts with a period followed by the value of the class attribute. Figure 5.11 shows an example of class selector.
Figure 5.11: Class Selector In figure 5.11, the style will be applied to both the places where the values of the class attribute have been set to planets. If the style is required to be applied to only the <div> element then class element would be used as shown in Code Snippet 2.
div.planets
{ font-size: 1.5em; }
87 of 590
Concepts
Code Snippet 2:
Session
5
Introduction to CSS3
5.4.3 ID Selector
An ID selector matches an element whose id attribute is set in an HTML page and applies styles to the content of that element. The ID selector specifies styles for an element whose id attribute is set to a unique value. An ID selector starts with the hash symbol (#) followed by the id attributes value and the declaration block. Figure 5.12 shows an example of ID selector.
88 of 590
Session
5
Introduction to CSS3
The highest priority is given to the external style sheet defined by an author. The next priority is of the reader, which can be a software that reads the content (screen reader software), and the last priority is of the browser. Sort the declarations by the priority of a selector, where the ID selector has the highest priority. Sort the declaration according to the specified order.
5.4.6 Comments
A comment refers to the descriptive text that allows a Web page designer to provide information about the CSS code. Comments make the program more readable and help the designer to explain the styles specified for elements. This is helpful when other Web designers analyze the CSS code. The browser can identify comments as they are marked with special characters, which are /* and */. When the browser encounters these symbols, the text within them are ignored and are not displayed in the browser. You can have single-line and multi-line comments in the CSS file.
89 of 590
Concepts
Session
5
Introduction to CSS3 Figure 5.14 shows an example using comments in a CSS code.
Concepts
{ color:green; }
90 of 590
Session
5
Introduction to CSS3
To reduce the code, developers can group selectors. Separate each selector with a comma. Code Snippet 5 displays the grouping of selectors.
Code Snippet 5: h1,h2,p { color:green; }
It is also possible to apply a style for a selector within a selector. Code Snippet 6 demonstrates the nesting of selectors.
Code Snippet 6: p { color:green; } .changed { background-color:red }
In the code, a style is specified for all the paragraphs and another style is specified for all elements whose class attribute has the value set to changed.
91 of 590
Concepts
Pseudo classes allow the users to apply different styles to the elements such as buttons, hyperlinks, and so on.
Session
5
Introduction to CSS3 Table 5.3 lists the different states of an element.
State
active hover link visited
Description
Defines a different style to an element that is activated by the user. Defines a different style to an element when the mouse pointer is moved over it. Defines a different style to an unvisited hyperlink. Defines a different style to the visited hyperlink. Table 5.3: Different States of an Element
Selector Name
Description
Is used for selecting all unvisited links Is used for selecting all visited links Is used for selecting the active link Is used for selecting links on mouse over Is used for selecting the input element which has focus Is used for selecting the first letter of every <p> element Is used for selecting the first line of every <p> element Is used for selecting every <p> elements that is the first child of its parent Is used for inserting content before every <p> element Is used for inserting content after every <p> element Is used for selecting every <p> element with a lang attribute value
Concepts
Session
5
Introduction to CSS3
Pseudo classes specify the styles to be applied on an element depending on its state. In CSS3, a selector can contain multiple pseudo-classes. These pseudo-classes should not be mutually exclusive. For example, the selectors a:visited:hover and a:link:hover are applicable, but a:link:visited is not applicable because :link and :visited are mutually exclusive selectors. The HTML code creates a form that accepts the customer details and provides a link that allows the user to view the bill as shown in figure 5.15.
Figure 5.15: HTML Code CSS code specifies the different styles for the visited links, unvisited links, and for the links when the mouse hovers over it.
93 of 590
Concepts
Session
5
Introduction to CSS3 Figure 5.16 shows a style sheet code.
Figure 5.16: Style Sheet Code Explanation for the code shown in figure 5.16 is as follows:
a:link { color: white; background-color: black; border: 2px solid white; }
Concepts
94 of 590
Session
a:hover {
5
Introduction to CSS3
Specifies the styles for a link when a mouse hovers over it. Figure 5.17 shows an example output of mouse hovered link.
Consider a scenario where you are designing a Web site that explains the important technical terms. While defining such terms, you might feel the need to emphasize more on the first letter by applying different styles. It becomes difficult if you try to apply styles only on the first letter of a line or paragraph. This can be achieved by using the pseudo elements. Pseudo elements provide you with a flexibility to apply styles to a specific part of the content such as a first letter or first line. This allows you to control the appearance of that specific content without affecting the rest of the content.
Session
5
Introduction to CSS3 Figure 5.18 shows the purpose of pseudo elements.
Figure 5.18: Purpose of Pseudo Elements Pseudo element adds some special effects to HTML elements such as <p>, <body>, and so on.
Pseudo Elements
The :first-line and :first-letter pseudo elements allow you to apply styles to the first line and first letter respectively.
:first-line
The :first-line pseudo element allows you to apply styles to the first line. Figure 5.19 shows an HTML code where the :first-line pseudo element will be used.
Concepts
Figure 5.19::first-line Pseudo Element The Code Snippet 9 in the style sheet declares the style that will be applied to the first line in the paragraph.
96 of 590
Session
p:first-line {
5
Introduction to CSS3
Code Snippet 9:
Specifies the styles to be applied to the first line of the paragraph content.
:first-letter
The :first-letter pseudo element allows you to apply styles to the first letter. Figure 5.20 shows an example of the HTML code for the :first-letter pseudo element.
Figure 5.20::first-letter Pseudo Element Figure 5.21 shows CSS code for the :first-letter pseudo element.
Figure 5.21: CSS Code for the :first-letter Pseudo Element Explanation for the code shown in figure 5.21 is as follows:
p:first-letter
Specifies the styles to be applied on the first letter of the paragraph content.
97 of 590
Concepts
Session
5
Introduction to CSS3 Figure 5.22 shows the output of :first-letter pseudo element.
This selectors/pseudo classes represent the anchor element (specified using the HTML a tag) and its various states. There are two other ways to assign hyperlink styles. They are as follows: 1. 2. Div specific Link specific
Concepts
98 of 590
Session
5
Introduction to CSS3
99 of 590
Concepts
Session
5
Introduction to CSS3 Code snippet 11 displays the use of CSS and HTML file containing a hyperlink with the value of class set to navone.
Code Snippet 11: <!DOCTYPE html> <html lang=en> <head> <meta charset=utf-8> <style> .navone:link { } .navone:visited { } .navone:hover { text-decoration: none; } .navone:focus { text-decoration: none; color: #FFF; background: #06b; } .navone:active { text-decoration: underline; color: #FFF; color: #FFF; background: #000; text-decoration: none; color: #FFF; background: #06a; text-decoration: underline; color: #FFF; background: #008; font-size:30px;
Concepts
100 of 590
Session
} </style> </head> <body>
5
Introduction to CSS3
background: #06F;
This link will use the style rule class of navone even if it is placed inside a div that has div specific hyperlink style rules. Figure 5.23 shows output of a class specific hyperlink.
101 of 590
Concepts
Session
5
Introduction to CSS3
(D) It starts with a hash symbol followed by the value of the class attribute
2.
Absolute lengths are specified when the Web page designer is aware of the ______ of the output device. (A) Text properties (B) Physical properties (C) (D) Image properties Positioning properties
3.
Which of these options represent valid style sheets? (A) Vertical (B) Inline (C) (D) Horizontal Embedded
4.
Which of these options are valid selectors? (A) ID (B) Inline (C) (D) External Class
5.
Which of the following statements are valid for CSS? (A) Can specify multiple property-value pairs for a selector (B) (C) Can specify multiple property-value pairs for selector separated by a comma Can specify multiple selectors for a single property by grouping the selector
Concepts
102 of 590
Session
5
Introduction to CSS3 A, B B B, D A A, C
5.7.1 Answers
1. 2. 3. 4. 5.
103 of 590
Concepts
Session
5
Introduction to CSS3
Summary
CSS is a mechanism for adding style such as fonts, colors, and spacing to Web documents. CSS has multiple levels and profiles. The general syntax of CSS consists of three parts namely, selector, property, and value. Selectors refer to the HTML elements with the styles that are applied to them and they can be Type, Class, ID, or Universal selectors. A comment refers to the descriptive text that allows a Web page designer to provide information about the CSS code. Pseudo classes allow the users to apply different styles to the elements such as buttons, hyperlinks, and so on. Psuedo elements allow the developer to apply styles to a specific part of a content such as first letter or first line. A hyperlink style can be assigned either through DIV or through link class.
Concepts
104 of 590
Session
5
Introduction to CSS3
Try it Yourself
1. Joan OBrien works for a famous jewelry design company headquartered at Seattle, USA. The management of the company wants to increase the sale of the jewelry produced by reaching out to maximum number of clients spread across the globe. This could be achieved by creating a user friendly and attractive Web site for the company. Joan has been asked to develop the Web site and make the site attractive by applying different styles to the contents displayed at the Web site.
105 of 590
Concepts
Dont just learn the tricks of the trade, learn the trade
Session
5
Introduction to CSS3 (Workshop)
Note - Please refer to the respective lab deliverable for demonstrations and guided
simulations.
Labs
108 of 590
Session
6
Formatting Using Style Sheets
6.1 Introduction
Earlier Web designers had limitations in the presentation of text. <font> tags were used to change the color and typeface of the text. Sizing was still a concern and the designers used the pre-defined font sizes. Effects such as boldness and strike-through were possible only through basic forms of HTML tags. Even, applying different colors to borders and alignment of a paragraph was a concern. Since, Web page presentation has become an important aspect of Web designing, the stylesheets allow various styles for formatting texts, borders, or paragraphs.
Property
Description
It is used for specifying the color of the text. text-align It is used in specifying the horizontal alignment of text in an element. text-decoration It is used for specifying the decoration of the text in an element. text-indent It is used for specifying the indentation of first line of text in an element in length or %. text-transform It is used in specifying the casing of text in an element. word-spacing It is used for increasing or decreasing the space between words. Table 6.1: Different text Properties The font properties allow you to specify the font for the text. They allow you to change the different font attributes of the text such as font, size, and style of the text. The browser must support the font specified by the font properties. Otherwise, it will display the default font, which is dependent on the browser. Table 6.2 lists the different font properties.
font-family
Property
Description
It is used for specifying the font and can specify a generic family or a specific family name such as Serif or Times New Roman. It is used for specifying the size of the font and can have an absolute or relative value. It is used for specifying the style of the font. It is used for specifying whether the text should be displayed in small-caps. Table 6.2: Different font Properties
Concepts
font-size font-style
font-variant
110 of 590
Session
6
Formatting Using Style Sheets
The different text styles such as text-align, text-indent, and text-transform provide different values that allow specifying the alignment, indentation, and casing of text in an element. The text-align property allows the text to be centered, or left or right aligned, or justified. Table 6.3 lists the values of text-align property.
left
Property
Description
It is used for aligning the text to the left of the Web page. It is used for aligning the text to the right of the Web page. It is used for aligning the text in the middle of the Web page. It is used for justifying the text on both sides of the Web page. Table 6.3: Values of text-align Property
right
center
justify
As discussed the text-indent property is used for specifying the indentation of the text. Table 6.4 lists the values of text-indent property.
length %
Value
Description
It is used in specifying fixed indentation and the default value is 0. It is used in specifying an indentation as a percentage of the width of the parent element. The parent element is the element within which the selector element is defined. Table 6.4: Values of text-indent Property
The text-transform property is for changing the case of letters in a text. Table 6.5 lists the values of text-transform property.
none
Value
Description
It is used in specifying that the text will be displayed with the same casing as written within the element. It is used in specifying that the first letter of each word will be capitalized. It is used in specifying only uppercase letters. It is used in specifying only lowercase letters.
111 of 590
Concepts
Session
6
Formatting Using Style Sheets Figure 6.1 shows DIV element HTML code.
Figure 6.2 displays a CSS code that specifies the text styles for the DIV element. The text-align property is set to left, which will align the text towards the left. The text-indent property is set to 2em, which will indent the text with respect to the font size. The text-transform property is set to uppercase, which will display all the letters in uppercase.
Figure 6.2: CSS Code The text specified in the DIV element is aligned towards the left and all the letters are displayed in uppercase. Figure 6.3 shows output.
Concepts
112 of 590
Session
6
Formatting Using Style Sheets
The text-decoration and word-spacing properties provides different values that allow the user to specify the decoration and word spacing of text in an element. Table 6.6 lists the values assigned to the text-decoration property.
none
Value
Description
It is used for displaying normal text without any formatting. It is used for displaying a line under the text. It is used for displaying a line over the text. It is used for displaying a line through the text. It is used for flashing the text.
Table 6.6: Values Assigned to the text-decoration Property Table 6.7 lists the values assigned to the word-spacing property.
normal length
Value
Description
It is used in specifying normal spacing between words and it is the default value. It is used in specifying fixed space between words.
Table 6.7: Values Assigned to the word-spacing Property Figure 6.4 shows the header and paragraph HTML code.
113 of 590
Concepts
Session
6
Formatting Using Style Sheets Figure 6.5 displays a CSS code that specifies the text properties for the BODY and H3 elements. The word-spacing property is set to 2px for the BODY element. This will display each word by leaving a distance of two pixels. The text-decoration property is set to underline for the H3 element. This will underline the heading in the Web page.
Figure 6.5: CSS Code of text-decoration Property Figure 6.6 shows an output of heading tag with underline.
Figure 6.6: Output of Heading Tag with Underline In figure 6.6, the header is underlined and each word in the header and the paragraph is displayed by leaving a distance of two pixels between them.
Concepts
114 of 590
Session
6
Formatting Using Style Sheets
The span tag has different attributes; it supports JavaScript event attributes also. Table 6.8 lists different attributes and values used in <span> tag.
Attribute
class dir id lang style title xml:lang rtl
Value
classname
Description
It is used in specifying the text direction for the content in an element. It is used in specifying the text direction for the content in an element. It is used in specifying a unique id for an element. It is used in specifying a language code for the content in an element. It is used in specifying an inline style for an element. It is used in specifying extra information about an element. It is used in specifying a language code for the content in an element, in XHTML documents.
115 of 590
Concepts
Session
6
Formatting Using Style Sheets Code Snippet 4 demonstrates the use of the textindent property in the HTML file.
Code Snippet 4: <!DOCTYPE HTML> <html> <head> <title>Font Gallery</title> <style> p {text-indent: 150px} </style> </head> <body> <p>The font styles properties allow you to specify the font for the text. They allow
you to change the different font attributes of the text such as font, size, and style of the text. The browser must support the font specified by the font properties. Otherwise, it will display the default font, which is dependent on the browser.
</p> </body> </html>
Concepts
116 of 590
Session
6
Formatting Using Style Sheets
Code Snippet 5 demonstrates the inline style for <p> tag and an internal CSS code for padding property.
Code Snippet 5: Inline style <p style=padding: 20px> Internal CSS p {padding: 20px}
Code Snippet 6 demonstrates the use of the textindent property in the html file.
Code Snippet 6: <!DOCTYPE HTML> <html> <head> <title>Font Gallery</title> <style> p {padding: 20px } </style> </head> <body>
<p>The font styles properties allow you to specify the font for the text. They allow you to change the different font attributes of the text such as font, size, and style of the text. The browser must support the font specified by the font properties. Otherwise, it will display the default font, which is dependent on the browser.</p>
</body> </html>
117 of 590
Concepts
Session
6
Formatting Using Style Sheets
Margin - The margin property is used to add a specified amount of white space
Code Snippet 7 demonstrates the inline style for <p> tag and an internal CSS code for margin property.
Code Snippet 7: Inline style <p style=margin: 20px> Internal CSS p {margin: 20px}
border-style properties
Description
It sets an elements left border. It sets an elements right border. It sets an elements top border. It sets an elements bottom border.
border-right-style border-bottom-style
Concepts
118 of 590
Session
6
Formatting Using Style Sheets
Value
Description
It is used for specifying a dashed border. It is used for specifying a dotted border. It is used for specifying two borders. It is used for specifying a 3D grooved border. It is used for specifying a 3D inset border. It is used for specifying a 3D outset border. It is used for specifying a ridged border. It is used for specifying a solid border.
Table 6.10: Values of the border-style Properties Figure 6.10 shows an HTML code.
Figure 6.10: HTML Code Figure 6.11 shows CSS code of border style.
119 of 590
Concepts
Session
6
Formatting Using Style Sheets
border-right-style: groove;
Applies two borders at the bottom. Figure 6.12 shows the output of border-style properties.
To make the code concise CSS allows certain shorthand properties. With the help of these shorthand properties the length of the code is reduced. The shorthand property for setting the border is border-style. Figure 6.13 shows Sample HTML Code.
Figure 6.13: Sample HTML Code Figure 6.14 shows CSS code of shorthand border-style properties.
Concepts
120 of 590
Session
6
Formatting Using Style Sheets
Applies a 3D grooved border at the top, 3D inset border at the right, 3D outset border at the bottom, and dashed border at the left. Figure 6.15 shows output of shorthand border-style properties.
121 of 590
Concepts
Session
6
Formatting Using Style Sheets
Property
Description
It is used for specifying the color for the right border. It is used for specifying the color for the top border.
Table 6.11: Different border-color Properties The border-color property accepts different color values that determine the different shades of color to be applied to the borders. The table 6.12 lists the values of the different border-color properties.
color
Value
Description
It is used in specifying the color to be applied to the border by using either the RGB or hexadecimal value, or the color name itself. transparent It is used for specifying that the border is transparent. Table 6.12: Values of the Different border-color Properties Figure 6.16 shows an HTML code DIV with border-color properties.
Concepts
Session
6
Formatting Using Style Sheets
The shorthand property for setting the color of the border is border-color. Figure 6.18 shows an HTML code of a table with border-color properties.
123 of 590
Concepts
Session
6
Formatting Using Style Sheets Figure 6.19 shows CSS code for shorthand border-color.
Displays the top border in red, right border in blue, bottom border in green, and left border in yellow color.
Property
Description
It is used for specifying the width of the right border. It is used for specifying the width of the top border.
Table 6.13: Different border-width Properties The width of the border can be specified or altered by using the predefined values of the border width properties. The values of the border width properties specify the way the border will appear. Table 6.14 lists the values of the different border-width properties.
Concepts
Value
Description
It is used in specifying a medium border. It is used in accepting an explicit value that specifies the thickness of border. It is used for displaying a thick border. It is used in specifying a thin border.
Session
6
Formatting Using Style Sheets
Figure 6.20: HTML Code for border-width Properties Figure 6.21 shows the CSS code of border-width properties.
125 of 590
Concepts
Session
6
Formatting Using Style Sheets Figure 6.22 shows the output of border-width properties.
The shorthand property for setting the border is border-width. Figure 6.23 shows an HTML code using the shorthand border-width properties.
Figure 6.23: HTML Code for Shorthand border-width Properties Figure 6.24 shows the CSS code using the shorthand property, border-width.
Concepts
126 of 590
Session
6
Formatting Using Style Sheets
Specifies a top and bottom border as thick and right and left border as thin. Figure 6.25 shows output using shorthand code of border-width properties.
Property
Description
It is used in specifying the width, style, and color for the bottom border. It is used in specifying the width, style, and color for the left border. It is used in specifying the width, style, and color for the right border. It is used in specifying the width, style, and color for the top border. Table 6.15: Different Shorthand Border Properties
127 of 590
Concepts
Session
6
Formatting Using Style Sheets The values of the different border properties determine the type of effect to be applied to the borders. Figure 6.26 shows an HTML code for shorthand border properties.
Figure 6.26: HTML Code for Shorthand Border Properties Figure 6.27 shows a CSS code using different shorthand border properties.
Concepts
128 of 590
Session
6
Formatting Using Style Sheets
Displays a medium 3D inset left border in purple color. Figure 6.28 shows the output of border properties.
Figure 6.28: Output of Border Properties Figure 6.29 shows an HTML and CSS code of image border property.
129 of 590
Concepts
Session
6
Formatting Using Style Sheets
Explanation for the code: border: solid thin #FF0000;
Specifies that all the four borders must be solid in style, thin by width, and red in color. Figure 6.30 shows the output of Image Border Property.
Value
left right center justify
Description
Aligns the text to the left. Aligns the text to the right. Centers the text. Aligns text to both left and right margins by adding space between words (like in newspapers and magazines). Specifies that the value of the text-align property should be inherited from the parent element. Table 6.16: Values of text-align Property
Concepts
inherit
The text-align property applies only to block-level elements, such as paragraphs. Hence, text-align cannot change the alignment of a single word without changing the alignment of the entire line. V 1.1 Aptech Limited
130 of 590
Session
6
Formatting Using Style Sheets
For Western languages, which are read from left to right, the default value of text-align is left. The text aligns on the left margin and has a ragged right margin. Languages such as Hebrew and Arabic has default align to right since they are read from right to left.
Value
normal number length % inherit
Description
A normal line height. This is default. A number that will be multiplied with the current font size to set the line height. A fixed line height in px, pt, cm, and so on. A line height in percent of the current font size. Specifies that the value of the line-height property should be inherited from the parent element. Table 6.17: Values of line-height Property
131 of 590
Concepts
Session
6
Formatting Using Style Sheets
(C) (D)
line-height text-align
2.
The <span> tag _____ inline-elements in a document. (A) Right aligns (B) Left aligns (C) (D) Groups Deletes
3.
Which border property specifies the different properties in just one declaration? (A) border-bottom-color (B) border-bottom (C) (D) border-right-width border-left
4.
Match the value against the description: Value (A) medium (B) (C)
length thick
Description (1) (2) (3) (4) Specifies a thin border. Specifies a thick border. Accepts an explicit value that specifies the thickness of border. Specifies a medium border. This is the default value. (C) (D) a-4, b-1, c-2, d-3 a-4, b-3, c-2, d-1
(D) thin
Concepts
(A) a-2, b-1, c-3, d-4 (B) a-1, b-2, c-3, d-4
132 of 590
Session
5.
6
Formatting Using Style Sheets Property Description (1) Specifies the color for the right border. (2) Specifies the color for the top border. (3) Specifies the color for the bottom border.
border-bottomborder-leftborder-rightborder-top-
(4) Specifies the color for the left border. (C) (D) a-4, b-3, c-2, d-1 a-2, b-1, c-4, d-3
(A) a-3, b-4, c-1, d-2 (B) 6. a-1, b-2, c-3, d-4
What is the default text alignment for Hebrew and Arabic languages? (A) Left (B) Center (C) (D) Right Justify
133 of 590
Concepts
Session
6
Formatting Using Style Sheets
6.7.1 Answers
1. 2. 3. 4. 5. 6. A, B C B, D D A C
Concepts
134 of 590
Session
6
Formatting Using Style Sheets
Summary
The text styles specify and control the appearance of the text in a Web page. Indenting is the process of offsetting text from its normal position, either to the left or to the right. CSS border properties specify the style, color, and width of the border. The border-color property accepts different color values that determine the different shades of color to be applied to the borders. The values of the different border properties determine the type of effect to be applied to the borders. In CSS, the text-align property is used for horizontal alignment of text in an element. In CSS, the line-height property is used for vertical alignment of text in an element.
135 of 590
Concepts
Session
6
Formatting Using Style Sheets
Try it Yourself
1. Mathew wants to develop a Web page on his biblical findings. For writing major quotes of the bible verses he wants blue bordered text box with center alignment of the content and for its explanation he wants text box with red colored text that would be vertically center aligned. Use CSS code to create this Web page.
Concepts
136 of 590
Session
6
Formatting Using Style Sheets (Workshop)
Note - Please refer to the respective lab deliverable for demonstrations and guided
simulations.
Labs
138 of 590
Session -
This session explains formatting of graphics, insertion, sizing, and padding of graphics in Web pages. This session also explains CSS3 animation and how CSS3 can be used on Mobiles. In this Session, you will learn to:
Explain graphic formatting in Web pages Explain graphic insertion, sizing, and padding Explain CSS3 Animation Describe the use of CSS3 on mobile devices
Session
7
Displaying Graphics and CSS3 Animation
7.1 Introduction
After the release of HTML5 and CSS3 in the market, most of the Web designers are developing graphics based Web page. CSS3 has allowed the designers to style their Web pages graphically with ease. Currently, HTML5 applications provide amazing experiences with the use of new CSS3 animations. The introduction of mobile applications has allowed the users to expand their Web usage to mobile devices. CSS3 has introduced new features specifically for mobile devices.
a hardware or software. Color depth is defined by the number of bits per pixel (bpp) and it is also called as bit depth. Higher the color depth indicates higher range of colors used.
Compression/file size Graphic files are large, so images are compressed using
various techniques. Compression stores the original images in a reduced number of bytes using an algorithm. This image can be expanded back to the original size using a decompression algorithm. In some compression formats, images with less complexity results in smaller compressed file sizes. The two types of image file compression algorithms used are as follows:
Lossless compression In this algorithm, file size is reduced but preserves
a copy of the original uncompressed image. Lossless compression avoids accumulating stages of re-compression when editing images.
Concepts
uncompressed image is preserved. The image appears to be a copy of the original image but in actuality it is not a copy. Lossy compression achieves smaller file sizes when compared with lossless compression. Generally, lossy compression algorithms allow variable compression that comprises on image quality for file size.
Animation Some graphic format consists of a series of frames that are played one
after the other giving an impression of animation. Animated graphics are typically used on a Web page to attract visitors attention.
140 of 590
Session
7
Displaying Graphics and CSS3 Animation
that appears directly against the background color of the page. The background color of the Web page shows through the transparent portion of the image. In a transparent image, one and only one color can be hidden. If the color chosen to make transparent is same as the background of the inserted image, then an irregularly shaped image appears to float on the page. Figure 7.2 shows a transparent image.
141 of 590
Concepts
Session
7
Displaying Graphics and CSS3 Animation
JPEG - It uses a lossy compression which means that the image quality is lost in the
process of compressing the image. It is recommended that for continuous tone pictures such as photos JPEG should be used. Most JPEG editor allows the user to specify the amount of detail that the user is prepared to lose. If the quality is reduced, then the loss is visible; JPEG is about half the size of PNG.
PNG - It uses lossless compression, which means there is no loss of any image
detail. PNG was designed for transferring images on the Internet and not for professional-quality print graphics; therefore it does not support non-RGB color spaces such as CMYK. It supports high color and partial transparency using alpha channels.
Note - An alpha channel is a special type of channel used in graphics software for saving
selections.
GIF - It uses a lossless compression which means that there is no loss in quality
when the image is compressed. The uncompressed image stores its information in a linear fashion. Each line of pixels is read from left to right. An interlaced GIF file stores the lines of the image in a different order. Animated graphics are stored in gif format.
Compatibility and appearance are the keywords on the Web. The inserted images must be visible and undistorted when appearing on any recipients device. The Web designer can make assumptions that the Web site will open in a computer which will have minimum resolution of 800x600 pixel display capability. If a mobile based Web page needs to be created then the specifications will change.
Attributes
Description
Specifies the path of an image that is to be displayed. Specifies the height of an image. Specifies the width of an image.
Concepts
height width
142 of 590
Session
7
Displaying Graphics and CSS3 Animation
Code Snippet 1 demonstrates how to display an image in a Web page using the IMG element.
Code Snippet 1: <body> <img src=UNO.jpg width=225 height=151/> </body>
The code uses the src attribute of the IMG element to insert a JPEG image. The attribute specifies the name of the image and also indicates that the image is present in the same folder where the HTML file is saved. The width and height of the image is set to 225 and 151 pixels respectively by using the width and height attribute. A pixel refers to the smallest dot on the monitor screen. An image can also be stored in a subfolder of the folder containing the HTML file. In such cases, a reference to the image is made by using the sub folder name as shown in Code Snippet 2.
Code Snippet 2: <body> <img src=image_folder/UNO.jpg width=225 height=151/> </body>
To align the image the float style attribute can be used to specify the inline style for the element. This will force the image to be aligned to the left or right side of the screen and wrap the surrounding text around the image. Code Snippet 3 demonstrates the use of the float style.
Code Snippet 3: <body> <img src=image_folder/UNO.jpg style=float:left/> </body>
Table 7.2 lists the values of float property in the <img> tag.
Value
left right none inherit
Description Concepts
143 of 590
The element floats to the left. The element floats to the right. The element does not float and is the default value. The element specifies that the value of the float property should be inherited from the parent element. Table 7.2: Values of Float Property in <img> Tag
Session
7
Displaying Graphics and CSS3 Animation HTML5 introduced a new <figure> tag. The <figure> tag acts as a container containing the <img> tag. In other words, it is not a replacement for <img> tag, but acts as a container into which the <img> tag is placed. The <figure> tag specifies self-contained content, such as illustrations, diagrams, photos, code listings, and so on. While the content of the <figure> element is related to the main flow, its position is independent of the main flow, and if removed it does not affect the flow of the document. Code Snippet 4 demonstrates the use of <figure> tag.
Code Snippet 4: <figure> <img src=logo.gif style=float: left> width=304 height=228 /> </figure>
The main advantage of using <figure> tag is that it allows the user to use the <figcaption> tag along with it. The <figcaption> tag allows the user to add a caption to the image. The caption always appears along with the image even if the image floats in Web site layout. Code Snippet 5 demonstrates the use of <figcaption> tag.
Code Snippet 5: <figure> <img src=logo.gif> <figcaption>This diagram shows the logo of a product.</figcaption> </figure>
The <figure> tag can also assign styles and other attributes to the <figure> element using an external or internal style sheet. A single caption to a group of images can be added using the <figure> tag. Code Snippet 6 demonstrates how to assign a single caption to a group of images.
Code Snippet 6: <figure> <img src=flower1.jpg> <img src=flower2.jpg> <img src=flower3.jpg> <figcaption>The different types of flowers</figcaption> </figure>
Concepts
144 of 590
Session
7
Displaying Graphics and CSS3 Animation
Code Snippet 7 demonstrates CSS code for setting the image height and width property.
Code Snippet 7: p.ex { height:100px; width:100px; }
Table 7.3 lists different CSS properties and values of images. height Sets the height of an element
145 of 590
Concepts
Property
Description
Values
Session
7
Displaying Graphics and CSS3 Animation
Property
Description
Values
none length % inherit none length % inherit length % inherit length % inherit auto length % inherit
max-width
min-height
min-width
width
Table 7.3: Different CSS Properties and Values of Images Table 7.4 list the various values used with height and width properties.
Value
auto length % inherit
Description
The browser calculates the height and is the default value Defines the length in pixels (px) Defines the height of the containing block in percent format Specifies that the value of the property should be inherited from the parent element
Concepts
146 of 590
Session
Padding
7
Displaying Graphics and CSS3 Animation
The CSS padding property is used to specify the space between the element border and the element content. It is used to separate them from the surrounding element. The background color of the element affects the padding property. Using separate properties such as top, right, bottom, and left, different padding values can be specified and the padding can be changed separately. Table 7.5 list the various values used in padding property.
Value
length %
Description
This property specifies a fixed value for padding in pixels, pt, em, and so on This property specifies a value for padding in % of the containing element Table 7.5: Various Values used in Padding Property
Code Snippet 8 demonstrates the CSS code used for specifying different padding values for different sides.
Code Snippet 8: padding-top:10px; padding-bottom:10px; padding-right:15px; padding-left:15px;
In the code, the value for padding was set for all the sides. Instead of using different padding for different sides, users can use a shorthand property. A shorthand property is one where all the padding properties for the different sides are specified in one property. This will result in a shortened code. The shorthand property for all the padding properties is padding. The property can be used to specify one to four values for each of the side. Code Snippet 9 demonstrates the use of the shorthand property for padding.
Code Snippet 9: padding:25px 50px 75px 100px;
147 of 590
Concepts
Where top padding is 25px, right padding is 50px, bottom padding is 75px, and left padding is 100px.
Session
7
Displaying Graphics and CSS3 Animation Table 7.6 lists all CSS padding properties.
Property
padding padding-bottom padding-left padding-right padding-top
Description
The browser calculates the height and is the default value Defines the length in pixels (px) Defines the height of the containing block in percent format Specifies that the value of the property should be inherited from the parent element Sets the top padding of an element Table 7.6: CSS Padding Properties
body { margin:0; padding:40px 80px; background:#fff; font:70% Arial, Helvetica, sans-serif; color:#555; line-height:100%;
Concepts
Session
}
7
Displaying Graphics and CSS3 Animation
} p{
margin:1em 0;
a:hover{ color:#999; }
img{
list-style:none;
149 of 590
Concepts
Session
7
Displaying Graphics and CSS3 Animation
} ul#thumbs li{ float:left; margin-right:0px; border:1px solid #999; padding:2px; } ul#thumbs a{ display:block; float:left; width:125px; height:135px; line-height:50px; overflow:hidden; position:relative; z-index:1; } ul#thumbs a img{ float:left; position:absolute; top:0px; left:0px; } /* mouse over */ ul#thumbs a:hover{ overflow:visible; z-index:1000; border:none; }
Concepts
150 of 590
Session
7
Displaying Graphics and CSS3 Animation
ul#thumbs a:hover img{ border:1px solid #999; background:#fff; padding:2px; }
/* // mouse over */ /* clearing floats */ ul#thumbs:after, li#thumbs:after{ content:.; display:block; height:0; clear:both; visibility:hidden; } display:block; } min-height:1%; } height:1%; }
ul#thumbs, li#thumbs{
ul#thumbs, li#thumbs{
151 of 590
Concepts
Session
7
Displaying Graphics and CSS3 Animation
<ul id=thumbs> <li><a href=HTML5.png small.jpg/></a></li> </ul> </body> </html> target=_blank><img src=HTML5_
Concepts
152 of 590
Session
7
Displaying Graphics and CSS3 Animation
All the browsers do not support CSS3 transitions. Browsers that support CSS3 Transitions are as follows: Apple Safari 3.1 and later which requires the prefix webkitGoogle Chrome which requires the prefix webkitMozilla Firefox 3.7 alpha and later which requires the prefix mozOpera 10.5x and later which requires the prefix o-
At the moment Internet Explorer 9 does not support CSS3 Transitions. For performing CSS transitions the two required specifications are as follows: The CSS property that needs the effect The duration of the effect
Code Snippet 11 demonstrates the use of transition effect on the width property for 3 seconds.
Code Snippet 11: div { transition: width 3s; -moz-transition: width 3s; /* Firefox 4 */ -webkit-transition: width 3s; /* Safari and Chrome */ -o-transition: width 3s; /* Opera */ }
The effect will start when the specified CSS property changes value. The CSS property changes its value typically when a user moves a mouse over an element. Thus, the user can set the hover for <div> elements. Code Snippet 12 demonstrates the same.
Code Snippet 12: { width:200px; } div:hover
153 of 590
Concepts
Session
7
Displaying Graphics and CSS3 Animation Table 7.7 lists all the transition properties.
Property
transition
Description
Is a shorthand property and is used for setting the four transition properties into a single property transition-property Is used for specifying the name of the CSS property for which the transition value is set transition-duration Is used for defining the duration of the transition. Default value is 0 transition-timing-function Is used for describing how the speed during a transition will be calculated. Default value is ease transition-delay Is used for defining the start of the transition. Default value is 0 Table 7.7: Transition Properties Code Snippet 13 demonstrates an HTML and CSS code using all transition properties.
Code Snippet 13: <!DOCTYPE html> <html> <head> <style type=text/css> div { width:100px; height:100px; background:#000000; transition-property:width; transition-duration:2s; transition-timing-function:linear; transition-delay:1s; /* Firefox 4 */ -moz-transition-property:width;
Concepts
154 of 590
Session
7
Displaying Graphics and CSS3 Animation
-moz-transition-duration:2s; -moz-transition-timing-function:linear; -moz-transition-delay:1s; /* Safari and Chrome */ -webkit-transition-property:width; -webkit-transition-duration:2s; -webkit-transition-timing-function:linear; -webkit-transition-delay:1s; } div:hover { width:500px; } </style> </head> <body> <p><b>Note:</b> The example</p> <div></div> <p>Hover over the div element above, to see the transition effect.</ p> <p><b>Note:</b> The transition effect will wait 1 seconds before starting.</p> </body> </html>
155 of 590
Concepts
Session
7
Displaying Graphics and CSS3 Animation Figure 7.5 shows output of all transition properties.
Concepts
The three advantages to CSS3 animations over script-based animation techniques are as follows: 1. 2. Easy to use and anybody can create them without the knowledge of JavaScript. Executes well even under reasonable system load. As simple animations perform poorly in JavaScript, the rendering engine uses the frame-skipping techniques to allow smooth flow of animation. V 1.1 Aptech Limited
156 of 590
Session
3.
7
Displaying Graphics and CSS3 Animation
Allows the browser to control the animation sequence, optimize performance and efficiency by reducing the update frequency of animations executing in tabs that arent currently visible.
Property
Description
Is used for specifying the animation Is a shorthand property representing all the animation properties, except the animation-play-state property Is used for specifying the name of the @keyframes animation Is used for specifying the duration of an animation cycle in seconds or milliseconds. Default value is 0 Is used for describing the progress of animation over one cycle of its duration. Default value is ease Is used for specifying the start value of animation. Default value is 0 Is used for specifying the number of times an animation is played. Default value is 1 Is used for specifying whether or not the animation should play in reverse on alternate cycles. Default value is normal Is used for specifying the state of the animation, that is whether it is running or paused. Default value is running
animation-iterationcount animation-direction
animation-play-state
Table 7.8: @keyframes Rule and all the Animation Properties The syntax for @keyframes is as follows:
@keyframes myfirst { from {background: red;} to {background: yellow;} Syntax:
157 of 590
Concepts
Session
7
Displaying Graphics and CSS3 Animation
} @-moz-keyframes myfirst /* Firefox */ { from {background: red;} to {background: yellow;} } @-webkit-keyframes myfirst /* Safari and Chrome */ { from {background: red;} to {background: yellow;} }
The animation created using @keyframes must be bound with the selector for effective execution. For this, specify the name of the animation and the duration of the animation to the selector. Code Snippet 14 demonstrates HTML and CSS code of @keyframes rule and all the animation properties.
Code Snippet 14: <!DOCTYPE html> <html> <head> <style type=text/css> div { width:200px; height:200px; background:red; position:relative; border-radius:100px; animation-name:myfirst; animation-duration:4s; animation-timing-function:linear;
Concepts
158 of 590
Session
7
Displaying Graphics and CSS3 Animation
animation-delay:1s; animation-iteration-count:infinite; animation-direction:alternate; animation-play-state:running; /* Firefox: */ -moz-border-radius:100px; -moz-animation-name:myfirst; -moz-animation-duration:4s; -moz-animation-timing-function:linear; -moz-animation-delay:1s; -moz-animation-iteration-count:infinite; -moz-animation-direction:alternate; -moz-animation-play-state:running; /* Safari and Chrome: */ -webkit-border-radius:100px; -webkit-animation-name:myfirst; -webkit-animation-duration:4s; -webkit-animation-timing-function:linear; -webkit-animation-delay:1s; -webkit-animation-iteration-count:infinite; -webkit-animation-direction:alternate; -webkit-animation-play-state:running; } @keyframes myfirst { 0% {background:red; left:0px; top:0px;} 50% {background:blue; left:300px; top:300px;} 75% {background:green; left:0px; top:300px;} 25% {background:yellow; left:300px; top:0px;}
159 of 590
Concepts
Session
7
Displaying Graphics and CSS3 Animation
100% {background:red; left:0px; top:0px;} } @-moz-keyframes myfirst /* Firefox */ { 0% {background:red; left:0px; top:0px;} 25% {background:yellow; left:300px; top:0px;} 50% {background:blue; left:300px; top:300px;} 75% {background:green; left:0px; top:300px;} 100% {background:red; left:0px; top:0px;} } @-webkit-keyframes myfirst /* Safari and Chrome */ { 0% {background:red; left:0px; top:0px;} 25% {background:yellow; left:200px; top:0px;} 50% {background:blue; left:200px; top:200px;} 75% {background:green; left:0px; top:200px;} 100% {background:red; left:0px; top:0px;} } </style> </head> <body> <p><b>Note:</b> Animation</p> <div></div> </body> </html>
Concepts
160 of 590
Session
7
Displaying Graphics and CSS3 Animation
Figure 7.6 shows the output of @keyframes rule and all the animation properties.
Figure 7.6: Output of @keyframes Rule and all the Animation Properties
Next, the user can also specify another link element for screen media with a minimum screen width of 481 pixels. In other words, the style sheet for this element can be used for standard computer screens.
161 of 590
Concepts
Session
7
Displaying Graphics and CSS3 Animation Separate Web sites must be developed for mobile devices. The home page of the main site should provide a link that connects to the mobile Web site. This technique identifies the mobile device of the user and renders the mobile Web site automatically in the best view possible. Most mobile Web sites are created to precede the domain name of the main site with m for example m.aptech-education.com To detect a mobile device, a Web site can use JavaScript on the client, a scripting language on the server, or Wireless Universal Resource File (WURFL) on the server. The five ways to provide Web pages for mobile devices are as follows: Define a style sheet for mobile devices Include a link to a mobile version of the Web site Use JavaScript to detect mobile devices and redirect Use a server-side scripting language to detect and redirect Use the WURFL to detect mobile devices
set of proprietary APIs and an XML configuration file which contains information about device capabilities and features for a variety of mobile devices.
Concepts
Rendering engines are a set of tools that are used in most browsers that supports different HTML features. Some of the rendering engines of different browsers are as follows:
Gecko - The Gecko engine is the main engine of Mozilla Firefox, and a number of
related browsers. It has support for various HTML5 features. Although, Firefox is an eminent and highly appreciated browser in the Web development community, it does not yet have the full support for HTML5.
162 of 590
Session
7
Displaying Graphics and CSS3 Animation
Trident - The Trident engine is used by different versions of Internet Explorer (IE).
Currently, HTML5 is not majorly supported by the Trident engine. IE9 was anticipated to support HTML5 completely, but it has failed to support some features such as the advanced form element support and geolocation.
WebKit - The WebKit engines is supported mainly for the Safari browser used in
Apple Macs, iPhones, iPads, and other Apple products. This engine is based on the open source KHTML project. Webkit is also the base for Android based browsers such as Google Chrome. WebKit has evolved to become the standard rendering engine for mobile platforms. WebKit has the maximum support for most of the HTML5 elements, although it still does not support everything.
Presto - Presto is the engine used in the Opera browsers. Opera browsers are
considered to be a technically superior browser, but market share of Opera browsers is still low.
Each browser interprets the Web site code in a different manner, which means that it can appear differently to users using different browsers. The best practices for optimum browser compatibility are as follows:
Test the Web site in different browsers - Once the Web site design is created,
review the Web sites appearance and functionality on multiple browsers to ensure that all the users are getting the same experience according to the design. Preferably test on different versions of the same browser also as they can show the Web site differently.
Write a good clean HTML coding - Sometimes the Web site may appear correctly
in some browsers even if the HTML code is not valid, but there is no guarantee that it will appear correctly in all the browsers. To ensure that the page looks same in all browsers is to write Web pages using valid HTML and CSS codes, and then test it in many browsers. Using External CSS can help pages render and load faster.
163 of 590
Concepts
Session
7
Displaying Graphics and CSS3 Animation
2.
Which of the following browsers support CSS3 Transitions? (A) Apple Safari 2.1 (B) Google Chrome (C) (D) Opera 10.5x IE 4
3.
The CSS padding properties define the _____ between the element border and the element content. (A) size (B) space (C) (D) distance font
4.
Match the features against the usability. Value (A) auto (B) (C) length % 1. 2. 3. 4. Description Specifies that the value of the height property should be inherited from the parent element Defines the height in percent of the containing block Defines the height in px, cm, etc. The browser calculates the height. This is default (C) (D) a-4, b-1, c-2, d-3 a-4, b-3, c-2, d-1
(D) inherit
Concepts
(A) a-2, b-1, c-3, d-4 (B) a-1, b-2, c-3, d-4
164 of 590
Session
5.
7
Displaying Graphics and CSS3 Animation (C) (D) Trident Gecko
Which of the following is the engine for Safari browser? (A) Presto (B) WebKit
6.
Which of the following statements are valid for performing CSS transitions? (A) Specify the name for transition (B) (C) Specify the CSS property, that needs to add an effect Specify the duration of the effect
165 of 590
Concepts
Session
7
Displaying Graphics and CSS3 Animation
7.8.1 Answers
1. 2. 3. 4. 5. 6. A B, C B D B B, C
Concepts
166 of 590
Session
7
Displaying Graphics and CSS3 Animation
Summary
The text styles specify and control the appearance of the text in a Web page. Indenting is the process of offsetting text from its normal position, either to the left or to the right. CSS border property specifies the style, color, and width of the border. The border-color property accepts different color values that determine the different shades of color to be applied to the borders. The values of the different border properties determine the type of effect to be applied to the borders. In CSS, the text-align property is used for horizontal alignment of text in an element. In CSS, the line-height property is used for vertical alignment of text in an element.
167 of 590
Concepts
Session
7
Displaying Graphics and CSS3 Animation
Try it Yourself
1. Mathew wants to develop a Web page on his biblical findings. For writing major quotes of the bible verses he wants blue bordered text box with center alignment of the content and for its explanation he wants text box with red colored text that would be vertically center aligned. Use CSS code to create this Web page.
Concepts
168 of 590
Session
7
Displaying Graphics and CSS3 Animation (Workshop)
Note - Please refer to the respective lab deliverable for demonstrations and guided
simulations.
Labs
170 of 590
Session -
This session explains the different types of navigation bar, HTML5 semantic tags and layout. Finally, this session explains the usage of divisions in HTML5. In this Session, you will learn to:
Explain HTML5 semantic tags Explain HTML5 semantic tag layouts Explain the usage of navigation bar Describe a text-based and graphical navigation bar Explain image mapping Explain divisions in HTML5
Session
8
Creating Navigational Aids and Division-Based Layout
8.1 Introduction
For designing a Web site, a number of elements and principles are used to get the desired results. Using these principles and elements helps to develop a rich, attractive, efficient, and aesthetically pleasing Web site. In other words, using some HTML tags and graphics does help to develop a useful and efficient Web site. Navigation bar plays an important role in making the Web page user-friendly.
for grouping related content and is different from other content groups present on the Web page. It is similar to a div tag though section element has more semantic meaning. In other words, section element is more meaningful as the content inside the section tags should be related.
Header - The header element represents the header of a Web page. It can be used
either at the top of the document or at the top of a section. Though most of the Web sites currently uses a single header at the top of the page called masthead, but a Web developer can have multiple headers in a single HTML5 document. This element is used as a container containing a group of introductory content or a set of navigational links.
Footer - The footer is similar to the header and can be present as the footer either
Concepts
for the document or for the section. There can be multiple footer elements in an HTML5 document. A footer element has information about the Web document. The typical contents which are placed in footer are as follows: Authors information Copyright information Text-based navigation bar
172 of 590
Session
8
Creating Navigational Aids and Division-Based Layout
Any metadata for the section can also be included in a footer tag.
Aside - The aside element is used for representing the content that is related to the
main text of the document. It aligns itself as a sidebar. As compared with other structural tags its importance is not related with its position within a document, but rather its relationship with the content. It is not mandatory to have an aside element aligned to the right or left of a Web page. It can be at the top, the bottom, or even in the middle of a Web page.
Nav - The nav element represents a section of a Web page that contains navigation
links/menus to other Web pages or to other parts within the Web page. In other words, it allows the user to navigate through the Web page and site. This section is created for major navigational information such as a navigation bar for the entire site or for a subsection menu.
Web page or site content. It is self-contained and stands on its own. The possible sources for the article tag are as follows: Blog post News story Comment Review Forum post
Note - The div tag must not be entirely replaced by the semantic tags. The semantic tags
relevance to the context. For example, a mark tag can be used for highlighting words in a Web page that a visitor searched for.
calendar. It is used optionally with a time and a time-zone offset. This element can be used to encode dates and times in a machine-readable format. For example, a Web user can add birthday reminders or scheduled events to the users calendar and enable the search engines to produce better search results.
173 of 590
Concepts
Time - The <time> tag is used for defining either the time, or a date in the Gregorian
Session
8
Creating Navigational Aids and Division-Based Layout Table 8.1 lists attribute and value of <time> tag.
Attribute
datetime pubdate
datetime pubdate
Value
Description
Provides the date/time given by the elements content It is used for specifying publication date and time of the document
Table 8.1: Attribute and Value of <time> Tag Code Snippet 1 demonstrates the code to display date and time.
Code Snippet 1: <!DOCTYPE html> <html> <body> <time datetime=13:00>1pm</time> <time datetime=2011-07-15>July 15th, 2011</time> <time datetime=2011-07-15T13:00>1pm on July 14th</time> </body> </html>
The datetime attribute is not mandatory. Code Snippet 2 demonstrates the code to display date.
Code Snippet 2: <time>2011-07-14</time> Meter - The <meter> tag displays markup or scalar measurement within a defined
range. Absolute scalar values, such as height or weight, are not represented automatically by the meter tag. For this, the user must specify the height and weight within the known range of values. It is also used for displaying fractional value. Code Snippet 3 demonstrates the code to display <meter> tag.
Code Snippet 3:
Concepts
174 of 590
Session
8
Creating Navigational Aids and Division-Based Layout
form_id number number number number number number
Attribute
form high low
Value
Description
Is used for specifying one or more forms that <meter> element belongs to Is used for specifying the high range value Is used for specifying a range of value that is to be considered as low and should be greater than min attribute value Is used for specifying the maximum value of the range Is used for specifying the minimum value of the range Is used for specifying the optimal value for the <meter> tag Is used for specifying the current value of the <meter> tag
of a task.
Attribute
max value
Is used for specifying the work as a floating point number that the task requires in total number Is used for specifying how much task has been completed Table 8.3: Attributes and Value of <progress> Tag
number
Value
Description
The sample representation of a Web page layout is displayed in figure 8.1. The section will explain every section defined and the purpose of each section.
Session
8
Creating Navigational Aids and Division-Based Layout In other words, figure 8.1 shows the HTML5 semantic layout and used elements for every section.
<header>
The <header> element provides introductory information. This information can include titles, subtitles, logos, and so on. It can also include the navigational aids. The <head> tag provides information about the entire document, whereas the <header> tag is used only for the body of the Web page or for the sections inside the body. Code Snippet 5 demonstrates the use of <header> tag.
Code Snippet 5: <!DOCTYPE html> <html lang=en> <head> <meta charset=utf-8> <title>My First Page</title> </head> <body> <header> <h1>Sample Blog </h1> </header> </body> </html>
Concepts
176 of 590
Session
8
Creating Navigational Aids and Division-Based Layout
In the code, the <header> element shows the commencement of the body. This is the visible part of the document. Inside the <header>, the <h1> element is used to indicate the importance of the heading.
<nav>
The nav element is a section which contains the links to other pages or links to different sections within the page. In other words, it is a section containing the navigation links. Navigational elements are helpful in identifying large blocks of navigational data and are generally not preferred for small navigational displays. Code Snippet 6 demonstrates the use of <nav> tag.
Code Snippet 6: <body> <header> <h1>Sample Blog</h1> </header> <nav> <ul> <li> home </li> <li> help </li> <li> contact </li> </ul> </nav> </body>
In the code, the <nav> element is present between the <body> tags but after the closure of <header> tag.
<section>
It is the main information bar that contains the most important information of the document and it can be created in different formats. For example, it can be divided into several blocks or columns. For example, a Web sites home page could be divided into sections for an introduction, news updates, and contact information.
177 of 590
Concepts
Session
8
Creating Navigational Aids and Division-Based Layout Code Snippet 7 demonstrates the use of <section> tag.
Code Snippet 7: <body> <header> <h1>Sample Blog </h1> </header> <nav> <ul> <li> home </li> <li> help </li> <li> contact </li> </ul> </nav> <section> <h1>Links</h1> <ul> <li><a href=#>Link 1</a></li> <li><a href=#>Link 2</a></li> <li><a href=#>Link 3</a></li> </ul> </section> </body>
Similar to the navigation bar, the main information bar is a separate section. Therefore, the main information bar appears after the </nav> closing tag.
<aside> Concepts
The <aside> element is a column or a section that generally contains data linked to the main information but not as relevant or important as the main information. This element is used for typographical effects, such as for sidebars, for groups of nav elements, for advertising purposes, and for other content that cannot form a part of the main content of the page.
178 of 590
Session
8
Creating Navigational Aids and Division-Based Layout
The <aside> element can be placed in any part of the site layout. It can also be used in any way as long as the content is not considered as the main content of the document.
179 of 590
Concepts
Session
8
Creating Navigational Aids and Division-Based Layout Figure 8.2 shows output of Code Snippet 8.
<footer>
HTML5 provides the <footer> element to give an end to the documents body. A footer typically contains information about the sections. This can include the author or company details, links to related documents, copyright data, and so on. Code Snippet 9 demonstrates the use of <footer> tag.
Code Snippet 9:
Concepts
</head>
180 of 590
Session
<body>
8
Creating Navigational Aids and Division-Based Layout
<header> <h1>Sample Blog </h1> </header> <nav> <ul> <li> home </li> <li> help </li> <li> contact </li> </ul> </nav> <section> <h1>Links</h1> <ul> <li><a href=#>Link 1</a></li> <li><a href=#>Link 2</a></li> <li><a href=#>Link 3</a></li> </ul> </section> <aside> <blockquote>Archive Number One</blockquote> <br> <blockquote>Archive Number Two</blockquote> </aside> <footer> Copyright © 2012-2013 </footer> </html> </body>
Usually, the <footer> element represents the end of the body section. However, the <footer> tag can be used many times inside the body to represent the end of different sections.
181 of 590
Concepts
Session
8
Creating Navigational Aids and Division-Based Layout Figure 8.3 shows output of Code Snippet 9.
<article>
The <article> element helps to insert a self-contained composition in an application, page, document, or site. For example, an <article> element could be an interactive widget, an entry in a blog, an article in a newspaper or magazine, a post in a forum, a comment submitted by a user, or any other independent content.
Concepts
182 of 590
Session
8
Creating Navigational Aids and Division-Based Layout
183 of 590
Concepts
<aside>
Session
8
Creating Navigational Aids and Division-Based Layout
Copyright © 2012-2013 </footer> </body> </html>
In the code, the <article> tags are placed within the <section> tags. This indicates that the <article> tag belongs to this section. The <article> tags are placed individually one after another, because each one is an independent part of the <section>. Figure 8.4 shows output of Code Snippet 10.
Concepts
184 of 590
Session
8
Creating Navigational Aids and Division-Based Layout
Figure 8.5 shows the new layout, after adding the <article> tag.
Figure 8.5: New Layout after Adding the <article> tag The content of every <article> element has its own independent structure.
185 of 590
Concepts
Session
8
Creating Navigational Aids and Division-Based Layout Some users browse Web site with graphics turned off, or use browsers with minimum graphics capability. For such situations, it is essential to provide text-based navigation bars which are created as a stand-alone navigation bars. The developer in addition can also provide a graphical bar. Text-based navigation bars are not associated with icons but are easy to create, and can be displayed in any Web browsers. The advantage of using a text-based navigation bar is that it reduces the loading time of a page. Although a text-based navigation bar is easy to create, it is not interesting because there is very less interaction or visual appeal to the visitor. Text links are hard to distinguish from the regular text that appears on a Web page. It can be displayed either horizontally or vertically. The font (best to use Web safe fonts), color, and link colors can be determined by the user via the Font pane. Code Snippet 11 demonstrates the HTML code for a text-based navigation bar.
Code Snippet 11: <!DOCTYPE html> <html> <head> </head> <body> <nav> <a href=/https/www.scribd.com/home/><font size=6>Home</font></a> | <a href=/https/www.scribd.com/news/><font size=6>News</font></a> | <a href=/https/www.scribd.com/contact/><font size=6>Contact</font></a> | <a href=/https/www.scribd.com/about/><font size=6>About</font></a> </nav> <h1>This is a Text-based Navigation Bar</h1> </body> </html>
Concepts
Session
8
Creating Navigational Aids and Division-Based Layout
Graphical navigation bar is more captivating than text-based navigation bar as it uses icons. The usability of the page increases with a good choice of icon for the navigation bar. It can also make the Web site more noticeable for the user visiting the Web site. In other words, graphical navigation bar is better than text-based navigation as it gives a visual appeal to the visiting users. The only disadvantage is that, since it uses images, it takes longer time for a page to load. Also, the Web page will be useless for users using a non-graphic browser.
Code Snippet 12 demonstrates CSS and HTML code for a graphical navigation bar.
187 of 590
Concepts
Session
8
Creating Navigational Aids and Division-Based Layout
float:left; border-left:1px solid #c4dbe7; border-right:1px solid #c4dbe7; } ul#navigation li { display:inline; font-size:12px; font-weight:bold; margin:0; padding:0; float:left; position:relative; border-top:1px solid #c4dbe7; border-bottom:2px solid #c4dbe7; } ul#navigation li a { padding:10px 25px; color:#616161; text-shadow:1px 1px 0px #fff; text-decoration:none; display:inline-block; border-right:1px solid #fff; border-left:1px solid #C2C2C2; border-top:1px solid #fff; background: #f5f5f5; -webkit-transition:color 0.2s linear, background 0.2s linear; -moz-transition:color 0.2s linear, background 0.2s linear;
Concepts
188 of 590
Session
8
Creating Navigational Aids and Division-Based Layout
-o-transition:color 0.2s linear, background 0.2s linear; transition:color 0.2s linear, background 0.2s linear; } ul#navigation li a:hover { background:#f8f8f8; color:#282828; } ul#navigation li a.first { border-left: 0 none; } ul#navigation li a.last { border-right: 0 none; } ul#navigation li:hover > a { background:#00FF00; } /* Drop-Down Navigation */ ul#navigation li:hover > ul { /*these 2 styles are very important, being the ones which make the drop-down to appear on hover */ visibility:visible; opacity:1; } ul#navigation ul, ul#navigation ul li ul { list-style: none; padding: 0; margin: 0;
189 of 590
Concepts
Session
8
Creating Navigational Aids and Division-Based Layout
/*the next 2 styles are very important, being the ones which make the drop-down to stay hidden */ visibility:hidden; opacity:0; position: absolute; z-index: 99999; width:180px; background:#f8f8f8; box-shadow:1px 1px 3px #ccc; /* css3 transitions for smooth hover effect */ -webkit-transition:opacity 0.2s linear, visibility 0.2s linear; -moz-transition:opacity 0.2s linear, visibility 0.2s linear; -o-transition:opacity 0.2s linear, visibility 0.2s linear; transition:opacity 0.2s linear, visibility 0.2s linear; } ul#navigation ul { top: 43px; left: 1px; } ul#navigation ul li ul { top: 0; left: 181px; /* strong related to width:180px; from above */ } ul#navigation ul li { clear:both; width:100%; border:0 none; border-bottom:1px solid #c9c9c9;
Concepts
190 of 590
Session
}
8
Creating Navigational Aids and Division-Based Layout
ul#navigation ul li a { background:none; padding:7px 15px; color:#616161; text-shadow:1px 1px 0px #fff; text-decoration:none; display:inline-block; border:0 none; float:left; clear:both; width:150px; } </style> </head> <body> <nav id=nav> <ul id=navigation> <li><a href=><font size=4><img src=Home-icon.png height=20 width=20>Home</img></font></a></li> <li><a href=><font size=4><img src=icon-news.png height=20 width=20>News</font></a></li> <li><a href=><font size=4><img src=Address-Book-icon.png height=20 width=20>Contact</font></a></li> <li><a href=><font size=4><img src=User group.png height=20 width=20>About</font></a></li> </nav> <br/> <br/> <br/>
191 of 590
Concepts
Session
8
Creating Navigational Aids and Division-Based Layout
<br/> <h1>This is a Graphical Navigation Bar</h1> </body> </html>
Attribute
name
mapname
Value
Description
It is used for specifying the name of an image-map
Table 8.4: <map> Tag Attribute and its Value Follow these guidelines to create an image map: 1. Use the <img> tag to insert and link an image. In the <img> tag, use the usemap attribute to define the image map name. Use the <map> tag to create a map with the same name. Inside this <map> tag, define the clickable areas with the <area> tag.
Concepts
2.
192 of 590
Session
8
Creating Navigational Aids and Division-Based Layout
193 of 590
Concepts
Session
8
Creating Navigational Aids and Division-Based Layout
8.6 Divisions
The <div> tag defines a division in an HTML Web page. It is used to group block-elements and format them with CSS. The new structural semantic tags reasonably reduce a lot of <div> tags usage, but <div> tag is still important in the HTML5 world. The <div> tag can be used when there is no other semantically appropriate element left that suits the purpose in a Web page development. It can be commonly used for stylistic purposes such as wrapping some semantically marked-up content in a CSS-styled container. Code Snippet 14 demonstrates an HTML code to show the use of <div> tag used for wrapping.
Code Snippet 14: <body> <div id=wrapper> <header> <h1>Hello</h1> <nav> <! -- ... --> </nav> </header> </div> </body>
Tips for using <div> tag in Web site development are as follows: The <div> tag is a block-level element. The <div> tag can contain any other tag. In HTML5, the <div> tag can be found inside any element that can contain flow elements, such as other <div>, <address>, <section>, and <table>.
Concepts
194 of 590
Session
8
Creating Navigational Aids and Division-Based Layout
Value
static absolute fixed relative inherit
Description
Positions the element in order, as they appear in the document flow. It is the default value. Positions the element relative to its first position. Positions the element relative to the browser window. Positions the element relative to its normal position. Positions the element with respect the value that is inherited from the parent element.
Table 8.5: Values For Positioning With the DIV Element Code Snippet 15 demonstrates the CSS code for <div> tags with different position properties.
Code Snippet 15: .lCard{ width: 100px; height:100px; background-color:blue; padding: 6px; position:fixed; left:450px; top:100px; } .rCard{ width: 100px; background-color:red; padding: 7px; position:relative; top:93px; } .bCard{ width: 100px; height:100px; background-color:green;
195 of 590
Concepts
left:300px;
Session
8
Creating Navigational Aids and Division-Based Layout
padding: 6px; position:absolute; left:310px; bottom:320px; }
Include the div tag within the style section of the HTML body. Code Snippet 16 demonstrates HTML code for <div> tags.
Code Snippet 16: <body> <div class=rCard> </div> <div class=bCard> </div> <div class=lCard> </div> </body>
Concepts
Figure 8.9: Output of Division Positioning Multiple columns are created by using the <div> tag and CSS is used to format the divisions. Divisions can be formatted by using the same character, paragraph, and page formatting styles. In the Code Snippet, CSS is used to format each DIV.
196 of 590
Session
8
Creating Navigational Aids and Division-Based Layout
2.
Image maps are images with clickable _____ that link to another page. (A) images (B) texts (C) (D) areas links
3.
Which tag is used to represents content that is tangentially related to the main text of a document? (A) <section> (B)
<aside>
(C) (D)
<header> <article>
4.
(D) relative
The element is positioned relative to its normal position. The element is positioned relative to the (2) browser window. The element is positioned relative to its first (3) positioned. Elements renders in order, as they appear in (4) the document flow. This is default. (1) (C) (D) a-4, b-3, c-2, d-1 a-3, b-2, c-4, d-1
(A) a-2, b-1, c-3, d-4 (B) a-1, b-2, c-3, d-4
197 of 590
Concepts
Session
8
Creating Navigational Aids and Division-Based Layout 5. Match the following.
Value Description
Used for displaying the publication date and time Used with JavaScript for displaying the progress (2) of a task (1) (3) Used for displaying fractional value (4) Used for defining marked or highlighted text (C) (D) a-4, b-3, c-2, d-1 a-2, b-1, c-4, d-3
(D) progress
(A) a-3, b-4, c-1, d-2 (B) a-1, b-2, c-3, d-4
6.
Which tag is used to markup measurements or a scalar measurement within a known range? (A) <time> (B)
<meter>
(C) (D)
<header> <progress>
Concepts
198 of 590
Session
8
Creating Navigational Aids and Division-Based Layout A C B C A B
8.7.1 Answers
1. 2. 3. 4. 5. 6.
199 of 590
Concepts
Session
8
Creating Navigational Aids and Division-Based Layout
Summary
HTML5 has introduced two types of semantic tags. They are namely, text-level and structural. Structural semantic tags are as follows: Section Header Footer Aside Nav Article Mark Time Meter Progress
Navigation is the most significant element in Web design. Since Web-layouts does not have any physical representation a user can depend on consistent navigation menu. Text-based navigation bars are created as stand-alone navigation bars that are not associated with icons. Text-based navigation bar is easy to create and can be displayed in any Web browsers. Graphical navigation bar is better than text-based navigation as it gives a visual appeal to the visiting users. The new structural semantic tags reasonably capture a lot of <div>s territory, but <div> tag still has a place in the HTML5 world. Div can be used when there is no other semantically appropriate element left that suits the purpose in a Web page development.
Concepts
200 of 590
Session
8
Creating Navigational Aids and Division-Based Layout
Try it Yourself
1. ABC Inc. is a gaming company which is planning to start its online site for games. ABC Inc. needs a navigation bar which will give information about their products, company itself, support, and online gaming center, and so on. Navigation bar should have the following links: 1. 2. 3. 4. 5. 6. Home About us Products Gaming Center Support Contacts
You as a Web site designer have been assigned the task for developing the Web site for the company using the new semantic tag.
201 of 590
Concepts
Session
Action may not always bring happiness, but there is no happiness without action.
Concepts
202 of 590
Session
8
Creating Navigational Aids and Division-based Layout (Workshop)
Note - Please refer to the respective lab deliverable for demonstrations and guided
simulations.
Labs
204 of 590
Creating Tables
This session explores how to create tables, specify the size of the table, and the width of a column in a table. The session also describes the merging of table cells, how to define page layout for tables, and apply formatting to tables. In this Session, you will learn to:
Describe how to create and format tables Explain the table size and the width of a column Explain the process of merging table cells Explain the page layout for tables
Session
9
Creating Tables
9.1. Introduction
Tables allow the user to view the data in a structured and classified format. Tables can contain any type of data such as text, images, links, and other tables. The user can create tables for displaying timetables, financial reports, and so on.
Concepts
Session
9
Creating Tables
The code uses the <table> element to create a table. The border attribute of <table> element gives a border to the table, which is 1 pixel wide. The <tr> element within the <table> element creates rows. The <td> element creates two cells with the values English and German in the first row and French and Italian in the second row. Figure 9.1 displays a table created.
207 of 590
Concepts
Session
9
Creating Tables
<tr> <th>Name</th> <th>Age</th> <th>Place</th> </tr> <tr> <td>Mark</td> <td>17</td> <td>Madrid</td> </tr> <tr> <td>John</td> <td>19</td> <td>London</td> </tr> </table> </body> </html>
In this code, the <table> element creates a table with a border of 1 pixel. The <th> element provides three column headings namely, Name, Age, and Place.
Concepts
208 of 590
Session
9
Creating Tables
The second and the third row lists the details of the students in the three columns. Figure 9.2 displays the output of the table with headings.
209 of 590
Concepts
<head>
Session
9
Creating Tables
<tr> <th colspan=2>IT</th> <th colspan=2>Accounts</th> </tr> <tr> <th>Name</th> <th>Location</th> <th>Name</th> <th>Location</th> </tr> <tr> <td>David</td> <td>New York</td> <td>John</td> <td>London</td> </tr> <tr> <td>Katthy</td> <td>New Jersey</td> <td>Peter</td> <td>Los Angeles</td> </tr> </table> </body> </html>
Concepts
The code creates a table with a border of 1 pixel. The <th> element specifies two column headings namely, IT and Accounts. Each of these header cells horizontally span across the two cells by setting the colspan attribute of the <th> element to 2. Each of these headings has two sub-headings namely, Name and Location, which specify the name and location of employees. The first and second rows display the details of the employees.
210 of 590
Session
9
Creating Tables
211 of 590
Concepts
Session
9
Creating Tables
</tr> <tr> <th rowspan=3>Audi</th> <td>A4</td> <td>34.5</td> </tr> <tr> <td>A5</td> <td>42.6</td> </tr> <tr> <td>A6</td> <td>30.75</td> </tr> <tr> <th rowspan=2>BMW</th> <td>328i</td> <td>28.25</td> </tr> <tr> <td>530d</td> <td>47.5</td> </tr> </table> </body> </html>
The code creates a table with a border width of 1 pixel. The three <th> elements within the <tr> element specify column headings namely, Manufacturer, Model, and Price. The rowspan attribute of the <th> element combines the three rows of the Manufacturer column into a common brand namely Audi. The three different models and the respective prices of the Audi brand are displayed in three different rows. Similarly, the rowspan attribute of the <th> element combines the next two rows of the Manufacturer column into a common brand called BMW.
Concepts
212 of 590
Session
9
Creating Tables
Aligns the data within a cell on the left side. This is the default value for table content.
center
Aligns the data within the cell on the center. This is the default value for table headings.
right
justify
Aligns the data within the cell by adjusting the text at the edges. To set the alignment with style you can use the text-align attribute to specify the horizontal alignment.
213 of 590
Concepts
Session
9
Creating Tables Code Snippet 5 demonstrates how to center align the table data.
Code Snippet 5: <!DOCTYPE HTML> <html> <head>
</head> <body>
<title>Automobile Gallery</title>
</table>
Concepts
</html>
</body>
The code aligns the data within the row using a style within the <tr> element. The table content is center aligned by setting the value of the text-align attribute to center.
214 of 590
Session
9
Creating Tables
Vertically aligns the data within the cell at the bottom. To set the alignment with the style you can use the text-align attribute to specify the vertical alignment use the following syntax:
<td style= text align: center; vertical align: middle>
The style can also be applied to individual rows, cells, or to the entire table.
215 of 590
Concepts
Syntax:
Session
9
Creating Tables Code Snippet 6 demonstrates how to align the data vertically within the table using the style attribute.
Code Snippet 6: <!DOCTYPE HTML> <html> <head>
</head> <body>
<title>CelinaBatteries</title>
<th>Product Description</th>
<td style=text-align: center; vertical-align: middle>P101 </td> </tr> <tr> <td>1.5 Volts AA Ultra Alkaline</td>
<td style=text-align: center; vertical-align: middle>M105 </td> </tr> <td>9 Volts pp3 Super Alkaline</td>
Concepts
</html>
</body>
</table>
The text-align attribute is set to the value center, which specifies that the data within the rows are centrally aligned. The vertical-align is used to specify the vertical alignment in the table.
216 of 590
Session
9
Creating Tables
For tables, padding is specified as a space between the text and the cell border. Suppose if the user wants to set the padding attribute for the individual cells then he/she can use the padding attribute in a style as follows:
<td style=padding: 4px>
217 of 590
Concepts
Session
9
Creating Tables Code Snippet 7 demonstrates how to specify a heading for a table.
Code Snippet 7: <!DOCTYPE HTML> <html> <head>
</head>
<th>Transport</th>
</tr> <tr>
</tr> <tr>
Concepts
</html>
</body>
</table>
</tr>
<td>90.00</td>
218 of 590
Session
9
Creating Tables
The code creates a table of border width of 1 pixel. The <caption> element that is used inside the <table> element specifies a caption to the entire table as Travel Expense Report. Figure 9.7 displays the table captions.
</head>
<title>Tables</title>
<h2>Table</h2> <tr>
219 of 590
Concepts
<body>
Session
9
Creating Tables
<td style =width: 80px>Fruits</td> </tr> <tr>
</html>
</body>
</table>
</tr>
The code creates a table of border width of 1 pixel. The <style> element is used to set table width to 100%. The width of the columns is set by using the style attribute. Figure 9.8 displays the table size and column width.
Concepts
220 of 590
Session
9
Creating Tables
Code Snippet 9 demonstrates creating a table having five columns and five rows, but many of the cells span multiple columns or rows.
Code Snippet 9: <!DOCTYPE HTML > <html> <head> <title>Favorite Destination</title> </head> <body> <h2>Report</h2> <table border=1 width=100% height=100%> <tr> <td colspan=2 rowspan=2>Results</td> <td colspan=3>Range</td> </tr> <tr> <td>18 to 20</td> <td>25 to 50</td> <td>over 50</td> </tr> <tr> <td rowspan=3>Your favorite vacation destination</td> <td>Dubai</td> <td>25%</td> <td>50%</td> <td>25%</td> </tr> <tr> <td>Bangkok</td> <td>40%</td> <td>30%</td> <td>30%</td> </tr> <tr> <td>Switzerland</td> <td>30%</td> <td>20%</td> </tr> <td>50%</td>
</html>
</body>
</table>
221 of 590
Concepts
Session
9
Creating Tables The code creates a table having a border of 1 pixel. It also creates a table with five columns and five rows and uses the colspan and rowspan attributes respectively. Figure 9.9 displays the merging table cells.
Suppose if the user wants to set all these attributes at one time then the user can use the border attribute and place the settings in the following order namely, width, color, and style respectively. The user can also format the sides of the border individually by replacing the border attribute with border-bottom, border-top, border-right, or border-left attribute. The user can apply these attributes to the entire table or individual cells and also create rules in the <style> area.
Concepts
222 of 590
Session
9
Creating Tables
Nowadays, there are many new techniques used for developing attractive Web pages. Tables are used for structuring the content. In other words, tables are used by the user to organize the data in an appropriate manner. With tables the user can arrange the data horizontally or vertically according to his/her requirements. Community Web sites such as Facebook has different page layouts, the user uses the navigation tabs to move from one page to another. Similarly, the look and feel of each page is different. While accessing Web sites such as Yahoo, Rediff, and so on users can view that the home page is very informative with a number of links, images, and so on. Each and every Web site has their unique way of presenting data to their customers or users. Many Web sites use pop-ups for providing information to their customers. Code Snippet 10 demonstrates a simple example of using table for structuring the content of a Web page.
Code Snippet 10: <!DOCTYPE HTML> <html> <head>
#navlayout {
background-color: #f2f2f2;
border-bottom: 1px solid #ccc; #navlayout li { border-top: 1px solid #ccc; } float: left; }
223 of 590
Concepts
Session
9
Creating Tables
text-decoration: none; font-weight: bold; color: #069;
<body>
</style>
background-color: #fff; }
<ul id=navlayout>
<li><a href=#>Contact Us</a></li> <li><a href=#>About Us</a></li> </ul> <li><a href=#> FAQs</a></li>
<li><a href=#>Home</a></li>
Concepts
</html>
</body>
</table>
</tr>
</td>
The code creates a page layout for a Web site. The data is arranged in a tabular format and an embedded style is used for defining the style. The style is defined using the style element placed immediately after the <head> section. V 1.1 Aptech Limited
224 of 590
Session
9
Creating Tables
Defining a style in this manner helps to reuse the style in the same Web page. The style is set using the ID selector methodology and is identified as navlayout. This will enable to apply the style to the content of all those elements whose id attribute has been set to navlayout. Figure 9.10 displays the example of a page layout for using tables.
225 of 590
Concepts
Session
9
Creating Tables
2.
Which of the following element is used to specify the heading for columns in a table? (A) <style> (B) <td> (C) <tr> (D) <th>
3.
Identify the attribute that allows spanning of cell horizontally. (A) rowspan (B) colspan (C) meta (D) div
4.
Which of the following option represent the possible values that can be used to vertically align the content within a table? (A) top (B) justify (C) middle (D) bottom
Concepts
226 of 590
Session
5.
9
Creating Tables
Andy is working on an online banking Web site. He wants to create a table for displaying the rate of interest allowed by the bank for different types of accounts. He also wants to give some width for the columns in the table. Which of the following code can he use to accomplish this task?
<table border=1> <tr> <td style=height: 20px>Savings</td> <td style=height: 80px>Current</td>
(A)
</tr> <tr>
(B)
</tr> <tr>
<td style =70%>10px</td> </table> <table border=1> <tr> <td style =width: 100px>Savings</td> <td style =width: 200px>Current</td>
(C)
</tr> <tr>
</table>
227 of 590
Concepts
Session
9
Creating Tables
<table border=1> <tr> <td style =20px>Savings</td> <td style =80px>Current</td> </tr> <tr> <td style =70px>4%</td> <td style =30px>10%</td> </tr> </table>
(D)
Concepts
228 of 590
Session
9
Creating Tables A, B, C D B A, C, D C
9.7.1 Answers
1. 2. 3. 4. 5.
229 of 590
Concepts
Session
9
Creating Tables
Summary
Tables allow the user to view your data in a structured and classified format. Padding is the amount of space between the content and its outer edge. The caption element defines a caption for a table. It is a sub-element of the <table> element. Spanning refers to a process of extending a cell across multiple rows or columns. The rowspan attribute spans a data cell across two or more rows. The colspan attribute allows the user to specify the number of columns a cell should span. The border attribute of the table element allows the user to specify a border for making the table visible in a Web page. Tables allow the user to organize the data. It enables the developer to design a Web page having an attractive page layout.
Concepts
230 of 590
Session
9
Creating Tables
Try it Yourself
1. Samson works for an advertising agency and is headquartered at Hong Kong. He is very fond of learning latest technologies that are coming up in the market. He wants to create an HTML5 Web site for his company. The company offers a number of services such as designing of logos, new media, promotions, and branding. Samson wants to develop their company Web site home page and also wants to add all the details about the company with additional graphics, text, animations, and arrange the content in an organized manner. He has decided to use tables for the Home page. Help him to develop the application. Carol is working on an online shopping Web site. This Web site has a wide range of collection for men, women, and kids. The Web site deals with many branded products such as bags, shoes, clothes, jewelry, beauty products, and many more. The Web site was created earlier using HTML 4 version. Now, she has decided to upgrade the Web site with HTML5. She wants to change the appearance and layout of the entire Web site by adding page layouts to the Web site using the new features of HTML5 so that the Web site is appealing and attractive for the new generation. Help her to design the Web site using new features of HTML5.
2.
231 of 590
Concepts
Session
9
Creating Tables (Workshop)
Note - Please refer to the respective lab deliverable for demonstrations and guided
simulations.
Labs
234 of 590
HTML Forms
This session describes the new features in HTML5 forms, working of new input types, new form attributes, new form field attributes, and new form elements. In this Session, you will learn to:
Describe HTML5 forms Explain the working of new input types in HTML5 Explain the new Form attributes Explain the new Form elements
10
Session
10
HTML Forms
10.1 Introduction
HTML, the core language of the World Wide Web is being used for designing Web pages for nearly a decade. With the continuous evolvement in the Web, Web designers and programmers find it difficult to make pages more flexible and dynamic in behavior. The dynamic behavior is particularly expected when displaying Web forms to the users. For example, HTML5 allows creating combo boxes, adding placeholder text on the page, providing client-side validations through JavaScript, and achieving dynamic behavior using Document Object Model (DOM) API. Although Internet Explorer 9 and Google Chrome 19 support most HTML5 features, there are some that are supported only in Opera 11.
Concepts
236 of 590
Session
10
HTML Forms
Note - The state of HTML5 is changing continuously to improve. Thus, support for new
form elements, attributes, and input types can vary across different browsers.
Element
Description
task on the page Represents a scale of known range datalist Represents a set of options used with list attribute to make a drop-down control output Represents the result of a calculation Table 10.1: New Elements in HTML5
Type
Description
Represents the completion progress of a task on the page Represents a scale of known range Represents a set of options used with list attribute to make a drop-down control Represents the result of a calculation Represents a numeric value in the input field Represents a numeric value to be selected from a range of numbers Represents a calendar which is shown at every click on the field Represents date in year-week format
search
237 of 590
Concepts
Session
10
HTML Forms
month
Type
Description
Represents a value with year-month format time Represents a value in hours and minutes format datetime Represents a full date and time input field with a time zone datetime-local Represents a full date and time with no time zone color Represents a predefined interface for selecting color Table 10.2: New Input Types Supported by HTML5
Type
Description
Represents a hint that help users to enter the correct data in the field A Boolean attribute that validates the entry in the field A Boolean attribute that allows multiple values to be entered in the field Focuses the input element on page load Represents a regular expression for validating the fields value Allows the elements to reference the form by including the form name Table 10.3: New Attributes in HTML5
Concepts
238 of 590
Session
10
HTML Forms
239 of 590
Concepts
Session
10
HTML Forms
Description
Allows script to run only when the element is invalid Allows script to run when the form gets an input from the user Represents a regular expression for validating the fields value Allows script to run when the form changes Table 10.4: Events and Methods
Concepts
HTML5 has introduced more data-specific user interface elements. Now, you will see the new input types in detail.
240 of 590
Session
10
HTML Forms
The type=email is used for specifying one or more e-mail addresses. To allow multiple addresses in the e-mail field, separate each address with comma-separator. In the registration form, the input type is changed from text to email as shown in Code Snippet 2.
Code Snippet 2: <form method=get action=test.html> <label for=emailid>Email:</label> <input type=email value= id=emailid name=emailaddress maxlength=255 </form> /> <input type=submit value=submit/>
In the code, <label> tag defines a label for the element on the form. The for attribute of <label> tag binds it with the related element, that is email element, on the form. The value of for attribute must match with the value of id attribute assigned to the element. Also, the email contains two attributes, namely id and name. The id attribute specifies a unique id for the element. The value of the id attribute should be unique within the document. It can be used as a reference for styles in style sheet or to access elements using DOM API in JavaScript. The name attribute specifies a name for the input element. It can be used for referencing the elements in a JavaScript or form data after a form is submitted to the server for processing. The look of the input is still like a plain text field, but changes are applied behind the scenes. Browsers, such as Firefox, Chrome, and Opera will display a default error message if user submits the form with some unrecognizable contents.
241 of 590
Concepts
Session
10
HTML Forms Figure 10.1 shows the error message for incorrect e-mail address in Chrome.
10.4.2 URL
The type=url input element is used for specifying a Web address. The look of the url field is a normal text field. Code Snippet 3 shows the code of url input type.
Code Snippet 3: <label for=url>Enter your Web page address:</label> <input type=url value= id=urlname name=urltext maxlength=255 />
Concepts
Browsers, such as Opera, Firefox, and Chrome supports validation for the url input type. While validating the URL, browsers only checks for entry with forward slash (/). For example, a URL such as x://mysite.com will be considered as valid, even though x:// is not a real protocol.
242 of 590
Session
10
HTML Forms
Figure 10.2 shows the error message for incorrect URL in Chrome.
The input type=number is used for accepting only number values. The input element displayed for number type is a spinner box. The user can either type a number or click the up or down arrow to select a number in the spinner box.
243 of 590
Concepts
10.4.4 Number
Session
10
HTML Forms Code Snippet 5 shows the code for including number input type on the form.
Code Snippet 5: <label for=stud_age>Age:</label> <input type=number value=15 id=stud_age name=studentage min=15 max=45 step=1 /> <input type=submit value=submit/>
In the code, the number input type has attributes, such as min and max to specify the minimum and maximum value for the input. Figure 10.3 shows the number input type in Opera.
10.4.5 Range
The input type=range is similar to number type and displays a slider control on the page. The range type is used when the exact value is not required in the input. In other words, the value from this type is not accurate. For example, an online survey form asking the clients to rate the products may not receive exact values in the ratings. Code Snippet 6 shows the code for including range input type with attributes min and max.
Code Snippet 6:
Concepts
<label>Survey for packages offered[scale: 1-10]:</label> <input type=range name=rating min=1 max=10 /> <input type=submit value=submit/>
244 of 590
Session
10
HTML Forms
In the code, the range input type contains attributes, such as min, max, step, and value. The min and max attributes are used to specify the minimum and maximum value allowed for a range and are set to 1 and 10 respectively. The step attribute specify the intervals for incrementing the value. The value of step attribute is 1 by default. The value attribute specifies the default value for the range. The default value is the midpoint of the range specified. Figure 10.4 shows the range input type in Opera.
Figure 10.4: Range Input Type in Opera Figure 10.5 shows the value for the range input type in the URL after the form is submitted by the user. The rating selected by the user can be seen in the Address Bar of the browser.
HTML5 has introduced several new input types for date and time. The format for all these date and time types is according to the ISO standards. At present only Opera provides the support for date element by displaying a calendar control.
Date
This input type contains only date in year, month, and day format. The time part is not support by date type.
Session
10
HTML Forms Code Snippet 7 shows the code of the date input type.
Code Snippet 7: <label for=stdate>Date:</label> <input type=date id=stdate name=startdate min=2000-01-01/> <input type=submit value=Submit id=btnSubmit></input>
In the code, all date input types have min and max attributes to set the range for the dates. The default value for date input type is based on the browsers. Different browsers take different dates as default. Thus, it is advisable to set the minimum and maximum value for the date type. Figure 10.6 shows the date input type.
Figure 10.6: Date Input Type Figure 10.7 shows the value sent for the date input type after the form is submitted by the user.
Concepts
The type=month includes only the year and month in the input.
246 of 590
Session
10
HTML Forms
id=stmonth name=startmonth />
Browser such as Opera will display the date picker for selecting month. On selecting any day from the calendar, the whole month is selected. Figure 10.8 shows the date picker for the month input type.
The input type=week provides a similar interface as displayed for date type and selects the entire week.
Code Snippet 9: <label>Week:</label> <input type=week name=week /> <input type=submit value=submit/>
247 of 590
Concepts
Session
10
HTML Forms Figure 10.9 shows the week input type in Opera.
Figure 10.9: Week Input Type in Opera In this figure, the 12th March is selected and the combo box also displays the 2012-W12 as the 12th week is selected. Similar to date input types, there are new time input types introduced in HTML5.
Time
The input type=time displays a time of day in hours and minutes format (24-hour clock). Code Snippet 10 shows the syntax of time input type.
Code Snippet 10: <label>Time:</label> <input type=time name=time /> <input type=submit value=submit/>
Concepts
248 of 590
Session
10
HTML Forms
The input type=datetime includes full date and time in the input. The input includes a date part and a time part which is represented as Coordinated Universal Time (UTC). Thus, UTC time will be displayed with T followed by a Z. For example, an input, such as 2012-07-03T12%3A05Z is interpreted as 2012-07-03T12:01. Code Snippet 11 shows the syntax of datetime input type.
Code Snippet 11: <label for=mydatetime>Date-Time:</label> <input type=datetime name=mydatetime /> <input type=submit value=submit/>
249 of 590
Concepts
Session
10
HTML Forms
Datetime-local
This input type is similar to datetime input type, except that the time zone is omitted for input type=datetime-local.
10.4.7 Color
HTML5 provides a predefined interface for selecting the colors using input type=color. The input value from the color input field is a hexadecimal number. For example, #00FF00 represents a hexadecimal RGB color value. At present, the color input type is supported on Opera browser and some new smart phones. Code Snippet 12 shows the usage of color input type to display a color picker on the Web page.
Code Snippet 12: <label>Color:</label> <input type=color name=mycolor /> <input type=submit value=submit/>
Concepts
250 of 590
Session
10
HTML Forms
Earlier, Web developers needed to write JavaScript snippets for performing the validations on the data entered by the users in form fields. HTML5 has provided several new attributes that perform the validations without writing JavaScript snippets for them. These attributes perform the following tasks: Check data provided by users with the regular expression pattern assigned to the fields Inform users with appropriate errors Check that the required fields are not left empty by the users Enable multiple values for the fields, if provided
These attributes can be used to support scripting drawbacks, without actually hard coding them in the Web pages. Browsers that do not understand these new attributes will ignore them.
10.5.1 Required
This is a boolean attribute that informs the browser to submit the form only when the required fields are not left empty by the users. The input type elements, such as button, range, and color cannot be set for required attribute as they have a default value. Different Web browsers such as Opera, Chrome, and Firefox provide different error messages, such as This is a required field, or Please fill out this field for required attribute. Code Snippet 13 shows assignment of required attribute to the name field on the registration form.
Code Snippet 13: <label>Name: <em> <img src=star.jpg width=9 height=10 alt= border=0> </em> </label> <br> <input type=text value= name=first size=8 tabindex=1 <input type=text value= name=last size=14 tabindex=2 required=true/> <input type=submit value=submit/>
251 of 590
Concepts
required =true/>
Session
10
HTML Forms Figure 10.13 shows the message of required attribute in Opera.
10.5.2 Placeholder
This attribute displays a short hint or text inside a form element. This informs the user about what data needs to be entered in that field. The placeholder text toggles, which means it appears in the field and disappears when the user clicks inside the field. Earlier, Web developers provided this functionality through JavaScript snippets which is now done in the browsers with the help of placeholder attribute. At present, all the browsers such as Chrome, Safari, Opera, and Firefox support the placeholder attribute. If the size of the hint exceeds the field size, then use title attribute to describe text for the field. Code Snippet 14 shows the assignment of placeholder attribute to the name field on the registration form.
Code Snippet 14: <label>Name: <img src=required_star.gif height=10px width=10px/></label> <br> <input type=text value= name=first size=8 tabindex=1 required=true placeholder=First Name/>
Concepts
<input type=text value= name=last size=14 tabindex=2 required=true placeholder=Last Name /><br/>
252 of 590
Session
10
HTML Forms
10.5.3 Pattern
This attribute uses regular expressions for validating the fields. The data entered by the user must match with the pattern specified in the regular expression. This helps to limit the input accepted from the user. While including regular expressions through pattern attribute, it informs the users about the excepted pattern for the data. This can be achieved in the current browsers using the title attribute, which is displayed as a tool tip when the users move the pointer over the field. You need to validate a zip code of five numbers on the form. There is no pre-defined input type to restrict the input to numbers of specified length. Thus, pattern attribute can be used to create user-defined check values for the field. Also, a title attribute can be used to customize the error message displayed for the field.
253 of 590
Concepts
Session
10
HTML Forms Code Snippet 15 shows the assignment of pattern attribute to the phone number field on the registration form.
Code Snippet 15: <label>Phone number:<img src=required_star.gif height=10px width=10px/></label> <input type=tel value= size=4 maxlength=5 tabindex=11 required=true placeholder=Codepattern=[+0-9]{1,4} title=Format:(+)99(99)/> <label>-</label> <input type=tel value= size=10 maxlength=12 tabindex=13 required=true placeholder=Number pattern=[0-9]{8,} title=Minimum 8 numbers/>
In the code, [+0-9] pattern indicates that only special character + as well as numbers are allowed. Also, {1, 4} refers to the length of the numbers, that is between 1 and 4. Similarly, {8,} means minimum eight numbers are allowed in the tel input type field. Figure 10.15 shows the message of pattern attribute in Opera.
Concepts
254 of 590
Session
10
HTML Forms
10.5.4 Multiple
This is a boolean attribute that allows multiple values for some input types. This was available only for select input type in the earlier version of HTML. HTML5 allows multiple attribute with input types, such as email and file. If assigned, it allows selection of multiple files, or include several e-mail addresses in the email field separated by comma separator. At present, browsers such as Chrome, Opera, and Firefox support multiple attribute for email and file element. Code Snippet 16 shows the assignment of multiple attribute to the e-mail address field on the registration form.
Code Snippet 16: <label>Email Address:<img src=required_star.gif height=10px width=10px/></label> <input type=email value= tabindex=5 required=true multiple/> name=emailid maxlength=255 placeholder=Email Address
In the code, multiple attribute will allow insertion of multiple e-mail addresses in the field. Every e-mail address will be validated individually by the browser. Figure 10.16 shows the validation of multiple e-mail address.
255 of 590
Concepts
Session
10
HTML Forms
10.5.5 Autofocus
Earlier, Web developers were using JavaScript code to set the focus to the input field on page load. The purpose was to force the focus over the input field, even if the user selected some other element while page is still loading. As a result of the JavaScript code, control moves to the input field upon completion of page load. This way, regardless of what the user selected, the focus would always be on the input field. To provide an easier solution for this behavior, HTML5 has introduced autofocus attribute for the form elements. The autofocus attribute will focus on the input field on page load. However, depending upon the situation, it will not move the focus away if the user has selected some other field. Only one element can be focused with autofocus attribute on a particular page while loading. Code Snippet 17 shows the assignment of autofocus attribute to the first name field on the registration form.
Code Snippet 17: <label>Name:</label> <br> <input type=text value= name=first size=8 tabindex=1 placeholder =First Name autofocus/> <input type=submit value=submit/> <br> <label>First Name</label>
Concepts
256 of 590
Session
10
HTML Forms
10.5.6 Form
Earlier, all the form controls need to be provided between the opening and closing <form> tag. In HTML5, elements can be inserted at any place in the document and they can reference the form using the form attribute. Code Snippet 18 shows the association of an element with the form on the Web page.
Code Snippet 18: <body> <input type=text name=mytext id=mytext form=myform/> . . . . . . <form id=myform> . . . . . . </form> </body>
In the code, the form is declared with an id attribute. The value of the id attribute is assigned to the input element using form attribute.
257 of 590
Concepts
Session
10
HTML Forms Figure 10.18 shows the behavior of autocomplete attribute in Chrome.
Figure 10.18: Behavior of Autocomplete Attribute in Chrome Code Snippet 19 demonstrates to disable the default behavior of autocomplete attribute.
Code Snippet 19: E-mail: <input type=email name=email autocomplete=off /> <input type=submit value=submit/>
Concepts
258 of 590
Session
10
HTML Forms
10.6.1 Datalist
Datalist is a form-specific element. It provides a text field with a set of predefined list of options that are displayed in a drop-down list. When the text field receives focus, a list of options is displayed to the user. The <datalist> element is very similar to standard <select> element available in earlier HTML. The only difference in datalist is that it allows the user to enter data of their choice or select from the suggested list of options. The lists of options for the <datalist> element are placed using the option element. Then, the datalist is associated with an input element using the list attribute. The value of the list attribute is the value of id attribute provided with the <datalist> element. The same datalist can be associated with several input fields. At present, only Opera browser provides the support for the datalist. Code Snippet 20 shows the syntax of providing the <datalist> element on the form.
Code Snippet 20: <label> Select the mode of payment: </label> <input type=text name=payment list=paymentlist /> <datalist id=paymentlist> <option value=Cash-on-Delivery> <option value=Net Banking> <option value=Credit Card> <option value=Debit Card> <option value=e-Gift Voucher> </datalist> <input type=submit value=submit/>
In the code, a datalist requires value attribute to be added with the <option> tag. Values nested between the opening and closing <option> tag will not be displayed in the datalist menu.
259 of 590
Concepts
Session
10
HTML Forms Figure 10.19 shows the <datalist> element in Opera.
Figure 10.19: Datalist Element in Opera As shown in figure 10.19, the datalist is displayed with simple text field that shows the suggested list of options in a drop-down list on focus.
10.6.2 Progress
The progress element represents the current status of a task, which gradually changes as the task heads for completion. This is not a form-specific element. For example, when the user downloads any file from a particular Web page, the download task is represented as a progress bar. Code Snippet 21 shows the syntax for providing progress element on the form.
Code Snippet 21:
Concepts
<label> Downloading status: </label> <progress value=35 max=100 ></progress> <input type=submit value=submit/>
In the code, the progress element contains two attributes namely, max and value. The max attribute declares the maximum value for the task to be processed for its completion. V 1.1 Aptech Limited
260 of 590
Session
10
HTML Forms
The value attribute indicates how much task has been processed so far. Figure 10.20 shows the progress element in Opera.
10.6.3 Meter
The meter element represents a measurement scale for a known range. The known range have the definite minimum and maximum values to measure the data on the scale. For example, a meter element can be used to represent measurements, such as disk usage space, fraction value, or significance of a query result. All these have a known maximum value defined for them. The meter element cannot indicate age, height, or weight, as maximum values for them cannot be specified. Code Snippet 22 shows the code of the meter element.
Code Snippet 22: <label> Total score of marks: </label> 0 <meter min=0 max=400 value=180 title=numbers scored low=120 high=300> </meter> 400<br/> <input type=submit value=submit/>
The min and max attribute specifies the minimum and maximum value that sets bounds for the range. The default value for the max attribute is 1. The value attribute specifies the current measured value. The high and low attributes specifies the range of values that can be considered as high or low for the given range.
261 of 590
Concepts
In the code, the meter element contains six attributes that are used to determine the measurements in the known range.
Session
10
HTML Forms For example, in the given range of scores, the range of values below 120 will be considered low, but anything above 300 will be considered as high. There is another attribute named optimum which refers to the ideal value for the measurement. Figure 10.21 shows the meter element in Opera.
10.6.4 Output
The output element displays the results of a calculation on a form. The result values displayed in the output element are processed from the other form elements. For example, the output element might be used to display the total cost on the purchase items after calculating discount amount in a registration form or purchase order form. Code Snippet 23 shows the calculation of data from other form elements to be displayed in the output element.
Code Snippet 23: <form oninput=x.value = parseInt(type.value)* parseInt(duration.value)> <label>Membership Type:</label> <select name=type> <option value=400>Gold - $400</option> <option value=500>Silver - $500</option> <option value=600>Platinum - $600</option> </select>
Concepts
262 of 590
Session
10
HTML Forms
<label>Duration [years]:</label> <input type=number value=0 name=duration min=1max=5 step=1 /> <label> Annual Payment Fees: $.</label> <output name=x for=type duration></output>
In the code, for attribute relates the output element with the elements whose values are taken for calculation. The form oninput event handles the input event which is fired whenever the value of the elements change on receiving input from the user. A JavaScript code can also be written to update the values for the output element. Figure 10.22 shows the result of calculation for output element.
263 of 590
Concepts
Session
10
HTML Forms
2.
Which of the following attribute displays a short hint or text inside a form element? (A) meter (B) type (C) (D) caption placeholder
3.
The ______________ element represents the current status of a task, which gradually changes as the task heads for completion. (A) datalist (B) pattern (C) (D) progress required
4.
Which of the following statements are true about Datalist? (A) Provides a text field with a set of predefined list of options that are displayed in a drop-down list
<datalist> element is very similar to standard <select>
(B) Is a form-specific element element Does not allow the user to enter data of their choice or select from (D) the suggested list of options (C)
Concepts
264 of 590
Session
5.
10
HTML Forms
Which of the following code disables the default behavior of autocomplete attribute?
E-mail: <input type=email name=email (A) autocomplete=on /> <input type=submit value=submit/> E-mail: <input type=email name=email (B) autocomplete=yes /> <input type=submit value=submit/> E-mail: <input type=email name=email/> <input type=submit value=submit/> E-mail: <input type=email name=email (D) autocomplete=off /><input type=submit value=submit/>
(C)
265 of 590
Concepts
Session
10
HTML Forms
10.7.1 Answers
1. 2. 3. 4. 5. B D C A, B, C D
Concepts
266 of 590
Session
10
HTML Forms
Summary
HTML5 provides a great enhancement to Web forms. Creation of form is made easier for Web developers by standardizing them with rich form controls. HTML5 introduces new form elements such as new input types, new attributes, browser-based validation, CSS3 styling techniques, and forms API. HTML5 provides new input types that are data-specific user interface elements such as email, url, number, range, date, tel, and color. The new form elements introduced in HTML5 are namely, datalist, progress, meter, and output. HTML5 has provided several new attributes that performs the validations without writing JavaScript snippets for them. In HTML5, one can use the submit input type for form submission.
267 of 590
Concepts
Session
10
HTML Forms
Try it Yourself
1. Samson works for an advertising agency named Creative Designers which is headquartered at Hong Kong. He is very fond of learning latest technologies that are coming up in the market. He wants to create an HTML5 Web site for his advertising agency. The Web site should display the list of products for sale such as books, computers, vehicles, cameras, laptops, musical instruments, and so on. Only registered users can purchase products from the site. Help him to develop the application.
Concepts
268 of 590
Session
10
HTML Forms (Workshop)
Note - Please refer to the respective lab deliverable for demonstrations and guided
simulations.
Labs
270 of 590
11
Session
11
HTML5 Audio and Video
11.1 Introduction
Traditionally, Web browsers were capable of handling only graphics and text. Suppose, if a user had to play some video, then, a distinct program, plug-in, or an ActiveX control had to be installed. Earlier, Web designers and Web developers used to set up Web pages to play audio and video on the Web using Adobe Flash player.
Container Concepts
Mp4 Ogg WebM
Video Codec
H.264 Theora VP8
Audio Codec
AAC Vorbis Vorbis
272 of 590
Session
11
HTML5 Audio and Video
There are the three supported file formats for the <audio> element in HTML5. Table 11.2 lists the audio file formats supported by the Web browsers.
Browsers Support
Opera 10.6 Apple Safari 5 Google Chrome 6 FireFox 4.0 Internet Explorer 9
MP3
No Yes Yes No Yes
Wav
Yes Yes Yes Yes No
Ogg
Yes No Yes Yes No
Browsers Support
Opera 10.6 Apple Safari 5 Google Chrome 6 FireFox 4.0 Internet Explorer 9
MP4 WebM
No Yes Yes No Yes Yes No Yes Yes No
Ogg
Yes No Yes Yes No
273 of 590
Concepts
Session
11
HTML5 Audio and Video Code Snippet 1 displays the embedding of an audio file in the Web page using the <audio> tag. The music is played in the background when the page is loaded on the browser.
Code Snippet 1: <!DOCTYPE html> <html> <head> <title>audio element</title> </head> <body> <audio src=d:\sourcecodes\audio.mp3 controls autoplay </audio> </body> </html> loop> html5 audio not supported
The src attribute is mandatory, the <audio> tag includes several other options. Figure 11.1 displays the <audio> element.
Concepts
Figure 11.1: <audio> Element The existing HTML5 specification does not specify the formats supported by the browser in the <audio> tag. The audio formats frequently used are wav, ogg, and mp3.
274 of 590
Session
11
HTML5 Audio and Video
The users can also use the <source> tag to specify the media along with the media type and other attributes. An audio element can contain multiple source elements and the browser will identify the first supported format.
Audio Attributes
Description
This attribute identifies whether to start the audio or not once the object is loaded. The attribute accepts a boolean value which when specified will automatically start playing the audio as soon as possible without stopping This attribute starts the buffering automatically This attribute identifies the audio playback controls that should be displayed such as resume, pause, play, and volume buttons This attribute identifies whether to replay the audio once it has stopped This attribute identifies whether the audio has to be loaded when the page loads and is ready to execute. This preload attribute is ignored if autoplay exists This attribute specifies the location or the URL of the audio file that has to be embedded Table 11.4: <audio> Tag Attributes
275 of 590
Concepts
Session
11
HTML5 Audio and Video Code Snippet 2 demonstrates the use of <embed> tag in the <audio> element.
Code Snippet 2: <!DOCTYPE HTML> <html> <body> <audio autoplay loop> <source src=sampaudio.mp3> <source src=sampaudio.ogg> <embed src=sampaudio.mp3> </audio> </body> </html>
The <audio> element in HTML5 supports multiple formats. The content included within the <embed> tag is automatically played by default. Suppose, if the user does not want to play the audio file automatically then he/she can set the value of the autostart attribute to false. Code Snippet 3 demonstrates the use of the autostart attribute.
Code Snippet 3: <embed src=mpaudio.mp3 autostart=false >
The <embed> tag also supports another attribute named loop. The loop attribute determines whether the audio clip will be replayed continuously or not. If the value of the loop attribute is set to true or infinite then the music will be played continuously. If the loop attribute is not specified then it is same as setting the value to false.
Concepts
276 of 590
Session
11
HTML5 Audio and Video
Code Snippet 4 demonstrates the use of some of the audio formats supported by HTML5.
Code Snippet 4: <!DOCTYPE HTML> <html> <body> <audio controls autoplay> <source src=/https/www.scribd.com/html5/sampaudio.ogg type=audio/ogg /> <source src=/https/www.scribd.com/html5/sampaudio.wav type=audio/wav /> Your browser does not support the <audio> element. </audio> </body> </html>
This code snippet shows the ogg and wav formats supported by the <audio> tag. While adding the <audio> element in the code, the user can specify error messages to check if the browser is supporting the <audio> tag or not.
277 of 590
Concepts
Session
11
HTML5 Audio and Video Code Snippet 5 demonstrates the use of the <video> element.
Code Snippet 5: <!DOCTYPE HTML> <html> <head> </head> <body> <video src=D:\Source codes\movie.mp4> Your browser does not support the video. </video> </body> </html>
In the code, the src attribute is used for specifying the location of the mp4 video file format used by the <video> tag. While adding the <video> element in the code, the user can specify messages between the <video> and </video> tag to check if the browser is supporting the <video> tag or not. Figure 11.2 displays the <video> element.
Concepts
Session
11
HTML5 Audio and Video
The HTML5 specification provides a list of attributes that can be used with the <video> element. Table 11.5 lists the <video> tag attributes.
autoplay muted loop
Description
Specifies that the browser will start playing the video as soon as it is ready Allows to mute the video initially, if this attribute is existing Allows displaying the controls of the video, if the attribute exists Specifies that the browser should repeat playing the existing video once more if the loop attribute exists and accepts a boolean value Specifies whether the video should be loaded or not when the page is loaded Specifies the location of the video file to be embedded Table 11.5: <video> Tag Attributes
controls
preload src
Note - The muted attribute is not supported in Safari and Internet Explorer.
This attribute allows the browser to load only the page. The video will not be downloaded while the page is being loaded.
Metadata
This attribute allows the browser to load the metadata when the page is being loaded.
Auto
This is the default behavior as it allows the browser to download the video when the page is loaded. The browser can avoid the request.
279 of 590
Concepts
Session
11
HTML5 Audio and Video Code Snippet 6 demonstrates the use of none and metadata values for the preload attribute.
Code Snippet 6: <!DOCTYPE HTML> <html> <head>
</head> <video width=160 height=140 src=D:\Source Codes\movie. mp4 Your browser does not support the video. controls preload=none muted> <body>
<video width=160 height=140 src=D:\ Source Codes\movie. mp4 Your browser does not support the video. controls preload=metadata muted>
</video>
</html>
</body>
</video>
In the code, the preload attribute specifies none and metadata values. Figure 11.3 displays the effect of none and metadata values.
Concepts
Session
11
HTML5 Audio and Video
The user can specify the size of the video with the height and width attribute of the <video> element. Suppose, if these attributes are not provided then the browser sets the video with the key dimensions of the video. This will result in changing the page layout as the Web page is adjusted to accommodate the video. Code Snippet 7 demonstrates how to apply the height and width attributes to the <video> element.
Code Snippet 7: <!DOCTYPE HTML> <html> <head> </head> <title> Video Size</title> <style> video{ <body> <video src=D:\Source Codes\movie.mp4 controls preload=auto width=360 height=340> Your browser does not support the video. </video> </body> </html> } </style> background-color: black; border: medium double black;
281 of 590
Concepts
In the code, the style attribute is used to specify the background-color and border style of the video. The code also specifies the preload, height, and width attributes for the <video> element.
Session
11
HTML5 Audio and Video Figure 11.4 displays the width, height, and style effect.
This is an open source, royalty-free, and patent-free format available. This format is supported by browsers such as Opera, Chrome, and Firefox.
WebM
Concepts
This is a royalty-free and patent-free format supported by Google. This format is supported by browsers such as Opera, Chrome, and Firefox. Free WebM Encoder 1.2 is a simple utility that allows you to convert video files to the WebM format.
H.264/MP4
H.264 or MP4 formats are supported on iPhone and Google Android devices. V 1.1 Aptech Limited
282 of 590
Session
11
HTML5 Audio and Video
There is a simple way to encode H.264 is by using the Handbrake. Handbrake is an open-source, GPL-license application and is accessible by using Mac OS X, Windows, and Linux. Handbrake has two versions, command-line and graphical versions. This format is available for free till 2015. This format is supported by browsers such as Internet Explorer, Chrome, and Safari.
Micro Video Controller
This converter creates all files that the user requires for HTML5 <video> element that works on the cross browser.
These assumptions meet the requirements of a vast majority of users accessing the application. However, not all users will fall in this category. Therefore, another set of assumptions are to be considered for these users and they are as follows:
Users who are not familiar with the language that the content is delivered Users who use keyboards and screen readers to access the content on Web
283 of 590
Concepts
Users who have hearing and visual impairment and thus, cannot listen to the audio or view the video
Session
11
HTML5 Audio and Video Users who cannot view or hear the media content because of their working environment or due to device restrictions HTML5 provides powerful features to make applications accessible to such users. WebVTT (Web Video text Tracks) is a file format used to mark up the external text tracks. This format allows the user to give a textual description of the content in the video. This description is then used by different accessibility devices to define the content to those users who cannot see it.
Container
Description
Contains the URL of the text track data Contains the language of the text track data Contains the type of content the track definition is used for Indicates that this will be the default track if the user does not specifies the value Specifies the title to be displayed for the user Table 11.6: Track Element Attributes
srclang kind
default label
Concepts
284 of 590
Session
11
HTML5 Audio and Video
Code Snippet 8 demonstrates how a track element is used in combination with <video> element for providing subtitles.
Code Snippet 8: <video controls> <source src=myvideo.mp4 type=video/mp4> <source src=myvideo.webm type=video/webm> <track src=eng.vtt label=English p subtitles srclang=en > </video> kind=subtitles
This code specifies the src, label, and srclang attributes in the track element. Here, the srclang is set to en that is English language. Code Snippet 9 demonstrates a track element used in combination with <video> element providing subtitles in another language.
Code Snippet 9: <video controls> <source src=myvideo.mp4 type=video/mp4> <source src=myvideo.webm type=video/webm> <track src=de.vtt srclang=de label=German p subtitles kind=subtitles> </video>
This code specifies the src, label, and srclang attributes in the track element. Here, the srclang is set to de which represents French language.
individual controls do not interact with keyboard. The access to keyboard is provided by the Firefox specific shortcuts.
285 of 590
Concepts
Audio Support
Session
11
HTML5 Audio and Video
IE 9 - This browser expose controls with accessibility APIs, however individual
keyboard.
Concepts
286 of 590
Session
11
HTML5 Audio and Video
___________ is a combination of various elements such as video, graphics, sound, and text. (A) Audio (B) Multimedia (C) (D) Video Autoplay
2.
Which of the following element allows the user to enable a native audio file within the Web browser? (A) Audio (B) Text (C) (D) Video Autoplay
3.
_________ is a new open source video container format supported by Google. (A) Flv (B) Ogg (C) (D) Avi WebM
4.
_______________ is the level of ease with which computers can be used and be available to a wide range of users, including people with disabilities. (A) Browser (B) Element (C) (D) Accessibility Autoplay
5.
Which of the following browser supports accessibility for audio and video elements? (A) Firefox (B) IE9 (C) (D) Netscape Navigator Opera
287 of 590
Concepts
Session
11
HTML5 Audio and Video
11.8.1 Answers
1. 2. 3. 4. 5. B A D C A, B, D
Concepts
288 of 590
Session
11
HTML5 Audio and Video
Summary
Multimedia is a combination of various elements such as video, graphics, sound, and text. There are various media types used for audio and video files on different Web sites. The <audio> element will help the developer to embed music on the Web site and allow the user to listen to music. Users can play the audio in older browsers using the <embed> tag. The <video> element is used for embedding the video content on the Web page. Preload attribute identifies whether the audio has to be loaded when the page loads and is ready to execute. WebM is a new open source video container format supported by Google.
289 of 590
Concepts
Session
11
HTML5 Audio and Video
Try it Yourself
1. Julia works for a music online Web site named, Crayon Developers and is headquartered at Tokyo, Japan. The Web site contains the information about the different genre of music such as jazz, opera, rock, and many more. Now, she wants to add the list of newly launched albums to the Web site. She wants to add some audio files to the Web site for the listeners that will create a different impact on the customers. Help her to develop the application. Ching Chow works for an online music company named, MovieBuzz and is headquartered at Yokohama, China. She has created her companys Web site on HTML 4 now she wants to upgrade her companys Web site to HTML5. The Web site contains the information about the latest Hollywood movies and review of the released movies. She wants to add the new movie releases to her collection of movies where the visitors can view some video clips of movies. Help her to develop the application.
2.
Concepts
290 of 590
Session
11
HTML5 Audio and Video (Workshop)
Note - Please refer to the respective lab deliverable for demonstrations and guided
simulations.
Labs
292 of 590
Introduction to JavaScript
This session describes the scripting languages. The session also explores the JavaScript language and versions used in the language. It further describes the variables, data types, methods, built in functions, event handling, and jQuery mobile. In this Session, you will learn to:
Explain scripting Explain the JavaScript language Explain the client-side and server-side JavaScript List the variables and data types in JavaScript Describe the JavaScript methods to display information Explain escape sequences and built in functions in JavaScript Explain events and event handling Explain jQuery Describe how to use the jQuery Mobile
12
Session
12
Introduction to JavaScript
12.1 Introduction
Consider an organization that provides a Web site that allows its customers to view their products. The company has received frequent customer feedbacks to provide the shopping facility online. Therefore, the company has decided to add the shopping facility in their Web site by creating dynamic Web pages. These Web pages will allow the user to shop for the products online. Here, the main task of the developer is to validate the customers inputs while they shop online. For example, details such as credit card number, email, and phone number entered by the customer must be in a proper format. Further, the developer also needs to retrieve the chosen products and their quantity to calculate the total cost. The developer can handle all these critical tasks by using a scripting language. A scripting language refers to a set of instructions that provides some functionality when the user interacts with a Web page. Figure 12.1 displays the need for scripting.
Concepts
294 of 590
Session
12
Introduction to JavaScript
12.2 Scripting
Scripting refers to a series of commands that are interpreted and executed sequentially and immediately on occurrence of an event. This event is an action generated by a user while interacting with a Web page. Examples of events include button clicks, selecting a product from a menu, and so on. Scripting languages are often embedded in the HTML pages to change the behavior of the Web pages according to the users requirements. There are two types of scripting languages. They are as follows:
Client-side Scripting
Refers to a script being executed on a Web server to generate dynamic HTML pages. Figure 12.2 displays the types of scripting.
languages.
JavaScript is a scripting language that allows you to build dynamic Web pages by ensuring maximum user interactivity. JavaScript language is an object-based language, which means that it provides objects for specifying functionalities. In real life, an object is a visible entity such as a car or a table. Every object has some characteristics and is capable of performing certain actions. Similarly, in a scripting language, an object has a unique identity, state, and behavior.
295 of 590
Concepts
12.3 JavaScript
Session
12
Introduction to JavaScript The identity of the object distinguishes it from the other objects of the same type. The state of the object refers to its characteristics, whereas the behavior of the object consists of its possible actions. The object stores its identity and state in fields (also called variables) and exposes its behavior through functions (actions). Figure 12.3 displays the objects.
Version
1.1 1.2 1.3
Description
Is supported from 3.0 version of the Netscape Navigator and Internet Explorer Is supported by the Internet Explorer from version 4.0 Is supported by the Internet Explorer from version 5.0, Netscape Navigator from version 4.0, and Opera from version 5.0 Is supported by servers of Netscape and Opera 6 Is supported by the Internet Explorer from version 6.0, Netscape Navigator from version 6.0, and Mozilla Firefox from version 1.0
Concepts
1.4 1.5
296 of 590
Session
1.6
12
Introduction to JavaScript
Version
Description
Is supported in the latest versions of the Internet Explorer and Netscape Navigator browsers. It is also supported by Mozilla Firefox from version 1.5 Is supported in the latest versions of the Internet Explorer and Netscape Navigator browsers. It is also supported by Mozilla Firefox from version 2.0 Table 12.1: Various Versions of JavaScript Language
1.7
Note - The latest version, JavaScript 2.0, is into the development phase.
297 of 590
Concepts
Session
12
Introduction to JavaScript
Concepts
298 of 590
Session
12
Introduction to JavaScript
The <script> tag defines a script for an HTML page to make them interactive. The browser that supports scripts interprets and executes the script specified under the <script> tag when the page loads in the browser. You can directly insert a JavaScript code under the <script> tag. You can define multiple <script> tags either in the <head> or in the <body> elements of an HTML page. In HTML5, the type attribute specifying the scripting language is no longer required as it is optional. Code Snippet 1 demonstrates the use of the <script> tag.
Code Snippet 1: <!DOCTYPE html> <html> <head> <script> document.write(Welcome to the Digital World); </script> </head> <body> ... </body> </html>
There are two main purposes of the <script> tag, which are as follows: Identifies a given segment of script in the HTML page Loads an external script file
A variable refers to a symbolic name that holds a value, which keeps changing. For example, age of a student and salary of an employee can be treated as variables. A real life example for variables includes the variables used in algebraic expressions that store values. In JavaScript, a variable is a unique location in the computers memory that stores a value and has a unique name. The name of the variable is used to access and read the value stored in it. A variable can store different types of data such as a character, a number, or a string. Therefore, a variable acts as a container for saving and changing values during the execution of the script.
Session
12
Introduction to JavaScript
Figure 12.6: Declare Variables The syntax demonstrates how to declare variables in JavaScript.
Syntax: var <variableName>;
where,
var: Is the keyword in JavaScript. variableName: Is a valid variable name.
Concepts
where,
=: Is the assignment operator used to assign values.
300 of 590
Session
12
Introduction to JavaScript
The syntax demonstrates how to declare and initialize multiple variables in a single statement, which are separated by commas.
Syntax: var <variableName1> = <value1>, <variableName2> = <value2>;
Code Snippet 2 declares two variables namely, studID and studName and assign values to them.
Code Snippet 2: var studID; var studName; studID = 50; studName = David Fernando;
This code assigns values to studID and studName variables by using the assignment operator (=). The value named David Fernando is specified within double quotes. Code Snippet 3 demonstrates how to declare and initialize multiple variables in a single statement in JavaScript.
Code Snippet 3: var studName = David, studAge = 15;
Can consist of digits, underscore, and alphabets. Must begin with a letter or the underscore character. Cannot begin with a number and cannot contain any punctuation marks. Cannot contain any kind of special characters such as +, *, %, and so on. Cannot contain spaces. Cannot be a JavaScript keyword.
301 of 590
Concepts
Session
12
Introduction to JavaScript It is recommended to give meaningful names to variables such that the name determines the kind of data stored in the variable.
Description
Contains only two values namely, true or false Contains only one value namely, null. A variable of this value specifies that the variable has no value. This null value is a keyword and it is not the same as the value, zero Contains positive and negative numbers and numbers with decimal point. Some of the valid examples include 6, 7.5, -8, 7.5e-3, and so on Contains alphanumeric characters in single or double quotation marks. The single quotes is used to represent a string, which itself consists of quotation marks. A set of quotes without any characters within it is known as the null string Table 12.2: Primitive Data Types
number string
Concepts
302 of 590
Session
12
Introduction to JavaScript
Description
Refers to a collection of properties and functions. Properties specify the characteristics and functions determine the behavior of a JavaScript object Refers to a collection of statements, which are instructions to achieve a specific task Refers to a collection of values stored in adjacent memory locations Table 12.3: Composite Data Types
Functions Arrays
12.10 Methods
JavaScript allows you to display information using the methods of the document object. The document object is a predefined object in JavaScript, which represents the HTML page and allow managing the page dynamically. Each object in JavaScript consists of methods, which fulfills a specific task. There are two methods of the document object, which displays any type of data in the browser. These methods are as follows:
write(): Displays any type of data. writeln(): Displays any type of data and appends a new line character.
The syntax demonstrates the use of document.write()method, which allows you to display information in the displayed HTML page.
Syntax: document.write(<data> + variables);
where,
data: Specifies strings enclosed in double quotes. variables: Specify variable names whose value should be displayed on the HTML
page.
303 of 590
Concepts
The syntax demonstrates the use of document.writeln() method, which appends a new line character.
Session
12
Introduction to JavaScript Code Snippet 4 demonstrates the use of write() method.
Code Snippet 4: <!DOCTYPE HTML> <html> <head> <title> JavaScript language </title> <script> document.write(<p> JavaScript:); document.writeln(is a scripting); document.write(and a case-sensitive language.); </script> </head> <p> JavaScript: is a scripting and a case-sensitive language. </p> </html>
The code uses the writeln() method to display the text after the colon without leaving a space. It finally appends a new line character after the text. Then, the text within the write() method is displayed on the same line after leaving a space. The same paragraph is displayed in the body of the HTML page. Note that the text in the p element appears on different lines. In HTML, the text on the second line, and a case sensitive language will not be displayed in the new line in the browser even though the ENTER key is pressed while writing the code. Rather, it will be displayed on the same line with a space. The writeln() method also follows this same format. Figure 12.7 displays the use of write() and writeln() methods.
Concepts
Session
12
Introduction to JavaScript
A Web page designer might code complex script to fulfill a specific task. In JavaScript, a Web page designer specifies comments to provide information about a piece of code in the script. Comments describe the code in simple words so that somebody who reads the code can understand the code. Comments are small piece of text that makes the program more readable. While the script is executed, the browser can identify comments as they are marked with special characters and do not display them. JavaScript supports two types of comments. These are as follows:
Single-line Comments
Single-line comments begin with two forward slashes (//). You can insert single-line comments as follows:
// This statement declares a variable named num. var num; Multi-line Comments
Multi-line comments begin with a forward slash followed by an asterisk (/*) and end with an asterisk followed by a forward slash (*/). You can insert multiple lines of comments as follows:
/* This line of code declares a variable */ var num;
305 of 590
Concepts
Session
12
Introduction to JavaScript Table 12.4 lists the escape sequence characters.
\b \f \n \r \t \ \ \\ \aaa \xaa \uaaaa
Escape Sequence
Non-Printing Character
Back space Form feed New line Carriage return Horizontal tab Single quote Double quote Backslash Matches a Latin-1 encoding character using octal representation, where aaa are three octal numbers. For example, \251 represents the copyright symbol Matches a Latin-1 encoding character using hexadecimal representation, where aa are two hexadecimal numbers. For example, \x61 represents the character a Represent the Unicode encoding character, where aaaa are four hexadecimal numbers. For example, the character \ u0020 represents a space Table 12.4: Escape Sequence Characters
The code uses a Unicode encoding character namely, \u0022, which represents double quotes. These open and close double quotes will contain the term credit card. Similarly, the word Internet will be placed in single quotes. The single quotes are specified using the backslash character.
Concepts
Note - An encoding scheme specifies how to represent character data in terms of their
acceptable range, maximum number of characters, and patterns. Unicode is a character set that contains all the international characters required for processing information. Latin 1 is the encoding scheme for English and Western European languages on the Internet.
306 of 590
Session
12
Introduction to JavaScript
A function is a piece of code that performs some operations on variables to fulfill a specific task. It takes one or more input values, processes them, and returns an output value. JavaScript provides built-in functions that are already defined to fulfill a certain task. Table 12.5 lists the built-in functions.
alert()
Function
fill Displays a dialog box with alert(Please all the fields of the some information and OK form); button
Description
Example
confirm()
Displays a message box with the instruction Displays a dialog box with OK and Cancel buttons. It verifies an action, which a user wants to perform Converts a string value into a numeric value Converts a string into a number with decimal point Evaluates an expression and returns the evaluated result Checks whether a value is not a number Displays a dialog box that accepts an input value through a text box. It also accepts the default value for the text box.
Returns 10.33
eval(2+2);
Returns 4
isNan(Hello);
Returns true
your
Displays the message in the dialog box and Name in the text box.
307 of 590
Concepts
Note - The \n character, when used in the alert() function, prints the information on a new line. This does not happen when the \n character is used with the write methods of the document object.
Session
12
Introduction to JavaScript Code Snippet 6 demonstrates the use of some of the built-in functions in JavaScript. It performs the addition operation using JavaScript.
Code Snippet 6: <!DOCTYPE HTML> <html> <head> <title> JavaScript language </title> <script> var value = ; var numone = prompt(enter first value to perform the multiplication operation, value); document.write(The result of multiplying: + numone + and + numtwo + is: + result + . ); </script> </head> </html> var numtwo = prompt(enter second value to perform the multiplication operation, value); var result = eval(numone * numtwo);
In the code, it takes the first value from the user and stores in the numOne variable. Then, it takes the second value from the user and stores in the numTwo variable. It multiplies the values and stores the output in the result variable and then displays the output on the Web page.
Concepts
308 of 590
Session
12
Introduction to JavaScript
Figure 12.8: Input First Number Figure 12.9 displays the input second number.
Figure 12.9: Input Second Number Figure 12.10 displays the result.
309 of 590
Concepts
Session
12
Introduction to JavaScript
12.14 Events
Consider a scenario where you want to design an Employee registration Web form. This form allows the users to fill in the appropriate details and click the submit button. When the user clicks the submit button, the form data is submitted to the server for validation purposes. In this case, when the user clicks the button, an event is generated. The submission of form refers to the action performed on click of the button. An event occurs when a user interacts with the Web page. Some of the commonly generated events are mouse clicks, key strokes, and so on. The process of handling these events is known as event handling. Figure 12.11 displays the event.
Concepts
It specifies the event state, which includes information such as the location of mouse cursor, element on which an event occurred, and state of the keys in a keyboard.
310 of 590
Session
12
Introduction to JavaScript
311 of 590
Concepts
Session
12
Introduction to JavaScript
Concepts
312 of 590
Session
12
Introduction to JavaScript
Code Snippet 7 demonstrates how to create a JavaScript code that defines the event handlers.
Code Snippet 7: function numericonly() { if(!event.keyCode >=48 && event.keyCode<=57)) event.returnValue=false; } function countWords() { var message = document.getElementByID(txtMessage).value; message= message.replace(/\s+/g, ); var numberOfWords = message.split( ).length; document.getElementById(txtTrack).value = words Remaining: + eval(50 - numberOfWords); if(numberOfWords > 50) alert(too many words.); }
In the code, the function numericOnly()declares an event handler function, numericOnly(). The event.keyCode checks if the Unicode character of the entered key is greater than 48 and less than 57. This checks that only numeric values are entered. It also declares an event handler function, countWords(). It retrieves the text specified in the txtMessage control. split()function splits the specified string when a space is encountered and returns the length after splitting. It also calculates and displays the number of remaining words to complete the count of 50 words. If the number of words is greater than 50, an alert box is displayed.
onmousedown onmouseup
313 of 590
Concepts
Mouse events occur when the user clicks the mouse button. Table 12.6 lists the mouse events.
Session
12
Introduction to JavaScript
onclick
Events
Description
Occurs when the mouse button is pressed and released Occurs when the mouse button is double-clicked Occurs when the mouse pointer is moved from one location to other Occurs when the mouse pointer is moved over the element Occurs when the mouse pointer is moved out of the element Table 12.6: Mouse Events
Concepts
314 of 590
Session
12
Introduction to JavaScript
</tr> <tr> <td> Departure Date: </td> <td> <input id=txtDeparture type=text /></td> </tr> <tr> <td> Number of Person: </td> <td> <input id=txtPerson type=text maxlength=3 size=3></td> </tr> <tr> <td> <img id=imgSubmit width=120px height=30px src=submit.jpg alt=Submit, onmousedown=showImage(this, submitdown.jpg); onmouseup=showImage(this, submit.jpg);,onclick=frmReservation.submit();/> </td> <td> <img id=imgSubmit width=120px height=30px src=reset.jpg alt=Reset, onmousedown=showImage(this, resetdown.jpg); onmouseup=showImage(this, reset.jpg);,onclick=frmReservation.reset();/> </td> </tr> </table> </form> </body>
</html>
315 of 590
Concepts
Session
12
Introduction to JavaScript It will also display the submit.jpg image when the mouse is released from Submit button. It also submits the form data when the Submit button is clicked. Further it displays the image when Reset button is clicked and it displays the reset.jpg image when the mouse is released from Reset button. It will reset the form data when the Reset button is clicked. Code Snippet 9 demonstrates the loading of images in a JavaScript file.
Code Snippet 9: function showImage(object,url) { object.src=url; }
Concepts
316 of 590
Session
12
Introduction to JavaScript
Events
Description
Occurs when an element receives focus Occurs when an element loses focus Occurs when the selection of an element starts Occurs when the present selection changes Occurs when the selected element is moved
317 of 590
Concepts
Session
12
Introduction to JavaScript Code Snippet 10 demonstrates the use of focus and selection events.
Code Snippet 10: <!DOCTYPE HTML> <html> <head> <title> Reservation </title> <script> function showStyle(field) { field.style.backgroundColor = #FFFFCC; } function hideStyle(field) { field.style.backgroundColor = #FFFFFF; } function setFontStyle(field) { field.style.fontWeight = bold; field.style.fontFamily = Arial; }
</script> </head> <body> <h2> Feedback Form</h2> <form id=frmreservation> <table> <tr> <td> <label for=txtName>Name:</label></td> <td> <input id=txtName type=text onfocus=showStyle(this ); onblur=hideStyle(this); onselect=setFontStyle( this); />
Concepts
318 of 590
Session
</td> </tr> <tr>
12
Introduction to JavaScript
<td> <label for=txtEmail>E-mail:</label></td> <td> <input id=txtEmail type=text onfocus=showStyle(this); onblur=hideStyle(this); onselect=setFontStyle(this); /> </td> </tr> <tr> <td> <label for=txtComment>Comment:</label></td> <td> <textarea id=txtComment cols=15 rows=3 onfocus=showStyle(this); onblur=hideStyle(this); onselect=setFontStyle(this);> </textarea> </td> </tr> <tr> <td> <input id=btnSubmit type=button type=button value=Submit /></td> <td> <input id=btnReset type=reset /></td> </tr> </table> </form> </body> </html>
319 of 590
Concepts
In the code, a specified style is displayed when the element receives and loses focus. It also displays the specified font style when the element is selected. It also declares an event handler function and specifies the background color for the field. It sets the font style for text to bold and the text should appear in Arial font.
Session
12
Introduction to JavaScript Figure 12.16 displays the focus and selection events.
12.15 jQuery
jQuery is a short and fast JavaScript library developed by John Resig in 2006 with a wonderful slogan: Write less and do more. It simplified the client side scripting of HTML. jQuery also simplifies HTML files animation, event handling, traversing, and developing AJAX based Web applications. It helps in rapid Web application development. jQuery is designed for simplifying several tasks by writing lesser code. The following are the key features supported by jQuery:
Event Handling: jQuery has a smart way to capture a wide range of events, such
as user clicks a link, without making the HTML code complex with event handlers.
Concepts
Animations: jQuery has many built-in animation effects that the user can use while
DOM Manipulation: jQuery easily selects, traverses, and modifies DOM by using
320 of 590
Session
12
Introduction to JavaScript
Cross Browser Support: jQuery has a support for cross-browser and works well
Internet Explorer 6 and above Firefox 2.0 and above Safari 3.0 and above Chrome Opera 9.0 and above
Lightweight: jQuery has a lightweight library of 19 KB size. AJAX Support: jQuery helps you to develop feature-rich and responsive Web sites
Latest Technology: jQuery supports basic XPath syntax and CSS3 selectors.
The user can include jQuery library in their file. Code Snippet 11 shows how to use a jQuery library.
Code Snippet 11: <!DOCTYPE HTML> <html> <head> <title>The jQuery Example</title> // Using jQuery library // The user can add our JavaScript code here </script> <script src=jquery-1.7.2.min.js>
321 of 590
Concepts
Session
12
Introduction to JavaScript
</head> <body> </body> </html>
Concepts
322 of 590
Session
12
Introduction to JavaScript
<div id=firstdiv> Click on the text to view a dialog box. </div> </body> </html>
The code includes the jQuery library and also registers the ready event for the document. The ready event contains the click function that calls the click event. Figure 12.17 displays the output of jQuery.
This framework is easy to use and allows developing Web pages by using markup driven with minimum or no JavaScript.
323 of 590
Concepts
Session
12
Introduction to JavaScript
Accessibility
The framework supports Accessible Rich Internet Applications (ARIA) that helps to develop Web pages accessible to visitors with disabilities.
Enhancements and Degradation
The jQuery mobile is influenced by the latest HTML5, JavaScript, and CSS3.
Themes
This framework provides themes that allow the user to provide their own styling.
Smaller Size
The size for jQuery mobile framework is smaller for CSS it is 6KB and for JavaScript library it is 12KB. For executing the jQuery mobile, you have to download the Opera Mobile Emulator from the http://www.opera.com/developer/tools/mobile/ Web site. Download the emulator and install it on your machine and then write the code in the Coffee cup editor. Code Snippet 13 shows an example of a jQuery mobile.
Code Snippet 13: <!DOCTYPE html> <html> <head> <title>Page Title</title> <link rel=stylesheet href=jquery.mobile-1.0a3.min.css /> <script src=jquery-1.5.min.js></script> <script src=jquery.mobile-1.0a3.min.js></script> </head> <body> <div data-role=page> <div data-role=header> <h1>Car Rental</h1> </div> <div data-role=content>
Concepts
324 of 590
Session
12
Introduction to JavaScript
<p>Choose from the listed car models</p> <ul data-role=listview data-inset=true> <li><a href=#>Ford</a></li> <li><a href=#>Ferrari</a></li> <li><a href=#>BMW</a></li> <li><a href=#>Toyota</a></li> <li><a href=#>Mercedes-Benz</a></li> </ul> </div> <div data-role=footer> <h4>© DriveCars 2012.</h4> </div> </div> </body> </html>
The jQuery mobile application should have the following three files: CSS file jQuery library jQuery Mobile library
In the code, three files are included the CSS (jquery.mobile-1.0a3.min. css), jQuery library (jquery-1.5.min.js), and the jQuery mobile library (jquery.mobile-1.0a3.min.js). A user can also download the jQuery libraries from http://code.jquery.com/ Web site. The jQuery Mobile takes HTML tags and renders them on mobile devices. To work with this, HTML has to make use of data attributes. jQuery use these attributes as indicators for rendering it on the Web pages. jQuery also looks for div using a particular data-role values such as page, content, header, and footer are used in this code. There are multiple div blocks added to the code for page, content, header, and footer. Similarly, to display the different car models a data-role listview is added to enhance the look and feel of the mobile Web page. A user need to install the Opera Mobile Emulator from the Opera Web site.
325 of 590
Concepts
Session
12
Introduction to JavaScript After installing the Opera Mobile Emulator, perform the following steps to apply settings to the emulator: 1. 2. 3. 4. 5. Select All Programs Opera Mobile Emulator Opera Mobile Emulator. The Opera Mobile Emulator dialog box will be displayed. In the Profile tab, select the Samsung Galaxy Tab. In the Resolution drop-down, select the WVGA Portrait(480x800). Click Update. Click Launch. The Samsung Galaxy tab is displayed.
For executing the jQuery mobile code given in Code Snippet 12 in the CoffeeCup editor, perform the following steps: 1. Add the Opera Mobile Emulator in the CoffeeCup editor by clicking Tools Additional Browsers Test with Additional Browser 1 and give the location of the Opera Mobile Emulator installed on your system. After adding the emulator, you can see the emulator added to the additional browsers list. Open the jQuery file in the CoffeeCup editor and save. Click Tools Additional Browser Test with Additional Browser 1. Figure 12.18 displays the Opera Mobile Emulator.
2. 3.
Concepts
Session
12
Introduction to JavaScript
______________ is a scripting language, which can be executed on the client-side and on the server-side. A client-side JavaScript (CSJS) is executed by the browser on the users workstation. (A) Java (B) VBScript (C) (D) jQuery JavaScript
3.
The __________________ tag defines a script for an HTML page to make them interactive. (A) <script> (B)
<head>
(C) (D)
<title> <html>
4.
Which of the following is a piece of code that performs some operations on variables to fulfill a specific task? (A) Code (B) Script (C) (D) Function Variable
5.
Which of the following is a process of specifying actions to be performed when an event occurs? (A) Event Handling (B) Event Bubbling (C) (D) Scripting Function
327 of 590
Concepts
Session
12
Introduction to JavaScript
12.17.1 Answers
1. 2. 3. 4. 5. A, D D A C A
Concepts
328 of 590
Session
12
Introduction to JavaScript
Summary
Scripting refers to a series of commands that are interpreted and executed sequentially and immediately on an occurrence of an event. JavaScript is a scripting language, which can be executed on the client-side and on the server-side. A client-side JavaScript is executed by the browser on the users workstation. A variable refers to a symbolic name that holds a value, which keeps changing. A primitive data type contains a single literal value such as a number or a string. A function is a piece of code that performs some operations on variables to fulfill a specific task. Event handling is a process of specifying actions to be performed when an event occurs. Event bubbling is a mechanism that allows you to specify a common event handler for all child elements. jQuery mobile is a Web User Interface development framework that allows the user to build mobile Web applications that works on tablets and smartphones.
329 of 590
Concepts
Session
12
Introduction to JavaScript
Try it Yourself
1. Joaquina works for an online shopping Web site named, Zambia Developers and is headquartered at Tokyo, Japan. She has created a Web site on HTML5. The Web site contains a registration form where the customer has to enter their details. Joaquina wants to add some validations on the registration form so that the details entered by the customers are in a proper format such as the name, mobile number, and so on. So she has decided to add JavaScript code for validation of the data present in Web site. Help her to develop the application. Robert is working for Jazz Developers Private Ltd. located at Washington, USA. He has worked on many mobile projects. Recently, their company has received an order for creating mobile application for online shopping Web site. The Web site should be created in such a manner that it is accessible by all mobile devices so that the customer can order the products online. Robert has decided to create the application using jQuery with HTML5. Help him to develop the application.
2.
Concepts
330 of 590
Session
12
Introduction to JavaScript (Workshop)
Note - Please refer to the respective lab deliverable for demonstrations and guided
simulations.
Labs
332 of 590
13
Session
13
Operators and Statements
13.1 Introduction
An operator specifies the type of operation to be performed on the values of variables and expressions. JavaScript provides different types of operators to perform simple to complex calculations and evaluations. Certain operators are also used to construct relational and logical statements. These statements allow implementing decision and looping constructs.
Concepts
Arithmetic operators Relational operators Logical operators Assignment operators V 1.1 Aptech Limited
334 of 590
Session
13
Operators and Statements
Arithmetic Operator
+ (Addition) - (Subtraction) / (Division) % (Modulo) * (Multiplication)
Description
Performs addition. In case of string values, it behaves as a string concatenation operator and appends a string at the end of the other Performs subtraction. If a larger value is subtracted from a smaller value, it returns a negative numeric value Divides the first operand by the second operand and returns the quotient Divides the first operand by the second operand and returns the remainder Multiplies the two operands Table 13.1: Arithmetic Operators
Example
45 + 56
76-78
24 / 8 90 % 20 98 * 10
Code Snippet 1 calculates the loan interest and the total loan amount to be repaid by using the arithmetic operators.
Code Snippet 1: <script> var loanAmount = 34500; var interest = 8; var interestAmount, totalAmount;
335 of 590
Concepts
Session
13
Operators and Statements The code uses the arithmetic operators * and / to calculate the interest amount. This interest amount is then added to the total amount by using the + operator. The write() method displays the total amount to be repaid on the loan.
Expression
Type
Pre-increment Post-increment Pre-decrement Post-decrement
Result
Table 13.2: Increment and Decrement Operators Code Snippet 2 demonstrates the use of unary operators in JavaScript.
Code Snippet 2: <script> var number = 3; alert(Number after increment = + ++number); alert(Number after decrement = + number--); </script>
Concepts
The first alert() function will display the incremented value of the number variable. This is because in the first statement, ++ operator is evaluated first, and then the incremented value is substituted in the variable number. The second alert() function will not display the decremented value of the number variable. This is because the current value is first assigned to the variable, and then the -- operator is evaluated.
336 of 590
Session
13
Operators and Statements
The expression consisting of a relational operator is called as the relational expression or conditional expression. Table 13.3 lists the relational operators along with their descriptions and an example of each type.
Relational Operator
== (Equal)
Description
Example
90 == 91 99 != 98 3 === 4 3 !== 3 97 > 95 94 < 96 92 >= 93 99 <= 100
Verifies whether the two operands are equal != (Not Equal) Verifies whether the two operands are unequal === (Strict Equal) Verifies whether the two operands are equal and whether are of the same type !== (Strict Not Equal) Verifies whether the two operands are unequal and whether are not of the same type > (Greater Than) Verifies whether the left operand is greater than the right operand < (Less Than) Verifies whether the left operand is less than the right operand >= (Greater Than or Verifies whether the left operand is greater Equal) than or equal to the right operand <= (Less Than or Equal) Verifies whether the left operand is less than or equal to the right operand Table 13.3: Relational Operators
Code Snippet 3 compares the value of the firstNumber variable with the value of the secondNumber variable using relational operators.
Code Snippet 3: <script> var firstNumber = 3; var secondNumber = 4; document.write(First number is greater number: + (firstNumber > secondNumber)); than the than second the
document.write(<br/>First number is less second number: + (firstNumber < secondNumber)); number: + (firstNumber == secondNumber)); </script>
337 of 590
Concepts
Session
13
Operators and Statements In the code, each condition is evaluated to return a boolean value. The alert() function displays the boolean value as true or false.
Logical Operator
&& (AND)
Description
Example
! (NOT) || (OR)
Returns true, if either of the operands are (x == 2) && evaluated to true. If first operand evaluates to (y == 5) true, it will ignore the second operand Returns false Returns false, if the expression is true and !(x == 3) vice-versa Returns true Returns true, if either of the operands are (x == 2) || (y == 5) evaluated to true. If first operand evaluates to Returns true true, it will ignore the second operand Table 13.4: Logical Operators
Code Snippet 4 shows the script that uses logical AND operator to check whether the value of name and age variables are John and 23.
Code Snippet 4: <script> var name = John; var age = 23; alert(John\s age is greater than or equal to 23 years : + ((name==John) && (age >= 23))); </script>
The code declares and initializes two variables namely, name and age to John and 23 respectively. In the alert() function, the logical AND operator checks whether the value of the name variable is John and the value of the age variable is 23. Here, both the expressions are true and therefore, the operator will return true, which will be displayed in the message box to the user.
Concepts
338 of 590
Session
13
Operators and Statements
Assignment operator assign the value of the right side operand to the operand on the left side by using the equal to operator (=). The assignment operator is divided into two categories in JavaScript that is as follows:
Simple assignment operator - Is the = operator which is used to assign a value or result of an expression to a variable. For example, result = numOne + numTwo; Compound assignment operator - Is formed by combining the simple assignment operator with the arithmetic operators. For example, salary -= eval(salary * tax / 100);
Table 13.5 demonstrates the use of assignment operator by assuming the value of the variable numOne as 6.
numOne += 6; numOne -= 6; numOne *= 6; numOne %= 6; numOne /= 6;
Expression
Description
numOne = numOne + 6 numOne = numOne 6 numOne = numOne * 6 numOne = numOne % 6 numOne = numOne / 6 Table 13.5: Assignment Operator
Result
Bitwise operators
& (Bitwise AND) ~ (Bitwise NOT) | (Bitwise OR)
Description
Compares two bits and returns 1 if both of them are 1 or else returns 0
Example
a&b Returns 8 (00001000) ~a
Inverts every bits of the operand, changes its sign and subtracts by 1. Returns -10 It is a unary operator Compares two bits and returns 1 if a|b the corresponding bits of either or Returns 15 (00001111) both the operands is 1
339 of 590
Concepts
Session
13
Operators and Statements
Bitwise operators
^ (Bitwise XOR)
Description
Compares two bits and returns 1 if the corresponding bit of either, but not both the operands is 1 Table 13.6: Bitwise Operators
Example
a^b Returns 7 (00000111)
Code Snippet 5 demonstrates the working of the bitwise AND and OR operator in JavaScript.
Code Snippet 5: //(56 = 00111000 and 28 = 00011100) alert (56 + & + 28 + = + (56 & 28)); //(56 = 00111000 and 28 = 00011100) alert (56 + | + 28 + = + (56 | 28));
In the code, the bitwise AND operator performs the comparison operation on the corresponding bits of the two operands. It returns 1, if both the bits in that position are 1. The result of these comparisons is an 8-bit binary number, which is automatically converted into integer. This integer is displayed as the output which is 24. Similarly, the bitwise OR operator performs the comparison operation on the corresponding bits of the two operands. It returns 1, if either of the bits or both the bits in that position is 1. The result of these comparisons is an 8-bit binary number, which is automatically converted into integer. This integer is displayed as the output which is 60. Code Snippet 6 demonstrates the working of the bitwise XOR and NOT operators in JavaScript.
Code Snippet 6: //(56 = 00111000 and 28 = 00011100) alert (56 + ^ + 28 + = + (56 ^ 28)); //(28 = 00011100) alert (~ + 28 + = + (~28));
Concepts
In the code, the bitwise XOR operator performs the comparison operation on the corresponding bits of the two operands. It returns 1, if only 1 of the bits in that position is 1. The result of these comparisons is an 8-bit binary number, which is automatically converted into integer. This integer is displayed as the output that is 36. Similarly, the bitwise NOT operator inverts each bit, which results in an 8-bit binary number. This binary number automatically converts into integer. This integer is displayed as the output which is -29.
340 of 590
Session
13
Operators and Statements
There are some operators in JavaScript which do not belong to any of the categories of JavaScript operators. Such operators are referred to as the special operators. Table 13.7 lists the most commonly used special operators in JavaScript.
Special Operator
, (comma) ?: (conditional)
Description
Combines multiple expressions into a single expression, operates on them in the left to right order and returns the value of the expression on the right Operates on three operands where the result depends on a condition. It is also called as ternary operator and has the form condition, ? value1:value2. If the condition is true, the operator obtains value1 or else obtains value2 Returns a string that indicates the type of the operand. The operand can be a string, variable, keyword, or an object Table 13.7: Special Operators
typeof
Code Snippet 7 demonstrates the use of special operators to validate the age of a person for voting.
Code Snippet 7: <script> var age = parseInt(prompt(Enter age, Age)) status = ((typeof(age) == number && (age >= 18)) ?eligible : not eligible; document.write(You are + age + years old, so you are +status + to vote.); </script>
341 of 590
Concepts
In the code, the prompt() function accepts the value from the user. The value is converted into an integer and is stored in the age variable. The conditional operator specifies a condition before ? symbol. The condition checks whether the value of the variable age is a number and whether it is greater than equal to 18. If both these expressions return true, the value eligible is assigned to the status variable. Otherwise, the value not eligible is assigned to the status variable. The alert() function displays the final output as whether the user is eligible for voting or not eligible.
Session
13
Operators and Statements Figure 13.1 shows the prompt box in which a user enters the value 19 for the age variable.
Figure 13.1: Output Prompt Box Accepting Value Figure 13.2 displays the output indicating that the user is eligible for voting.
Concepts
342 of 590
Session
13
Operators and Statements
Table 13.8 lists the precedence of the operators from the highest to the lowest and their associativity.
Precedence Order 1 2 3 4 5 6 7 8 9 10 11
Operator
() ++, --
Description
Parentheses
Associativity
Left to Right
Post-increment and Not Applicable Post-decrement operators typeof, ++, -- Pre-increment and Pre-decrement Right to Left , -, ~, ! operators, Logical NOT, Bitwise NOT, and Unary negation *, /, Multiplication, Division, and Left to Right Modulo +, Addition and Subtraction Left to Right
<, <=, >, >= ==, !== &, || ?:
Less than, Less than or equal, Greater than, and Greater than or equal ===, !=, Equal to, Strict equal to, Not equal to, and Strict not equal to |, ^, &&, Bitwise AND, Bitwise OR, Bitwise XOR, Logical AND, and Logical OR Conditional operator
Left to Right
Left to Right Left to Right Right to Left Right to Left Left to Right
Table 13.8: Precedence of Operators Code Snippet 8 demonstrates the evaluation of an expression based on its operators precedence.
Code Snippet 8: <SCRIPT> var numOne = 96, numTwo = 45, numThree = 200; var result; alert(The result is: + result); </SCRIPT> result = 2 * (numThree - numOne + numTwo);
In the code, operators such as *, -, and + are being used to form the expression. According to the rules of operator precedence, parentheses alter the order of evaluation.
343 of 590
Concepts
Session
13
Operators and Statements Thus, the expression within parentheses is evaluated first and its result is used to evaluate the remaining expression. Since, the + and operators have same precedence, therefore, the expression within parentheses is evaluated from left to right. Then, the outcome of the expression is multiplied with the value 2 and assigned to the variable result. Figure 13.3 shows the result of the evaluated expression.
A literal refers to a static value. Therefore, a literal syntax allows specifying a fixed pattern, which is stored in a variable. This method of specifying patterns is useful when the Web page designer knows the pattern at the time of scripting. The syntax to specify the literal syntax is as follows:
Syntax:
Concepts
where,
regular_expression_pattern: Is a string pattern. variable_name: Is the name of the variable which stores the pattern.
344 of 590
Session
13
Operators and Statements
Code Snippet 9 shows the use of literal syntax to create a regular expression pattern.
Code Snippet 9: <SCRIPT> var ageFormat = /^\d{2}$/; </SCRIPT>
In the code, to match a 2-digit number, the ageFormat variable is declared. The variable stores the literal pattern. The pattern starts and ends with the forward slashes. The ^ character denotes the starting position of a string, \d{2} represents two digits, and $ character denotes the end of a string. This means that the string must contain only two digits to represent a valid age value.
RegExp() Constructor
The RegExp() constructor is useful when the Web page designer does not know the pattern at the time of scripting. This means that the method dynamically constructs a regular expression when the script is executed. The RegExp() constructor is a function that returns a reference to the built-in RegExp object. The syntax to use the RegExp() constructor is as follows:
Syntax: var variable_name = new RegExp(regular_expression_ pattern,flag);
where,
new: Is a keyword and a special operator that creates the RegExp object. variable_name: Is the name of the variable which refers to the RegExp object that
flag: Is a letter that specifies whether to search for patterns in the complete string and
Code Snippet 10 shows the use to RegExp() constructor to create a regular expression pattern.
Code Snippet 10: var nameCheck = new RegExp(^Jo); </script> <script>
In the code, the RegExp() constructor creates a search pattern at runtime. The pattern, ^Jo is matched with the specified string to check, if it starts with Jo at the first position.
345 of 590
Concepts
Session
13
Operators and Statements
exec(string) Executes a string to search the matching pattern within it. The
method returns a null value, if pattern is not found. In case of multiple matches, it returns the matched result set. Apart from these, RegExp object also supports properties that are used to get information regarding the string. Table 13.9 lists the properties of the RegExp object.
Property
$n
Description
Represents the number from 1 to 9. It stores the recently handled parts of a parenthesized pattern of a regular expression For example, if the pattern for the recent search was /(w+)(\s+)(w+)/ and the string found was Hi Mary, the value of RegExp. $1 would contain the value Hi Indicates whether the given regular expression contain a g flag. The g flag specifies that all the occurrences of a pattern will be searched globally, instead of just searching for the first occurrence. For example, /no/g matches both nos in No health no life Indicates whether the given regular expression contains an i flag Stores the location of the starting character of the last match found in the string. In case of no match, the value of the property is -1 Stores the copy of the pattern Table 13.9: Properties of RegExp Object
aif
Concepts
346 of 590
Session
13
Operators and Statements
Code Snippet 11 demonstrates the script to verify whether the entered zip code is valid or not using a regular expression.
Code Snippet 11: <script> var zipcodepattern = /^\d{5}$/; var zipcode = zipcodepattern.exec(prompt(Enter ZIP Code:)); if(zipcode != null) { alert(Valid ZIP Code.); alert(Regular Expression Pattern: + zipcodepattern.source); } else { alert(Invalid ZIP Code Format xxxxx.); } </script>
In the code, zipcodepattern variable stores a pattern that states that the search string must contain only 5 digits. The zip code is accepted from the user and the pattern is matched with the code using the exec() method. The if condition checks whether the entered zip code is not null. If it is not null, the Valid ZIP Code message and the pattern is displayed or else the Invalid ZIP Code Format xxxxx message is displayed.
347 of 590
Concepts
Session
13
Operators and Statements The brief description of these categories is as follows:
Position Matching
Characters or symbols in this category allow matching a substring that exists at a specific position within a string. Table 13.10 lists the various position matching symbols.
^ $ \b \B
Symbol
Description
Denotes the start of a string
Example
/^Good/ matches Good in Good night, but not in A Good Eyesight
Matches a word boundary. A word /ry\b/ matches ry in She is boundary includes the position very good between a word and the space Matches a non-word boundary /\Ban/ matches an in operand, but not in anomaly Table 13.10: Position Matching Symbols
Character Classes
Characters or symbols in this category are combined to form character classes for specifying patterns. These classes are formed by placing a set of characters within the square brackets. For example, the /[a-zA-Z0-9]/ pattern matches all alphabets and digits. Table 13.11 lists the various character classes symbols.
Symbol
[xyz]
Description
Example
Matches one of the characters /[BC]RT/ specified within the character set Matches BRT and CRT but, not RRT, since the leading letter R is not specified in the set [^xyz] Matches one of the characters not /[^BC]RT/ specified within the character set Matches RRT, but not BRT or CRT . Denotes a character except for the /s.t/ new line and line terminator Matches sat, sit, set, and so on
Concepts
348 of 590
Session
Symbol
\w \W \d \D \s \S
13
Operators and Statements
Description
Example
Matches alphabets and digits along /\w/ with the underscore Matches 600 in 600% Matches a non-word character /\W/ Matches a digit between 0 to 9 Searches for a non-digit Matches % in 800%
/\d/ /\D/
Searches any single space character /\s\w*/ including space, tab, form feed, Matches bar in scroll bar and line feed Searches a non-space character /\S\w*/ Matches bar scroll in scroll
Table 13.11: Character Classes Symbols Code Snippet 12 uses the position matching symbols, escape sequence characters, and character classes to form a regular expression.
Code Snippet 12: <script> // To match a string ending with ing var stringEnd = /ing$/; // To match single digit var num = /\d/; </script>
The code declares and initializes the stringEnd and num variables. The pattern for the stringEnd variable specifies that the search string must end with letters ing. The $ character denotes the end position of the string. The pattern for the num variable specifies that the search string must have at least one digit within it.
Repetition
Characters or symbols in this category allow matching characters that reappear frequently in a string.
349 of 590
Concepts
Session
13
Operators and Statements Table 13.12 lists the various repetition matching symbols.
Symbol
{x}
Description
Example
{x, }
{x,y}
? *
Matches x number of occurrences /\d{6}/ of a regular expression Matches exactly 6 digits Matches either x or additional /\s{4,}/ number of occurrences of a Matches minimum 4 whitespace regular expression characters Matches minimum x to maximum /\d{6,8}/ y occurrences of a regular Matches minimum 6 to maximum 8 expression digits Matches minimum zero to /l\s?m/ maximum one occurrences of a Matches lm or l m regular expression Matches minimum zero to /im*/ multiple occurrences of a regular Matches i in Ice and imm expression in immaculate, but nothing in good Matches one or multiple number /le+d/ of occurrences of a regular Matches both led and lead expression Table 13.12: Repetition Matching Symbols
Characters or symbols in this category allow grouping characters as an individual entity or adding the OR logic for pattern matching. Table 13.13 lists the various alternation and grouping character symbols.
Symbol
()
Description
Example
Organizes characters together in a /(xyz)+(uvw)/ group to specify a set of characters Matches one or more number in a string of occurrences of xyz followed by one occurrence of uvw Combines sets of characters into a /(xy)|(uv)|(st)/ single regular expression and then Matches xy or uv or st matches any of the character set Table 13.13: Alternating and Grouping Matching
Concepts
350 of 590
Session
13
Operators and Statements
Back References
Characters or symbols in this category allow referring back to a sub-expression in the same regular expression. This is useful when matching the remaining sub-expression of a regular expression is based upon the result of matching the previous sub-expression. Table 13.14 lists the back reference matching symbol.
Symbol
()\n
Description
Example
Matches a parenthesized set within /(\w+)\s+\1/ the pattern, where n is the number of Matches any word occurring twice in the parenthesized set to the left a line, such as hello hello. The \1 specifies that the word following the space should match the string, which already matched the pattern in the parentheses to the left of the pattern. To refer to more than one set of parentheses in the pattern, you would use \2 or \3 to match the appropriate parenthesized clauses to the left. You can have maximum 9 back references in the pattern Table 13.14: Back References
351 of 590
Concepts
Session
13
Operators and Statements JavaScript supports four decision-making statements which are as follows:
if if-else if-else if switch
13.4.1 if Statement
The if statement executes a block of statements based on a logical Boolean condition. If this condition is true, the block following the if statement is executed. If the condition is false, the block after the if statement is not executed and the immediate statement after the block is executed. Figure 13.4 shows the flow of execution for the if statement.
Concepts
352 of 590
Session
Syntax:
13
Operators and Statements
where,
condition: Is the boolean expression. statements: Consists of instructions to be executed when the boolean expression is true.
Code Snippet 13 checks whether the quantity value is a number and whether it is greater than 0 using the if statement.
Code Snippet 13: <script> var quantity = prompt(Enter quantity of product:,0); if(quantity < 0 || isNaN(quantity)) { alert(Please enter a positive number.); } </script>
The code accepts a quantity value from the user using the prompt() function and stores it in the quantity variable. The if statement is executed and the value of variable quantity is checked whether it is less than 0 and whether it is not a number. If value provided by the user is less than 0 or is a value other than a number, the condition evaluates to true and the output Please enter a positive number is displayed to the user.
The if statement specifies a block of statement to be executed when the condition in the if statement is true. However, sometimes it is required to define a block of statements to be executed when a condition is evaluated to false. This is done using the if-else statement. The if-else statement begins with the if block, which is followed by the else block. The else block begins with the else keyword followed by a block of statements to be executed upon the false condition.
Session
13
Operators and Statements The syntax to use the if-else statement is as follows:
Syntax: if (condition) { // one or more statements; } else { // one or more statements; }
Code Snippet 14 performs the division operation and validates that the divisor is not equal to 0 using the if-else statement.
Code Snippet 14: <script> var firstNumber = prompt(Enter first number:,0); var result = 0; { } else { result = firstNumber/secondNumber; alert(Result: + result); } </script>
var secondNumber = prompt(Enter second number,0); if (secondNumber == 0) alert(ERROR Message: Cannot divide by zero.);
Concepts
The code accepts two numbers for the division operation and stores them in the variables firstNumber and secondNumber respectively. The if statement checks whether the value of the variable secondNumber is 0. If it is 0, the alert() function displays the error message to the user. If the value is not 0, the else block is executed, which performs the division operation. The quotient is stored in the result variable and is displayed to the user. V 1.1 Aptech Limited
354 of 590
Session
13
Operators and Statements
The if-else if statements allow you to check multiple conditions and specify a different block to be executed for each condition. The flow of these statements begins with the if statement followed by multiple else if statements and finally by an optional else block. The entry point of execution in these statements begins with the if statement. If the condition in the if statement is false, the condition in the immediate else if statement is evaluated. The if-else if statements are also referred to as the if-else if ladder. The syntax to use the if-else if statements are as follows:
Syntax: if (condition) { // one or more statements; } else if (condition) { // one or more statements; } else { // one or more statements; }
Code Snippet 15 displays the grades according to the percentage value entered by the user using the if-else if statements.
Code Snippet 15: <script> var percentage = prompt(Enter percentage:,0); { alert (You have obtained the A grade.); } else if (percentage >= 35 && percentage < 60) if (percentage >= 60)
355 of 590
Concepts
Session
13
Operators and Statements
{ alert (You have obtained the B class.); } else { alert (You have failed); } </script>
The code accepts the percentage value from the user and stores it in the percentage variable. The if statement checks whether the value of the percentage variable is greater than or equal to 60. If this is true, the user has obtained the A grade. If the condition is false, the execution control is passed to the else if block. Here, the value of the percentage variable is checked as to whether it is greater than or equal to 35 and less than 60. If this is true, the user has obtained the B grade. If the condition is false, the else block is executed.
Concepts
356 of 590
Session
} } }
13
Operators and Statements
Code Snippet 16 validates the username and password using the nested-if statements.
Code Snippet 16: <SCRIPT> var username = prompt(Enter Username:); var password = prompt(Enter Password:); if (username != && password != ) { if (username == admin && password == admin123) { alert(Login Successful); } else { alert (Login Failed); } } </SCRIPT>
The code accepts the username and password and stores them in the username and password variables. The if statement checks whether the values of both the variables are not empty. If they are not empty, the inner if statement is executed. The inner if statement checks whether the value of the username variable is admin and the value of the password variable is admin123. If this condition is true, the Login Successful message is displayed to the user. If the condition is false, the else block is executed.
A program becomes quite difficult to understand when there are multiple if statements. To simplify coding and to avoid using multiple if statements, switch-case statement can be used as a different approach to code the same logic. The switch-case statement allows comparing a variable or expression with multiple values.
357 of 590
Concepts
Session
13
Operators and Statements The syntax to use the switch-case statement is as follows:
Syntax: switch(expression/variable) { case value1: // statements; break; case value2: // statements; break; . . . case valueN: // statements; break; default: // default statement }
where,
switch: Executes a specific case statement that holds the value of the expression or the
variable.
case: A value and a colon follow the case keyword. The block of a specific case statement
is executed when the value of switch expression and the case value are the same. Each case block must end with the break keyword.
break: Passes the execution control to the statement existing immediately out of the switch-case statement. If there is no break statement, the next case statement is
executed.
Concepts
default: The execution control passes to the default block when none of the case values matches with the switch expression. The default block is the same as the else block of the if-else if statements.
358 of 590
Session
13
Operators and Statements
Code Snippet 17 displays the salary of an employee according to the designation by using the switch-case statement.
Code Snippet 17: <SCRIPT> var designation = prompt(Enter designation:); switch (designation) { case Manager: alert (Salary: $21000); break; case Developer: alert (Salary: $16000); break; default: alert (Enter proper designation.); break; } </SCRIPT>
The code uses the variable designation to store the designation of an employee, which is accepted from the user. The switch statement takes the value of the designation variable and this value is matched with the different case statements. If the value matches, the particular case block is executed, which displays the respective salary. If none of the case values matches with the switch variable, the default block is executed.
359 of 590
Concepts
Session
13
Operators and Statements
a. b. c. d.
1. 2. 3. 4. (C) (D)
Checks whether the operands are equal and are of the same type Returns true if either of the operands are true Returns true if both the expressions are true Checks whether the two operands are identical a-4, b-3, c-2, d-1 a-1, b-2, c-3, d-4
(A) a-3, b-2, c-4, d-1 (B) a-2, b-3, c-4, d-1
2.
Which of the following are the correct ways to create a regular expression? (A) Literal Syntax (B)
exec()
(C) (D)
3.
Which of the following operators return a decimal value when they are evaluated? (A) Arithmetic (B) Logical (C) (D) Relational Bitwise
Concepts
360 of 590
Session
4.
13
Operators and Statements
Symbol Description
a. b. c. d.
\D \d \W \w
1. 2. 3. 4.
Matches alphabets and digits along with the underscore Matches a non-word character Matches a digit between 0 to 9 Matches a non-digit (C) (D) a-3, b-2, c-1, d-4 a-4, b-3, c-2, d-1
(A) a-4, b-1, c-2, d-3 (B) a-1, b-2, c-3, d-4
5.
The _______ statement allows comparing a variable or expression with multiple values. (A) if (B)
if-else if
(C) (D)
if-else switch-case
361 of 590
Concepts
Session
13
Operators and Statements
13.5.1 Answers
1. 2. 3. 4. 5. A A, C D D D
Concepts
362 of 590
Session
13
Operators and Statements
Summary
An operator specifies the type of operation to be performed on the values of variables and expressions. JavaScript operators are classified into six categories based on the type of action they perform on operands. There are six category of operators namely, Arithmetic, Relational, Logical, Assignment, Bitwise, and Special operators. Operators in JavaScript have certain priority levels based on which their execution sequence is determined. A regular expression is a pattern that is composed of set of strings, which is to be matched to a particular textual content. In JavaScript, there are two ways to create regular expressions namely, literal syntax and RegExp() constructor. Decision-making statements allow implementing logical decisions for executing different blocks to obtain the desired output. JavaScript supports four decision-making statements namely, if, if-else, if-else if, and switch-case statement.
363 of 590
Concepts
Session
13
Operators and Statements
Try it Yourself
1. 2. Write a JavaScript code to accept three numbers from the user and print the largest and the smallest number. Write a JavaScript code that accepts name and password from the user and validates the data entered by the user. The validation criterias are as follows: a. b. The value accepted for the name field should contain only characters with a maximum limit of 10 characters. Similarly, value for the password field should be a combination of characters, digits, and underscore. Also, the password should start with one or more characters followed by the digits.
3.
Write a JavaScript code that accepts the name from the user and greets them depending upon the hour of time. For example, if it is morning, the message displayed to the user will be Good Morning <name>. Write a JavaScript code that contains an expression for e-mail matching pattern. This pattern is checked with the e-mail address provided by the user and displays whether it is valid or invalid. A school conducts a Mathematics competition for its students. The grade system for the competition is as follows: Grade A: Marks greater than 75 Grade B: Marks in the range 60 to 75 Grade C: Marks in the range 45 to 60 Grade D: Marks less than 45 Write a JavaScript code to accept the marks from the user and display the grade achieved by the student.
4.
5.
Concepts
364 of 590
Session
13
Operators and Statements (Workshop)
Note - Please refer to the respective lab deliverable for demonstrations and guided
simulations.
Labs
366 of 590
14
Session
14
Loops and Arrays
14.1 Introduction
Consider a scenario where you want to accept and display ten numbers to the user. Instead of writing the same lines of code again and again for 10 times, you can use loops. Loops allow you to execute a single statement or a block of statements multiple times. They are widely used when you want to display a series of numbers and accept repetitive input. A loop construct consists of a condition that instructs the compiler the number of times a specific block of code will be executed. JavaScript supports three types of loops that are as follows:
while Loop for Loop do-while Loop
If the condition is not specified within the construct, the loop continues infinitely. Such, loop constructs are referred to as infinite loops.
Concepts
Session
Syntax:
14
Loops and Arrays
where,
condition: Is a boolean expression.
Code Snippet 1 displays the sum of numbers from 1 to 10 by using the while loop.
Code Snippet 1: <script> var i = 0; var sum = 0; while (i<=10) { sum = sum + i; i = i + 1; } alert (Sum of first 10 numbers: + sum); </script>
The code declares two variables, i and sum, which are initialized to value 0. The variable, i, is a counter variable, whose value increases for every execution of loop. The condition in the while loop checks that the value of the counter variable, i, is less than or equal to 10. If this condition is true, the value of the sum variable is added to the value of i variable. The value of the variable i is incremented by 1. Then, the program control is passed to the while statement to check the condition again. When the value of i becomes 11, the while loop terminates as the loop condition becomes false.
369 of 590
Concepts
Session
14
Loops and Arrays Figure 14.2 shows the output.
where,
initialization: Initializes the variable(s) that will be used in the condition. condition: Comprises the condition that is checked, before the statements in the loop
Concepts
are executed.
variable(s) on every successful execution of the loop to ensure that the condition specified in the condition section is reached. The increment and decrement operators, such as ++, --, and shortcut operators: += or -= are used in this section.
370 of 590
Session
14
Loops and Arrays
Figure 14.3: for Loop Code Snippet 2 demonstrates the script that accepts a number from the user and displays the first ten multiples of that number.
Code Snippet 2: <script> var inputNum = prompt(Enter any number:); var result = 0; document.write (Multiples of: + inputNum + <br />); for (var i=1; i<=10; i++) { result = inputNum * i ; document.write (inputNum + * + i + = + result + <br />); } </script>
In the code, a variable, inputNum, is created and initialized to the value specified by the user in the prompt box. The for loop declares a variable, i, and initializes it to the value 1. If the condition is true, the number specified by the user is multiplied to the value of i variable and the result is appended to the result variable. The program control is again passed to for statement, where the value of i is incremented. The incremented value is again checked with the specified condition and it is multiplied to the number specified by the user. This process continues till the value of i becomes 11.
371 of 590
Concepts
Session
14
Loops and Arrays Figure 14.4 shows the multiples of a number.
Concepts
372 of 590
Session
14
Loops and Arrays
Figure 14.5: do-while Loop The syntax for the do-while loop is as follows:
Syntax: do { ... statements; ... }while(condition);
where,
373 of 590
Concepts
Session
14
Loops and Arrays Code Snippet 3 demonstrates the script to accept the capital of United States from the user using the do-while loop.
Code Snippet 3: <script> var answer = ; do { answer = prompt(Capital of United States:, ); }while(answer!=Washington); alert(Capital of United States: + answer); </script>
The code declares a variable, answer, which stores the string entered by the user. The do block displays a prompt box without checking any condition. The prompt box accepts the capital of United States and stores this string in the variable, answer. The condition is specified in the while block that checks, if the user has entered the string Washington. If this condition is true, prompt box is closed; else the prompt box is again displayed to accept the user input. Figure 14.6 shows the output of capital of United States.
Concepts
374 of 590
Session
14
Loops and Arrays
Figure 14.7: Flow of Execution - break Statement Code Snippet 4 demonstrates the script that accepts a number from the user and determines if it is a prime number or not.
Code Snippet 4: <script> var inputNum = parseInt(prompt(Enter number: ,)); var num = 2; while(num <= inputNum-1) { if(inputNum % num == 0) { alert(inputNum + is not a Prime Number); } num++; } if(num == inputNum) { } </script> break;
The code creates a variable, inputNum, which is initialized to the number entered by the user.
375 of 590
Concepts
Session
14
Loops and Arrays The variable num is declared and initialized to 2. If the while condition returns true, the inner if statement is checked. If this condition returns true, an alert box is displayed stating that the number is not a prime number. The break statement is used to exit the entire while loop. If the condition evaluates to false, the program control is passed to if statement outside the while loop. Figure 14.8 shows the output of the prime number on accepting number, 6 from the user in the prompt box.
Concepts
376 of 590
Session
14
Loops and Arrays
The code declares a variable, i, in the for loop definition and initializes it to value 1. When the value of i is divided by zero, the if statement checks whether the remainder is equal to zero. If the remainder is zero, the value of i is displayed as the value is an even number. If the remainder is not equal to 0, the continue statement is executed. It transfers the program control to the beginning of the for loop. Figure 14.10 shows the output of the continue statement.
377 of 590
Concepts
Session
14
Loops and Arrays
14.7 Arrays
Consider a scenario where you want to store the names of 100 employees within an IT department. This can be done by creating 100 variables and storing the names. However, keeping track of 100 variables is a tedious task and it results in inefficient memory utilization. The solution to this problem is to create an array variable to store the names of 100 employees. Figure 14.11 shows the effective usage of memory achieved using an array.
Figure 14.11: Memory Utilization Using an Array An array is a collection of values stored in adjacent memory locations. These array values are referenced using a common array name. The values of an array variable must be of the same data type. These values that are also referred to as elements and can be accessed by using subscript or index numbers. The subscript number determines the position of an element in an array list. JavaScript supports two types of arrays that are as follows:
Concepts
378 of 590
Session
14
Loops and Arrays
In a single-dimensional array, the elements are stored in a single row in the allocated memory. Figure 14.12 shows the allocation of single-dimensional array.
Figure 14.12: Single-dimensional Array As shown in figure 14.12, the first array element has the index number zero and the last array element has an index number one less than the total number of elements. This arrangement helps in efficient storage of data. In addition, it also helps to sort data easily and track the data length. The array variable can be created using the Array object and new keyword along with the size of the array element. The syntax to declare and initialize a single-dimensional array is as follows:
Syntax: var variable_name = new Array(size); //Declaration variable_name[index] = value;
where,
variable_name: Is the name of the variable. size: Is the number of elements to be declared in the array. index: Is the index position.
379 of 590
Concepts
Session
14
Loops and Arrays Code Snippet 6 shows the different ways to declare and initialize a single-dimensional array.
Code Snippet 6: <script> //Declaration using Array Object and then Initialization var marital_status = new Array(3); marital_status[0] = Single; marital_status[1] = Married; marital_status[2] = Divorced; //Declaration and Initialization var marital_status = new Array(Single,Married,Divorced); //Declaration and Initialization Without Array var marital_status = [Single,Married,Divorced]; </script>
An array element can be accessed without using loops by specifying the array name followed by the square brackets containing the index number. Code Snippet 7 demonstrates a script that stores and displays names of the students using a single-dimensional array.
Code Snippet 7: <script> var names = new Array(John, David, Kevin); alert(List of Student Names:\n + names[0] + , + + names[1] + , + + names[2]); </script>
Concepts
In the code, var names = new Array(John,David,Kevin); declares and initializes an array. The names[0] accesses the first array element which is John. The names[1] accesses the second array element which is David.
380 of 590
Session
14
Loops and Arrays
The names[2] accesses the third array element, which is Kevin. Figure 14.13 displays the names of the students.
JavaScript allows you to access array elements by using different loops. Thus, you can access each array element by putting a counter variable of the loop as the index of an element. However, this requires the count of the elements in an array. So, the length property can be used to determine the number of elements in an array. Code Snippet 8 demonstrates the script that creates an array to accept the marks of five subjects and display the average.
Code Snippet 8: <script> var sum = 0; var marks = new Array(5); for(var i=0; i<marks.length; i++) { marks[i] = parseInt(prompt(Enter Marks:, )); } alert (Average of Marks: + (sum/marks.length)); </script> sum = sum + marks[i];
In the code, var marks = new Array(5); declares an array of size 5. It displays a prompt box that accepts the marks for a subject in each iteration. Then, the code calculates and displays the average marks.
381 of 590
Concepts
Session
14
Loops and Arrays Figure 14.14 displays the average of the marks, 90, 75, 85, 95, and 82 accepted from the user in the prompt box.
Concepts
Figure 14.15: Multi-dimensional Array A two-dimensional array is an array of arrays. This means, for a two-dimensional array, first a main array is declared and then, an array is created for each element of the main array.
382 of 590
Session
Syntax:
14
Loops and Arrays
where,
variable_name: Is the name of the array. index: Is the index position. value1: Is the value at the first column. value2: Is the value at the second column.
383 of 590
Concepts
Session
14
Loops and Arrays
Access Array Elements Without Loops
Code Snippet 9 creates a two-dimensional array that displays the employee details.
Code Snippet 9: <script> var employees = new Array(3); employees[0] = new Array(John, 25, New Jersey); employees[1] = new Array(David, 21, California); document.write(<H3> Employee Details </H3>); document.write(<P><B>Name: </B> + employees[0][0] + </P>); document.write(<P><B>Location: </B> + employees[0][2] + </ P>); document.write(<P><B>Name: </B> + employees[1][0] + </P>); document.write(<P><B>Location: </B> + employees[1][2] + </ P>); </script>
In the code, var employees = new Array(3) creates an array of size 3. The declaration employees[0] = new Array(John,23,New Jersey) creates an array at the 0th row of the employees array. Similarly, employees[1] = new Array(David,21,California) creates an array at the first row of the employees array. Figure 14.17 displays the employee details.
Concepts
384 of 590
Session
14
Loops and Arrays
In the code, products[0] = new Array(Monitor,236.75) creates an array at the 0th row of the products array. Similarly, products[1] = new Array(Keyboard,45.50) creates an array at the first row of the products array. The condition, i < products.length, specifies that the counter variable i should be less than the number of rows in the array variable, products. For each row in the array, the condition, j < products[i].length specifies that the counter variable j, should be less than the number of columns specified the ith row of the array variable, products. Finally, document.write(<TD> + products[i][j] + </TD>) displays the values at the ith row and jth column of array variable, products. Figure 14.18 displays the product details in a table.
385 of 590
Concepts
Session
14
Loops and Arrays
Method
Description
Combines one or more array variables Joins all the array elements into a string Retrieves the last element of an array Appends one or more elements to the end of an array Sorts the array elements in an alphabetical order Table 14.1: Methods of Array Object
Code Snippet 11 demonstrates how to access and manipulate the array elements.
Code Snippet 11: <script> var flowers = new Array(Rose, Sunflower, Daisy); document.write(Number of flowers: + flowers.length + <br/>); document.write(Flowers: + flowers.join(, ) + <br/>); document.write(Orchid and Lily are Added: + flowers.push(Orchid, Lily) + <br/>); document.write(Flowers (In Ascending Order): + flowers.sort() + <br/>); document.write(Flowers Removed: + flowers.pop()+<br/>); </script>
Concepts
Session
14
Loops and Arrays
In the code, an array variable flowers is created, that stores the names of three flowers. The length property is used to display the number of flowers in the array variable. The join() method joins the flower names and separates them with a comma. The push() method adds orchid and lily at the end of the array and the total number of flowers in the array list is displayed as 5. The sort() method sorts the flowers in alphabetical order. The pop() method retrieves the last element that is Sunflower, from the array list.
where,
variable_name: Is the name of the variable. array_name: Is the array name.
Code Snippet 12 demonstrates how to display elements from an array using the for...in loop.
Code Snippet 12: <script> var books = new Array(Beginning CSS 3.0, Introduction to HTML5, HTML5 in Mobile Development); document.write(<H3> List of Books </H3>); for(var i in books) document.write(books[i] + <br/>); } </script>
387 of 590
Concepts
Session
14
Loops and Arrays Figure 14.20 displays the corresponding output of the script.
Concepts
388 of 590
Session
14
Loops and Arrays
2.
(1) Joins all the array elements into a string (2) Appends one or more elements to the end of an array
(3) Retrieves the last element of an array (4) Combines one or more array variables (C) (D) a-2, b-3, c-4, d-1 a-3, b-2, c-4, d-1
(D) join (A) a-4, b-1, c-2, d-3 (B) a-1, b-2, c-3, d-4
3.
Which of the following statement terminates the current execution, but does not terminate the execution of the loop entirely? (A) halt (B) continue (C) (D) break exit
4.
Which of the following option is not a valid declaration of the for loop?
(B)
(D) increment/decrement)
for (condition;
389 of 590
Concepts
for (initialization;
(C) increment/decrement)
for (;condition;
Session
14
Loops and Arrays 5. Identify the correct ways to create an array variable in the JavaScript. (A) Object (B) new (C) (D) Array String
Concepts
390 of 590
Session
14
Loops and Arrays B C B D B, C
14.10.1 Answers
1. 2. 3. 4. 5.
391 of 590
Concepts
Session
14
Loops and Arrays
Summary
A loop construct consists of a condition that instructs the compiler the number of times a specific block of code will be executed. JavaScript supports three types of loops that include: while loop, for loop, and do-while loop. The break statement is used to exit the loop without evaluating the specified condition. The continue statement terminates the current execution of the loop and continue with the next repetition by returning the control to the beginning of the loop. JavaScript supports two types of arrays namely, Single-dimensional array and Multi-dimensional array. The for..in loop is an extension of the for loop that enables to perform specific actions on the arrays of objects.
Concepts
392 of 590
Session
14
Loops and Arrays
Try it Yourself
1. Write a JavaScript code to accept a number from the user and check whether the number is armstrong or not. An armstrong number is a number whose sum of cubes of individual digit is same as the number itself. For example, 153 is an armstrong number, as the sum of 13 + 53 + 33 = 153. 2. Write a JavaScript code to create an array that store names of 10 students in it. Then, display the names of the students in an alphabetic order from the array. Also, use the for..in loop to display the name of the students from the array. Write a JavaScript code to print the transpose of a matrix. Transpose of a matrix is where the rows are interchanged with columns and vice versa. Write a JavaScript code to display the following pattern on the Web page:
3. 4.
393 of 590
Concepts
Session
14
Loops and Arrays (Workshop)
Note - Please refer to the respective lab deliverable for demonstrations and guided
simulations.
Labs
396 of 590
15
Session
15
Functions and Objects
15.1 Introduction
Consider a scenario where a Web page has been designed to greet the user with his/her name on the click of a button. A code can be used here to accomplish this task, but may result in the same output on repetitive execution. However, writing these statements each time for the same action is tedious, time consuming, and error prone. To make the code more task-oriented and manageable, JavaScript allows to group statements before they are actually invoked. This can be achieved by using the concept of functions. A function is a reusable block of code that is executed on the occurrence of an event. The event can be a user action on the page or a call within the script.
15.2 Functions
A function is an independent reusable block of code that performs certain operations on variables and expressions to fulfill a task. A function might take parameters, which are variables or values on which it performs operations. After performing operations, a function might return the resultant value to display it in the browser. For example, a function named Add() might take two numbers on which the addition operation will be performed and will return the result of addition. A JavaScript function is always created under the script element. JavaScript supports both user-defined and built-in functions. Figure 15.1 shows the functions in an HTML page.
Concepts
398 of 590
Session
15
Functions and Objects
JavaScript allows declaring a function using the function keyword. The keyword is followed by the name of the function and parameters enclosed within the parenthesis. If the function does not take any parameters, then it must be specified with the empty parenthesis. Once the function is declared, you need to define the function by specifying the operations or instructions within the curly braces { and }. These curly braces indicate the start and end of the function block, which is collectively referred to as the body of the function. There are certain conventions that must be followed for naming functions. They are as follows: Can consist of letter, digits, and underscore Can begin only with a letter or an underscore Cannot be a JavaScript keyword Cannot begin with a digit Cannot contain spaces
where,
function: Is a keyword used to declare a function. function_name: Indicates the name of the function. list of parameters: Is optional and specifies the parameters to be passed to the
A function must be defined, before it can be invoked in the script. Also, there can be multiple functions defined within the script element.
399 of 590
Concepts
Session
15
Functions and Objects Figure 15.2 shows the declaration and definition of a function.
Concepts
400 of 590
Session
15
Functions and Objects
401 of 590
Concepts
Session
15
Functions and Objects Figure 15.4 shows the parameterized functions.
Figure 15.4: Parameterized Functions As shown in figure 15.4, the num1 and num2 parameters will hold the values of val1 and val2 arguments to perform the operations. The num1 and num2 parameters are only accessible within the function, whereas the val1 and val2 variables are accessible anywhere within the script element. The parameters of a function are variables that are declared in the function declaration. Here, num1 and num2 are the parameters of the function. Similarly, arguments are the values passed to the function. Here, val1 and val2 are the arguments whose values are passed to the parameters, num1 and num2, while invoking the function. Alternatively, one can use same variable names for arguments and parameters while creating and invoking functions. In either of the case, the variables will occupy different memory space.
pass by value method, the called function do not change the values of the parameters passed to it from the calling function.
402 of 590
Session
15
Functions and Objects
This is because each parameter occupies different memory locations. Figure 15.5 shows the pass by value method.
the pass by reference method, the called function modifies the value of parameters passed to it from the calling function. This change is reflected when the control passes back to the calling function. Figure 15.6 shows the pass by reference method.
403 of 590
Concepts
Session
15
Functions and Objects Code Snippet 1 demonstrates the code to pass Array object as a parameter to a function.
Code Snippet 1: <script> var names =new Array(James, Kevin, Brad); function change_names(names) { names[0]= Stuart; } function display_names() { document.writeln(<H3> List of Student Names:</H3>); document.write(<UL>); for(vari=0; i<names.length; i++) { document.write(<LI> + names[i]+ </LI>); } document.write(</UL>); change_names(names); document.write(<H3> List of Changed Students Names:</H3>); document.write(<UL>); for(vari=0; i<names.length; i++) { document.write(<LI> + names[i]+ </LI>); } document.write(</UL>); } display_names(names); </script>
Concepts
In the code, the function change_names(names) takes the names array as parameter. It changes the value at the 0th position in the array. The function is further invoked in the display_names() function. The display_names() function displays the values from the array before and after the value is changed at the 0th position in the array. V 1.1 Aptech Limited
404 of 590
Session
15
Functions and Objects
405 of 590
Concepts
Session
15
Functions and Objects Code Snippet 2 demonstrates the script that calculates the factorial of a number using a function and display the output to the user.
Code Snippet 2: <script> function factorial(num) { if(num==0) else { var result =num; while(num>1) { result = result *(num-1); num--; } return result; } } var num=prompt(Enter number:,); var result = factorial(num); alert(Factorial of +num+ is + result + .); </script> return 0; else if(num==1) return 1;
The code defines a function named factorial() which takes the num variable as the parameter. The execution of the script starts from the prompt() function, which takes the number from the user and stores it in the num variable. Next, the factorial() function is invoked by passing the num argument. If the user enters the value as 0 or 1, the function returns the value as 0 or 1 respectively. For any other number, the function calculates the factorial and returns the output value by using the return statement. The output is stored in the result variable, which is displayed to the user.
Concepts
406 of 590
Session
15
Functions and Objects
Figure 15.8: Factorial of Number Similarly, the return statement can be used to return a collection of values stored in arrays. Figure 15.9 shows a display_list() function which declares and initializes an array named, languages to store the languages. The function returns an array whose values are then displayed to the user.
15.3 Objects
Objects are entities with properties and methods and resemble to real life objects. Properties specify the characteristics or attributes of an object, while methods identify the behavior of an object. For example, consider a real life object namely, Car.
407 of 590
Concepts
Session
15
Functions and Objects The attributes of the Car object can include color, car number, and model. The methods of the car could be run() that specifies the running behavior of the car. Similarly, in JavaScript, objects have their own properties and methods. Figure 15.10 shows objects with their properties and methods.
Figure 15.10: Objects with Properties and Methods JavaScript provides built-in objects and allows creating user-defined objects. The description of the object is as follows:
Built-in Objects - Are pre-defined objects which are already defined. Their
properties and methods need to be called to fulfill a task. An example of a pre-defined object is the Array object.
Concepts
408 of 590
Session
15
Functions and Objects
In the second method, an object can be created by defining a template and initializing it with the new keyword. The syntax to create the object using these methods are as follows:
Direct Method
The syntax to create a custom object using the Object object is as follows:
Syntax:
var object_name = new Object();
where,
object_name: Is the name of the object. new: Is the keyword that allocates memory to the custom object. This is known as
instantiation of an object.
Object: Is the built-in JavaScript object that allows creating custom objects.
Template Method
An objects template refers to a structure that specifies the custom properties and methods of an object. There are two steps in creating an object by using this method. First, the object type is declared using a constructor function. Second, you specify the object of the declared object type by using the new keyword. JavaScript allows creating a reusable template without having to redefine properties and methods repeatedly to fulfill a particular objects requirements. This template is known as the constructor function. A constructor function is a reusable block that specifies the type of object, its properties, and methods. It might or might not take any parameters. After creating the constructor function, you specify an object of the declared object type using the new keyword. The new keyword allocates memory for the object and invokes a constructor function. The syntax to create a constructor function is as follows:
Syntax:
function object_type(list of parameters) // Body specifying properties and methods }
409 of 590
Concepts
Session
15
Functions and Objects where,
object_type: Indicates the object type. list of parameters: Is optional and specifies the parameters to be passed to a
The syntax to create the object using the new keyword is as follows:
Syntax:
object_name = new object_type(optional list of arguments);
where,
object_name: Is the name of the object.
Code Snippet 3 shows the creation of objects using direct method and template method.
Code Snippet 3: <script> //create an object using direct method var doctor_details=new Object(); //create an object using new keyword studOne = new student_info (James, 23, New Jersey); </script>
In the code, doctor_details object is created using the Object object. After creating the object, properties and methods can be specified. Similarly, student_info object is created using new keyword. The values James, 23, and New Jersey are the properties of the student_info which are initialized by constructor function during creation.
Concepts
410 of 590
Session
15
Functions and Objects
Code Snippet 4 demonstrates the script that creates the student_details object and adds properties namely, first_name, last_name, and age along with their values.
Code Snippet 4: <script> var student_details=new Object(); student_details.first_name= John; student_details.last_name= Fernando; student_details.age= 15; alert (Student\s name: +student_details.first_name+ + student_ details.last_name); </script>
The code specifies three properties of the student_details object namely, first_name, last_name, and age along with their values. The values of these properties are displayed in the browser using the write() method. Figure 15.11 shows the output of the student_details object.
Figure 15.11: Output student_details Object Similarly, if the template method is implemented to create a custom object, then a constructor function is used to declare properties for an object.
411 of 590
Concepts
Session
15
Functions and Objects Code Snippet 5 creates the employee_info object and adds properties in the constructor function.
Code Snippet 5: <script> // To define the object type function employee_info(name, age, experience) { this.name = name; this.age= age; this.experience= experience; } // Creates an object using new keyword empMary = new employee_info(Mary, 34, 5 years); alert (Name: + empMary.name + \n +Age: +empMary.age+ \n +Experience: +empMary.experience); </script>
The code specifies three properties namely, name, age, and experience along with their values in the constructor function. The object named empMary is created, which passes the values as the arguments. This invokes the constructor function and initializes the properties to their values. The this keyword is a reference to the current object whose properties are being initialized. It is used in the constructor to resolve conflict between the property and the parameter, both of which have the same name. The this keyword marks the distinction between the two, while assigning the value to the properties of an object. Figure 15.12 displays the output of the employee_info object.
Concepts
Session
15
Functions and Objects
Methods are similar to JavaScript functions, but there is a slight difference between them. A method is always associated with an object and is executed by referring to that object. On the other hand, a function is not associated with any object and is executed independently. Similar to functions, the custom methods can also take parameters. One or more methods can be specified after creating an object using the Object object or while creating the template. To invoke a method, they must be specified with the object name followed by a period, method name, and parenthesis with parameters, if any. Code Snippet 6 demonstrates the code that defines a custom method to calculate the area of a square.
Code Snippet 6: <script> var square =new Object(); square.length=parseInt(5); square.cal_area=function() { var area =(parseInt(square.length)*parseInt(4)); return area; } alert (Area: +square.cal_area()); </script>
The code defines a custom object named square whose length property is set to a numeric value 5. It also defines a custom function named cal_area(), which calculates the area of the square and returns the result. Figure 15.13 displays the output of the area of a square.
413 of 590
Concepts
Session
15
Functions and Objects Similarly, methods can be specified while using template method for creating a custom object. The implementation of custom methods is same for creating and invoking methods as specified for the direct method. However, in the template method, an ordinary function is created to implement the functionality. Then, this function is assigned to the custom method. Such functions are known as method functions. To invoke the function, you specify the object name followed by a period and the method name. Code Snippet 7 demonstrates the script that creates a custom method and associates it with the method function.
Code Snippet 7: <script> //Define a Method Function functioncal_diameter() { var diameter =this.radius*2; return diameter; } //Define a Constructor Function function circle(radius) { this.radius= radius; this.get_diameter=cal_diameter; } //Create the object circleObj = new circle(10); alert (Diameter: +circleObj.get_diameter()); </script>
Concepts
The code creates an object, circleObj and invokes the custom method get_diameter(), which in turn invokes the function, cal_diameter().
414 of 590
Session
15
Functions and Objects
The object model of JavaScript language forms the foundation of the language. These objects help to provide custom functionalities in the script. JavaScript treats the primitive data types as objects and provide equivalent object for each of them. For example, if a variable contains a string of characters, then it is treated as String object by JavaScript. Similarly, if a variable contains the value true or false, it is treated as Boolean object. JavaScript objects are categorized as built-in objects, browser objects, and HTML objects. The built-in objects are static objects which can be used to extend the functionality in the script. Some of these objects are: String, Math, and Date. The browser objects, such as window, history, and navigator are used to work with the browser window, whereas the HTML objects, such as form, anchor, and so on are used to access elements on a Web page.
where,
object_name: Is the instance of the String object
The String object provides different properties and methods to manipulate strings. Table 15.1 lists the properties of the String object.
length
prototype
Retrieves the number of characters in a string. Adds user-defined properties and methods to the String instance. Table 15.1: Properties of the String Object
415 of 590
Concepts
Property
Description
Session
15
Functions and Objects Table 15.2 lists the methods of the String object.
charAt()
Method
Description
Retrieves a character from a particular position within a string. concat() Merges characters from one string with the characters from another string and retrieves a single new string. indexOf() Retrieves the position at which the specified string value first occurred in the string. lastIndexOf() Retrieves the position at which the specified string value last occurred in the string. replace() Matches a regular expression with the string and replaces it with a new string. search() Searches for a match where the string is in the same format as specified by a regular expression. split() Divides the string into substrings and defines an array of these substrings. substring() Retrieves a part of a string between the specified positions of a string. toLowerCase() Specifies the lowercase display of the string. toUpperCase() Specifies the uppercase display of the string. Table 15.2: Methods of the String Object Code Snippet 8 demonstrates the script that creates a String object and test various methods on it.
Code Snippet 8: <script> varfull_name=new String(David James Taylor); document.write(Number of Characters are: +full_name.length+ <BR/>); document.write(Character at Position 6 is: +full_name.charAt(6)+ <BR/>); document.write(Student\s Name and their Father\s name are: +full_ name.split( ,2)+ <BR/>);
Concepts
416 of 590
Session
15
Functions and Objects
where,
PropertyName: Is the name of the property
Similarly, the syntax to invoke the methods of the Math object is as follows:
Syntax: var variable_name = Math.MethodName(optional list of parameters);
417 of 590
Concepts
Session
15
Functions and Objects Code Snippet 9 demonstrates the script that calculates area of a circle using the Math object.
Code Snippet 9: <script> var full_name=new String(David James Taylor); document.write(Number of Characters are: +full_name.length+ <BR/>); var area =Math.floor(tempArea); return area; } alert(Area of circle is: +area_circle(5)); </script>
In the code, Math.PI is a property that stores the value 3.142 into the variable, pi. The Math.pow(radius, 2) method calculates the radius raised to the power 2. Similarly, Math.floor(tempArea) method rounds the resultant value to a number less than or equal to the resultant value. Figure 15.15 shows the area of circle with the radius5.
418 of 590
Session
Syntax:
15
Functions and Objects
The various syntax to instantiate the Date object are as follows: a. To instantiate the Date object with the current date and time as that of the local machine.
var object_name = new Date();
where,
object_name: Is the instance of the Date object.
b.
To instantiate the Date object by providing passed milliseconds, since 01 January, 1970 as the parameter.
var object_name = new Date(milliseconds);
c.
To instantiate the Date object by passing date values and optional time values as the parameters.
var object_name = new Date(year, month, day, hour, minutes, seconds, milliseconds);
Here, the Date object refers to the month numbers from 0 to 11 and treats the first month as 00. Therefore, one needs to specify 02 as the month value for the March month. If the optional arguments are not supplied, they are set to 0. d. To instantiate the Date object by passing date values and optional time values in quotes as the parameter.
var object_name = new Date(dateString);
Method
Description
419 of 590
Concepts
Retrieves a numeric value between 1 and 31 which indicates the day of the month. getDay() Retrieves a numeric value between 0 and 6 which indicates the day of the week. getTime() Retrieves a numeric value which indicates the time passed in milliseconds since midnight 01/01/1970. getFullYear() Retrieves a four digit numeric value which indicates the year in the given date.
Session
15
Functions and Objects Code Snippet 10 demonstrates the script that displays the current date in the mm/dd/yyyy format.
Code Snippet 10: <<script> function display_date() { var today =new Date(); var date =today.getDate(); var month =today.getMonth(); month++; var year =today.getFullYear(); alert (Today\s date is: + month + / + date + / + year); } display_date(); </script>
420 of 590
Session
Syntax:
15
Functions and Objects
where,
object_name: Is the name of a common object for the set of statements
Apart from built-in objects, JavaScript also provides objects to access and manipulate various aspects of a Web browser. These objects are called as browser objects. They exist on all pages displayed in the browser and correspond to elements on a page. For example, browser objects allow accessing various characteristics of the browser, such as browser window itself, browser history, changing current URL, and moving backward and forward in the browser.
Session
15
Functions and Objects Figure 15.18 shows the hierarchy of browser objects.
Figure 15.18: Hierarchy of the Browser Objects The brief description for some of these objects is as follows:
window Object
The window object is the top level object in JavaScript hierarchy. This means that all the objects in the hierarchy are descendants of the window object. The window object represents a browser window. It contains browser information, such as the look and feel of the browser, its version, and so on. The window object provides properties that allows setting a default text for the status bar, name of the browser window, retrieve history, and so on. Table 15.4 lists some of the commonly used properties of the window object.
defaultStatus Specifies or retrieves the default text to be displayed in the status
Property
Description
bar of the browser window. Represents an HTML document that contains different elements. Contains history of the visited Uniform Resource Locators (URLs). Contains the content of the specified URL.
Concepts
Session
15
Functions and Objects
The window object provides methods that allows displaying error messages, confirmation boxes, and so on. Table 15.5 lists the methods of the window object.
alert()
Method
Description
Displays an alert box that states the message and an OK button. Prompts a dialog box that displays a message with the OK and Cancel buttons. createPopup() Creates a pop-up window. focus() Focuses the current window. open() Opens the specified file in a new browser window. prompt() Prompts a dialog box that accepts input from the user.
confirm()
Table 15.5: Methods of the window Object Code Snippet 11 demonstrates the methods of the window object.
Code Snippet 11: <!DOCTYPE html> <head> <title> window Object </title> <script> function new_window() { if(confirm(Do you want to open a new page?)) { window.open(http://www.aptech-education.com/pages/ about-us/about-aptech.html, _parent); } else { window.alert(In the Current Window); } } </script> </head> <body> <input type=button value=Click to move to the next </body> </html>
pageonClick=new_window();/>
423 of 590
Concepts
Session
15
Functions and Objects The code invokes the function new_window() on a button click. This function asks the user for opening the new page. If user clicks OK, then about-aptech.html page is opened in the current window. Otherwise, displays a message to the user.
history Object
The history object is a part of the window object. It contains a set of URLs visited by a user in a browser window. The history object is an array that allows referring to a particular URL by specifying its index number in the array. The length property allows you to determine the number of URLs in the history list. Table 15.6 lists the methods of the history object.
back() go()
Method
Description
Retrieves and displays the previous URL from the history list. Retrieves and displays the next URL from the history list. Displays the specified URL. It accepts a parameter, which can either be a string or a number to go to specific page. Table 15.6: Methods of the history Object
forward()
navigator Object
The navigator object contains information about a browser used by the client. It allows the user to retrieve browser specific information, such as name, version number, and language. Table 15.7 lists the properties of the navigator object.
appName
Property
Description
Retrieves the name of the browser. appVersion Retrieves the version number and platform of the browser. browserLanguage Retrieves the language of the browser. cookieEnabled Determines whether the cookies are enabled in the browser. platform Retrieves the machine type such as Win32, of the client browser. Table 15.7: Properties of the navigator Object
Concepts
424 of 590
Session
15
Functions and Objects
Code Snippet 12 demonstrates the use of navigator object to retrieve information about the browser.
Code Snippet 12: <!DOCTYPE html> <head> <title> navigator Object </title> <script> function display_browser() { document.write(Browser name: +navigator.appName+ <BR/>); document.write(Browser version: +navigator.appVersion+ <BR/>); document.write(Browser language: +navigator. browserLanguage+ <BR/>); document.write(Platform: +navigator.platform+ <BR/>); if(navigator.cookieEnabled) { document.write(Cookie is enabled in the browser.); } } </script> </head> <body> <input type=button value=Browser Information onclick=display_browser()/> </body> </html>
425 of 590
Concepts
Session
15
Functions and Objects Figure 15.19 displays the output of the navigator object for Opera browser.
The location object allows to access complete information of the URL loaded in the browser window. It is a part of the Window object. A single URL is composed of different portions, such as the host name, port number, and so on which can be accessed through the location object. Table 15.8 lists the properties and methods of the location object.
Property/Method
host href pathname protocol assign() reload() replace()
Description
Retrieves host name and port number of the URL. Specifies or retrieves the entire URL. Specifies or retrieves the path name of the URL. Specifies or retrieves the protocol of the URL. Loads a new document with the specified URL. Reloads the current document by again sending the request to the server. Overwrites the URL history for the current document with the new document.
Concepts
426 of 590
Session
15
Functions and Objects
Code Snippet 13 demonstrates the use of location object to retrieve the different portions of the specified URL.
Code Snippet 13: <!DOCTYPE html> <head> <title> location Object </title> <script> {
</script> </head> <body> <input type=button value=View URL Information </body> </html>
onclick=display_URLInfo()/>
427 of 590
Concepts
Session
15
Functions and Objects JavaScript allows the user to access HTML elements and also change the existing structure of an HTML document. This can be done by using DOM specification. The DOM is an API that defines the object structure for accessing and manipulating HTML elements. It is used with JavaScript to add, modify, or delete elements and contents on a Web page. DOM specifications are laid by W3C and are implemented by all the browsers to overcome incompatibility issues. W3C DOM specifications are divided into levels. The level 1 specification of DOM was first defined in 1998. The current DOM specification is level 3. The DOM reads all the elements contained in an HTML page. It treats the HTML elements as nodes. According to DOM specification, the entire HTML document represents a document node. This document node consists of element nodes, attribute nodes, and text nodes. Thus, the document node is the highest level node and text nodes are the lowest ones. Every node in the node hierarchy has a parent node, which consists of multiple child nodes. For example, <head> and <body> are the child nodes of <html>. All these nodes together form up a node tree and are related to each other. Code Snippet 14 shows an HTML document.
Code Snippet 14: <!DOCTYPE html> <html> <head> <title>Welcome</title> </head> <body> <h1> Introduction </h1> <ahref=#>Click Here</a> </body> </html>
Concepts
428 of 590
Session
15
Functions and Objects
Figure 15.21: DOM Structure All the nodes present in the node hierarchy contain certain properties. These properties provide information about the node. The different node properties are as follows:
nodeName - Represents the name of the node. It contains the tag name of the HTML
nodeValue - Represents the text contained within the node. This property is only
available for attribute nodes and not for document and element nodes.
nodeType - Represents the type of the node. For example, the document node,
The HTML DOM provides standard objects for HTML documents. Some of these objects are as follows:
429 of 590
Concepts
Document object
Session
15
Functions and Objects The brief description for some of these objects is as follows:
Document Object
The HTML DOM provides a document object which is used within JavaScript to access all HTML elements presented on the page. The document object is one of the basic JavaScript object. It represents the entire HTML document. It provides access to other elements, such as links, anchors, and so on. Each HTML page has only one document object. This object is created when the BODY element is loaded on the Web page. The document object is also the part of the window object and is accessed as window.document. The document object provides properties that allow the user to specify or retrieve the information about the elements and its content. Table 15.9 lists the properties of the document object.
body
Property
Description
Provides access to the BODY element. Specifies or retrieves the title of the document. Retrieves the collection containing all the anchors contained in a document. Retrieves the collection containing all the forms contained in a document. Retrieves the collection containing all the images contained in a document. Retrieves the collection containing all the links contained in a document. Table 15.9: Properties of the document Object
title
The document object provides methods that allow retrieving the HTML elements using the id, name, and tag name. Table 15.10 lists the methods of the document object.
close()
Property
Description
Closes a data stream and displays the data collected using the open() method. getElementById() Retrieves a collection of HTML elements by using the specified ID. getElementsByName() Retrieves a collection of HTML elements by using the specified name. getElementsByTagName() Retrieves a collection of HTML elements with the specified tag name.
Concepts
430 of 590
Session
open() write()
15
Functions and Objects
Property
Description
Opens a stream to accept the output from write() or writeln() methods. Writes the text or HTML expression to a document.
Table 15.10: Methods of the document Object Code Snippet 15 demonstrates the use of the document object to change the image on the click of a button.
Code Snippet 15: <!DOCTYPE html> <head> <title> Document Object </title> <script> function change_image() { varimgText=document.getElementById(myImg).alt; if(imgText==ford) { document.getElementById(myImg).src=ferrari.jpg; document.getElementById(myImg).alt =ferrari; document.getElementById(mytext).value =Ferrari Car; } else { document.getElementById(myImg).src=ford.jpg; document.getElementById(myImg).alt =ford; document.getElementById(mytext).value =Ford Car; } </script> </head>
431 of 590
Concepts
Session
15
Functions and Objects
<body> <imgid=myImg src=ford.jpgwidth=300 height=300alt=ford /><br/> Model: <input type=text id=mytext value=Ford Car readonly=readonly/><br/><br/> <input type=button value=Change Image onclick=change_ image()/> </body> </html>
In the code, image and text elements on the page are accessed using document. getElementById() method. The method retrieves the elements based on the specified ids and sets new values for their properties. This is all done at runtime, and not through markup. The use of document.getElementById() enables to access the elements within JavaScript function and change them dynamically. Figures 15.22 and 15.23 show the initial image and changed image respectively on clicking Change Image button.
Concepts
Session
15
Functions and Objects
Form Object
Form accepts input from the user and sends data for validation. JavaScript allows you to process and validate the form data. A single HTML document can contain multiple forms. The DOM specification provides a form object that represents an HTML form. A form object is created for each <form> tag in an HTML document. Code Snippet 16 demonstrates the use of the form object that counts number of controls in a form.
Code Snippet 16: <!DOCTYPE html> <head> <title> Form Object </title> <script> function display_length() { var count =document.getElementById(form1).length; alert(Number of controls on the form: + count); } </script> </head> <body> <form id=form1 action=welcome.php> First name: <input type=text name=firstname value=John /><br /> Last name: <input type=text name=lastname value=Smith /><br /> Age : <input type=text name=age value=40 /><br /> <input type=button value=ControlsonClick=display_ length()/> </body> </html>
In the code, a Web page contains a form with input elements, such as text and a button. The form is accessed in JavaScript using the id attribute which is set to form1. Then, the length property of the form object is used to retrieve the number of elements in a form.
433 of 590
Concepts
</form>
Session
15
Functions and Objects Thus, the statement form1.length returns the value 4, that is stored in the variable count. Finally, the value of variable count is displayed in the alert window. Figure 15.24 shows the number of controls in the form.
Concepts
434 of 590
Session
15
Functions and Objects
2.
Which of the following methods do not change values of the parameters passed to it from the calling function? (A) Pass By Variable (B) Pass By Reference (C) (D) Pass By Value Pass By Object
3.
The ______ object is the parent object from which all JavaScript objects are derived. (A) String (B) Object (C) (D) Math Array
4.
1. 2. 3. 4.
Retrieves the information of the URL loaded in the browser window Contains information about the browser used by the client Contains a set of URLs visited by the user in a browser window Represents a browser window
(D) location
(B)
(D)
435 of 590
Concepts
(C)
Session
15
Functions and Objects 5. Identify the correct document object method that retrieves a collection of HTML elements using the specified name. (A) getElement() (B)
getElementsByName()
(C) (D)
getElementById() getElementsByTagName()
Concepts
436 of 590
Session
15
Functions and Objects A C B D B
15.7.1 Answers
1. 2. 3. 4. 5.
437 of 590
Concepts
Session
15
Functions and Objects
Summary
A function is reusable piece of code which performs calculations on parameters and other variables. The return statement passes the resultant output to the calling function after the execution of the called function. Objects are entities with properties and methods and resemble to real life objects. There are two ways to create a custom object namely, by directly instantiating the object or by creating a constructor function. JavaScript provides various built-in objects, such as String, Math, and Date. JavaScript also provides browser objects, such as window, history, location, and navigator. DOM is a standard technique for dynamically accessing and manipulating HTML elements. The DOM provides a document object which is used within JavaScript to access all HTML elements presented on the page.
Concepts
438 of 590
Session
15
Functions and Objects
Try it Yourself
1. Create a Web site for an online store that allow their customers to buy music and movie CDs and DVDs over the Internet. For online shopping, Web site accepts the credit card details from the customer. These credit card details should be validated before allowing the customers to proceed further. Assume that you are one of the developer and have to perform the following tasks: Create a Web page that displays images of movie CDs and DVDs. On click of any image, a new window is opened displaying details of the selected movie. Create a Web page with a form containing appropriate controls that allow customers to input their credit card number. Check the credit card details. If the credit card details do not match, an alert box must be displayed stating the same. Allow the customers to navigate through the Web site by providing the Next, Previous, Top, and Bottom buttons. Allow the customers to maintain the history of URLs visited in a browser window.
Hint: To fulfill these requirements, the developer can make use of the DOM objects. 2. Create a Web page with a label and a button named fade. When user clicks button, the label along with the text must disappear and again on second click, the label should reappear. Create a expand and collapse panel with a button using HTML, CSS, and JavaScript. Initially, the panel will be in the expanded mode. When user clicks button, the panel will be collapsed and only a bar along with a button is visible. Similarly, when the user clicks button next time, the panel is expanded.
3.
439 of 590
Concepts
First say to yourself what you would be; and then do what you have to do
Session
15
Functions and Objects (Workshop)
Note - Please refer to the respective lab deliverable for demonstrations and guided
simulations.
Labs
442 of 590
Session -
16
Session
16
Building a Mobile Web Application
16.1 Introduction
Today, access to the Web is not limited to only desktop systems, but is also available on portable and wireless devices, such as mobiles devices. Mobile devices, such as smartphones and tablets are equipped with browsers and network access that provide a better Web experience to their users. As the number of mobile users has increased, so has the need for a mobile Web experience that is identical to a desktop user experience. In other words, mobile users now look for applications targeting their mobiles that are similar to the ones on their desktops. This has led to the emergence of mobile Web application development. Different companies follow distinctive strategies for developing mobile applications depending on the need of their users.
Message Service (SMS) facility. They do not provide support for Web browsers or network access.
basic mobile device, typically Web support. There is a large market for these mobile devices and they are preferred by users who do not need heavy Internet usage. They also include a basic camera and a basic music player.
Low-end mobile devices - These types of models provide more features than a
Manufacturers, such as Nokia, Motorola, Sony Ericsson, Samsung, and so forth have gained popularity for offering low cost handset in the global market.
Concepts
444 of 590
Session
16
Building a Mobile Web Application
Figure 16.1 shows the low-end mobile devices available from different manufacturers.
to their increased user experience and moderate cost. Some key features of these devices include: medium sized-screen, HTML supported browser, a decent camera, games, and support for applications. They have a proprietary Operating System (OS) that is not well-known and is also not portable across various platforms. Figure 16.2 shows the mid-end mobile devices available from different manufacturers.
such as an accelerometer, advanced camera features, and Bluetooth. They have a better look and feel as compared to mid-end mobile devices.
445 of 590
Concepts
Session
16
Building a Mobile Web Application Figure 16.3 shows the high-end mobile devices.
devices have a full browser support similar to desktop browsers with wireless LAN and 3G connection. Apart from these, they have several advanced features that are as follows: Digital Compass Global Positioning System (GPS) Touch screen Camera with video recording TV out Bluetooth Accelerometer
Some of the popular smartphones available in the market are Apple iPhone, a wide range of BlackBerry smartphones, HTC Magic smartphone, Nokia Lumia, Samsung Galaxy series, and so on.
Concepts
446 of 590
Session
16
Building a Mobile Web Application
mobile computers with a touch screen virtual keyboard and stylus or digital pen. Features of tablets include: multi-touch display, better user experience, high quality screen resolution, better Web support, and multitasking OS with high speed. Some of the tablets available in the market are BlackBerry PlayBook Tablet PC, Samsung Galaxy Tab, and HCL Me Tab. Figure 16.5 shows different types of tablet devices.
447 of 590
Concepts
Session
16
Building a Mobile Web Application
Personal Digital Assistants (PDAs). The Palm OS was later on extended to support smartphones. Currently, Palm Inc. has developed webOS, which is based on the Linux kernel. webOS is now acquired by Helwlett-Packward and is used with various devices, such as Pre, Pixi, and Veer phones as well as HP TouchPad tablet.
Blackberry OS - It is a proprietary mobile OS developed by Research in Motion (RIM)
2.
3.
iOS - It is a mobile OS developed by Apple Inc. and was initially referred to as iPhone
OS. It is derived from Mac OS X, which is based on the UNIX platform. It was originally developed for iPhone and iPadTouch, but later extended to support other devices, such as iPad and Apple TV. iOS cannot be installed on non-Apple platforms.
Symbian - It is an open source mobile OS developed for mobile phones. It includes
4.
a user interface framework, libraries, and component tools. Symbian is the most widely supported platform for Nokia mobile devices. platform.
5. 6. 7.
Windows Mobile - It is a mobile OS that runs on top of the Windows Mobile Linux - It is an open source OS and is supported by smartphones that are manufactured
by Motorola.
smartphones and tablet computers. It can be customized by device manufacturers and community developers to extend the functionality of the devices.
Concepts
448 of 590
Session
16
Building a Mobile Web Application
Some of the basic considerations needed for designing a Web sites for intended mobile device are as follows:
The primary concern in designing a mobile Web site design is the screen resolution. The resolution means the number of pixels (width and height) on the screen of the mobile device. As there are no standards defined for screen resolution, it varies depending on its model and manufacturer. Table 16.1 lists the resolutions of mobile devices based on their categories.
Category
Low-end mobile devices Mid-end mobile devices High-end devices Smartphones
Table 16.1: Mobile Categories with Resolution The resolution of mobile devices is measured in terms of the physical dimensions of the screen. The screen dimensions are either measured diagonally in terms of inches/ centimeters or in terms of width and height. The relation between the physical dimension and resolution is termed as Pixels per Inch (PPI) or Dots per Inch (DPI). The higher DPI results in good print-quality graphics on the mobile device. Thus, the design of a Web site must be flexible and adjustable to meet the dimensions of the screen on which it is displayed.
449 of 590
Concepts
Session
16
Building a Mobile Web Application Table 16.2 lists the resolution and display sizes of different mobile devices.
Manufacturer
Apple Apple Apple BlackBerry HP Samsung Samsung Nokia
Model
iPad 3 iPhone 3GS iPhone 4S Torch 9810 TouchPad Galaxy S 4G Galaxy S II Lumia 800
Type
Tablet Smartphone Smartphone Smartphone Tablet Smartphone Smartphone Smartphone
The mobile devices are also categorized based on their orientation, vertical and horizontal. The vertical orientation devices are also referred to as portrait devices with taller display. Similarly, the horizontal orientation devices are referred as landscape devices with wider display. Figure 16.6 shows the mobile devices with vertical and horizontal screens.
Concepts
450 of 590
Session
16
Building a Mobile Web Application
Today, smartphones and tablets can switch between landscape and portrait views to present the better viewing of a Web page. This rotation capability of changing the view from landscape to portrait or vice-versa is due to the hardware accelerators available in the phones. Thus, a mobile Web site must be aware of these rotations and should be capable to provide a good user experience in both the orientations.
Input Methods
There are different methods to input data on the mobile devices. A mobile device can support more than one input method. Some of the possible input methods for a mobile device are as follows: Numeric keypad Alphanumeric keypad (Simple or QWERTY) Virtual keypad on screen Multi-touch External keypad Voice and handwriting recognition
Figure 16.7 shows a mobile device with QWERTY keyboard and touch screen.
451 of 590
Concepts
Figure 16.7: Mobile Device with QWERTY Keyboard and Touch Screen
Session
16
Building a Mobile Web Application
Navigation is the path followed by a user to travel in the Web site. As compared to the navigation tree of a desktop site, almost 80% of the information of a desktop site will not be useful to a mobile Web site. Thus, the main focus should be on 20%. Design Web pages based on the use cases. For example, some of the common use cases are: performing search for products and prices, performing search for nearest store location, or viewing a Contact us page. Arrange Web pages depending on the frequent requirements of the mobile users. This can be achieved through statistical information, or usability tests performed to keep the order updated. Restrict the depth of a mobile page to three clicks for a specific use case. Design minimum input controls for the form pages. Desktop Web site normally has a welcome screen. In case of mobile Web sites, avoid developing welcome screens. While designing a service, decide its usability. For example, before designing a service, such as locating a user, determine its usefulness as a service. Approximate the number of mobile pages required to separate services, after the home page.
Perspective
Concepts
The perspective of a mobile user is different from a desktop user in terms of needs and accessibility. Hence, a user-centric design approach should be followed for designing mobile Web sites. This ensures that a user completes the task easily and successfully. Some of the possible users contexts are as follows: What is the location of the user? Why is a mobile Web site accessed by the user? What are the needs of the user?
452 of 590
Session
16
Building a Mobile Web Application
What solution is offered by a mobile application to solve the users problem? Where is the user present while accessing a Web site? For example, a user can access the Web site while walking on the street, at a work place, at a public place, or so on.
Enhancement
Enhancement is a simple and powerful technique that can be adopted while designing a mobile Web site. This technique defines compatibility of Web site and allows access to basic content, services, and functionality on all type of mobile devices. Also, it provides a better Web experience on devices with higher standards. Some of the core principles for enhancing mobile Web sites are as follows:
Basic content and functionality are accessible in all browsers. Enhanced layout and behavior must be provided through external style sheets and JavaScript that are linked with the Web pages. Markup elements used on the pages must have proper semantic. Web browser settings on a users device should be considered.
The Web standards, such as HTML, CSS, and JavaScript followed in the mobile Web site design must be correctly used. This increases the possibility of displaying pages on large number of devices. The well-formedness of the markup tags used on a page can be achieved by validating them. Apart from validating HTML pages, use of certain HTML elements can be avoided while designing the Web pages for mobile devices. The brief description of these elements is as follows:
Use of HTML tables - As the screen size of mobile devices is small, so the use
of tables in layouts should be avoided. The reason to avoid tables is as it makes the scrolling difficult and also slows down the page loading in the browser. Also, tables are not rendered properly by the mobile devices.
Pop-up windows - The Web sites with pop-up windows makes the site
Use of graphics - The use of graphics increases download time of the pages.
Also, they can obstruct the layout of the old mobile browsers, resulting in incorrect display of the page.
Use of frames - Many mobile devices do not provide the support for frames
due to usability problems. Also, the HTML5 new specification does not provide the support for frames.
453 of 590
Concepts
impractical to work with. Also, all mobile browsers do not provide the support for them. Even, browsers providing support for pop-up windows may result in closing of the existing window.
Session
16
Building a Mobile Web Application
An IDE is a tool used for coding the markup, JavaScript, and CSS. Today in the market, there are different tools which provide the facility to easily build a mobile Web application. Some of these tools are as follows: Adobe Dreamweaver Microsoft Expression Web Aptana Studio Eclipse Editplus (text editor)
Latest versions of these tools provide better support for mobile markups. They also provide support for validating pages against mobile Web standards.
Emulators
The testing of a mobile Web application can be done using an emulator. An emulator is a software that translates the compiled code to the native platform on which the application is executed. The emulator runs as a desktop application that allows testing and debugging of a mobile application. It offers the environment similar to a real mobile device on which an application will be executed. In other words, it imitates the features, such as hardware and OS of a mobile device, to test and debug an application.
Concepts
Emulators are developed by manufacturers and are often offered free to users. They are either standalone applications or bundled with a Software Development Kit (SDK) for native development. Some of the popular emulators that either run as standalone applications or in an SDK are as follows: Android iOS V 1.1 Aptech Limited
454 of 590
Session
16
Building a Mobile Web Application
455 of 590
Concepts
Session
16
Building a Mobile Web Application
Two factors that need to be considered while designing a mobile Web application are its initial display (zoom) scale and orientation. Thus, it is necessary to inform mobile browsers to consider these factors while displaying a Web page. This can be achieved by using a <meta> tag. A <meta> tag indicate that the document is optimized for mobile devices and are used to control the display scale, while displaying HTML content on the device. It is specific to mobile browsers. Table 16.3 lists some of the variations of <meta> tag used for different mobile browsers.
Meta Tag
<meta name=HandheldFriendly content=true/>
Description
Indicates that the content is designed for small-screen handheld devices. The value true prevent the browsers from scaling the content <meta Accept width (in pixels) name=MobileOptimized to place the content and content=width /> forces the layout to one column in the browser <meta name=AppleIndicates that the Web mobile-web-app-capable application will run in a content=yes/> full-screen mode <meta name=FormatAutomatic detection of detection phone numbers is enabled content=telephone=no/> or disabled on Web pages Table 16.3: Meta Tags
Safari
Concepts
Similarly, a non-standard variation of <meta> tag is specified by giving an alternate <link> tag. This tag is mostly used with desktop Web pages and defines an alternative URL for displaying the same content on different medias, such as handled devices.
<link rel=alternate com /> media=handheld href=http://mysite.
456 of 590
Session
16
Building a Mobile Web Application
This is a technique used to inform the browser that the Web page is optimized for a mobile device. A viewport is the rectangular display area on the screen, where the content of a Web page are displayed by the browser. It contains attributes, such as width and height that can be set to larger or smaller values depending on the total visible area on the screen. The viewport meta tag is supported on many smartphones, such as iPhone, Android based phones, and browsers, such as Internet Explorer Mobile, Opera Mini, and Opera Mobile. Table 16.4 lists the attributes of the viewport meta tag.
Attribute
width
Description
Value
Integer value (in pixels) or constant device-width Integer value (in pixels) or constant device-height Floating value between 0.1 to n
Defines the horizontal size of the viewport in pixels height Defines the vertical size of the viewport in pixels initial-scale Sets the scale of the page for its initial display. Large value indicates zoomed in where as smaller value indicates zoomed out minimum-scale Defines the minimum zoom scale of the viewport maximum-scale Defines the maximum zoom scale of the viewport user-scalable Allows scaling of application on the mobile devices. In other words, users can zoom in and out in the application
Table 16.4: Viewport Meta Tag Attributes Code Snippet 1 demonstrates the viewport meta tag to set device width for a mobile Web page.
Code Snippet 1: <head> <!DOCTYPE html> <title>Mobile</title>
457 of 590
Concepts
Session
16
Building a Mobile Web Application
<!-- <meta name=viewport content=width=device-width, userscalable=no> --> </head> <body>
</NAV>
<p>
cross- platform. The vast number of mobile devices makes thorough testing a practical impossibility, leaving legacy browsers.
developers nostalgic for the days when they only had to support </p>
Concepts
In the code, the viewport width has been set to device-width which sets the device width to 320px. As all phones does not support the same width, so setting device-width allows the mobile browsers to set width according to the device width. Also, setting the attribute user-scalable=no prevents the user from increasing the display scale of the application. The default width taken for the viewport is 980px which is approximately the desktop size.
458 of 590
Session
16
Building a Mobile Web Application
Figure 16.8 displays the Web page on Opera Mobile Emulator, before setting the viewport meta tag.
Figure 16.8 : Output - Without Viewport Figure 16.9 displays the Web page on Opera Mobile Emulator after removing the comments from Code Snippet 1. The code sets the viewport meta tag.
Titles - Apart from <meta> tag, <head> element also contains a <title> tag which
should be taken into consideration, as the mobile browser is small as compared to a desktop browser. The text selected for <title> tag should be meaningful, short, and precise. It should be between four and eight words, as some old mobile devices truncate the long titles after 10 or 12 words. V 1.1 Aptech Limited
459 of 590
Concepts
Session
16
Building a Mobile Web Application
Icons - To add icons to a mobile Web page, images in GIF or PNG format could be
used. These formats are compatible with mobile devices, as they are easy to export and are optimized in size. For example,
<link rel=icon type=image/png href=mobile.png />
From HTML5 onwards, Android supports the apple-touch-icon-precomposed meta tag in order to display high-resolution icons.
The HTML5 new tags that provide semantics for the layout of an HTML document are as follows:
<article> - An independent portion of the document or site <figcaption> - Caption for a figure <aside> - Content that is tangential to the main part of the page or site <figure> - A figure or quotation pulled out of the flow of text <footer> - The footer of a document or section <hgroup> - A group of headings <nav> - A navigation section <header> - The header of a document or section
Images
Images can be used in mobile Web applications for pictorial representation. Almost all mobile browsers understand formats, such as GIF, JPEG, and PNG.
Concepts
However, images should not be used for setting background, buttons, links, or presenting titles on a mobile Web page. This is because images increase the number of request to the Web server and also load time of the Web page. The <img> tag is used to display image on a Web page. The attributes of <img> tag, such as width, height, and alt should be specified, as it reduces the rendering time of the image.
460 of 590
Session
16
Building a Mobile Web Application
461 of 590
Concepts
Session
16
Building a Mobile Web Application Figure 16.10 displays image on a mobile Web page.
A mobile Web application supports different types of lists. The various list types are as follows: a. b. c. Ordered lists - Used for navigational menus and are defined using <ol> tag on a Web page. Unordered lists - Used for presenting objects of same type and are defined using <ul> tag on a Web page. Definition lists - Used for presenting information as key/value pairs and are defined using <dl> tag on a Web page.
Code Snippet 3 demonstrates the use of a definition list to present the capacity list of different hardware components on a mobile Web page.
Code Snippet 3: <!DOCTYPE html> <head>
Concepts
</head>
462 of 590
Session
16
Building a Mobile Web Application
<body>
<header>
</body> </html>
</section>
</dl>
In the code, the <dl> tag is used to represent the information as key and value pair format. Figure 16.11 displays the definition list on a mobile Web page.
463 of 590
Concepts
Session
16
Building a Mobile Web Application
Links
Hyperlinks are used to link pages in a Web application. They are one of the important elements on Web pages and this holds true in case of mobile Web applications too. A hyperlink is defined using <a> tag with href attribute. The href attribute is set to the URL of a resource. Apart from href, the <a> tag should also have accesskey attribute specified with it. The accesskey attribute is a keyboard shortcut and is useful for mobile devices that have support for access keys. Code Snippet 4 demonstrates the use of <a> and <ul> tag to create a navigation list on a mobile Web page.
Code Snippet 4: <!DOCTYPE html> <head> <title>Navigation list</title> <meta name=viewport content=width=device-width, userscalable=no/> <link rel=apple-touch-icon-precomposed href=mobile.png /> </head> <body> <header> <h5> Main Menu </h5> </header> <NAV> <ul> <li><a title=Comprehensive Animation href=comprehensive. html accesskey=1>Comprehensive Animation Pro</a></li> <li><a title=2D and 3D href=animation_3d.html accesskey=2>2D & 3D Animation </a></li> <li><a title=3D Animation href=animation_2d.html
Concepts
464 of 590
Session
16
Building a Mobile Web Application
As mobile devices are basically phones, hence, links can be created to perform phone call actions. This is achieved using the tel:<phone number> scheme embedded with a hyperlink. The tel scheme is useful in situations, such as accessing helpdesk systems or voicemail systems. Code Snippet 5 demonstrates a tel scheme defined on a mobile Web page.
Code Snippet 5: <!DOCTYPE html> <head> <title> Mobile Application </title> <meta name=viewport content=width=device-width,minimum</head> scale=1.0,maximum-scale=1.0/>
465 of 590
Concepts
Session
16
Building a Mobile Web Application
<body> <header> <section><img src=logo.png border=1 alt=Arena Animation title=Arena Animation Home/> <b> Animation | Multimedia </b> </section> <nav> <ul> <li><a title=Comprehensive Animation href=#>Comprehensive Animation Pro</a></li> <li><a title=2D and 3D href=#>2D & 3D Animation </a></li> <li><a title=3D Animation href=#>Animation & 3D </a> </li> </ul> </nav> </header> <section id=intro> <p> Arena Animation is leader in animation and multimedia education with the widest network of centers across the country. Over a span of 14 years, 250,000 students and professionals have, through Arena, found their calling in animation, graphics, print publishing, web designing & films.</p> </section> <footer> <p> <a href=tel:+91 22 2827 2300>Contact us </a> <br/> Copyright © 2012 Aptech Ltd.</p>
Concepts
466 of 590
Session
16
Building a Mobile Web Application
Figure 16.13 displays the output of a Web page in a tablet selected in an Opera Mobile Emulator.
Apart from W3C specifications that are laid for CSS3, modern browsers have provided new styles for CSS3. These styles are specific to each browser. Therefore, to add these styles on a Web page, the relevant properties need to be prefixed with the browser specific keyword. The property prefixed with the keyword represents the browser on which it is supported. Table 16.5 lists the keywords with their supported browsers.
467 of 590
Concepts
Session
16
Building a Mobile Web Application
Keyword
-moz -ms -o -webkit
Browser
Firefox Internet Explorer Opera Google Chrome and Safari
Table 16.5: Keywords Supported by Browsers Code Snippet 6 demonstrates the CSS3 properties for a Web page that was developed in Code Snippet 5. These properties have been explored in the earlier sessions.
Code Snippet 6: <!DOCTYPE html> <head> <title> Mobile Application </title> <meta name=viewport content=width=device-width/> <style> html, body { margin: 0; padding: 0; border: 0; font-size: 100%; font-weight: normal; vertical-align: baseline; background: transparent; } body { line-height: inherit;
Concepts
468 of 590
Session
16
Building a Mobile Web Application
background-color:#A4A4FF; margin:0px; margin-top:5px; padding:0px; } ul#navigation { margin:0px; border-left:1px solid #c4bbe7; border-right:1px solid #c4dbe7; padding-top:5px; } ul#navigation li { display:inline; font-size:12px; font-weight:bold; margin:0; padding:0; float:left; position:relative; border-top:1px solid #c4dbe7; border-bottom:2px solid #c4dbe7; } ul#navigation li a { padding:10px; color:#616161; text-shadow:1px 1px 0px #fff; display:inline-block; border-right:1px solid #fff; border-left:1px solid #C2C2C2; border-top:1px solid #fff; text-decoration:none;
469 of 590
Concepts
Session
16
Building a Mobile Web Application
background: #f6f6f5; -webkit-transition:color 0.2s linear, background 0.2s linear; -moz-transition:color 0.2s linear, background 0.2s linear; -o-transition:color 0.2s linear, background 0.2s linear; transition:color 0.2s linear, background 0.2s linear; } ul#navigation li a:hover { background:#f8f8f8; color:red; } p{ border: 0; font-size: 100%; font-weight: normal; vertical-align: baseline; background: transparent; } a{ margin: 0; padding: 0; font-weight: normal; } #intro { background-color: yellow; border: solid black 2px; width: 600px; height: 150px; } </style> </head>
Concepts
470 of 590
Session
<body> <header>
16
Building a Mobile Web Application
<section><img src=logo.png border=1 alt=Arena Animation title=Arena Animation Home/> <b> Animation | Multimedia </b> </section> <nav id=nav> <ul id=navigation> <li> <a title=Comprehensive Animation href=#>Comprehensive Animation Pro</a></li> <li><a title=2D and 3D href=#>2D & 3D Animation </a></li> <li><a title=3D Animation href=#>Animation & 3D</a></li> </ul> </nav> </header> <section id=intro> <p style=font-size: 12px; font-style: italic; color:#0000FF> Arena Animation is leader in animation and multimedia education with the widest network of centers across the country. Over a span of 14 years, 250,000 students and professionals have, through Arena, found their calling in animation, graphics, print publishing, web designing & films.</p> </section> <footer> <p> <a href=tel:+91 22 2827 2300>Contact us </a> <br/> Copyright © 2012 Aptech Ltd. </footer> </body> </html> </p>
471 of 590
Concepts
Session
16
Building a Mobile Web Application Figure 16.14 displays the output of a mobile Web page with the CSS3 styles applied.
Media queries are used to target specific features, such as screen width, orientation, and resolution of the devices. The use of a media query is to display HTML pages on various devices, such as computers and mobile devices with different styles based on their media types. Earlier, CSS2 allowed creating style sheets for specific media types, such as screen and print. CSS3 has been enhanced further with the features of media queries. In media queries, expressions are added for specific media type, then checking for condition is done, and finally, respective style sheet is applied to a Web page. Media queries are used in two ways that are as follows:
Concepts
1. 2.
Inline within a CSS style sheet In the <link> tag as media attribute
472 of 590
Session
16
Building a Mobile Web Application
Code Snippet 7 shows the markup to apply a style sheet named screen.css to a device with screen and set the viewing-width of the area to 480.
Code Snippet 7: <link type=text/css rel=stylesheet media=only screen and (max-device-width: 480px) href=screen.css />
Some browsers can also interpret the CSS media queries placed inside a .css file. Code Snippet 8 shows the code to change the background color of a Web page depending on the device width.
Code Snippet 8: @media only screen and (max-device-width: 480px) { body { background-color: #666; } }
CSS media queries can also be used to define style sheets for different orientations. Code Snippet 9 shows the markups to serve style sheets based on the orientation of the device.
Code Snippet 9: <link rel=stylesheet media=all and (orientation: portrait) href=portrait_orientation.css /> <link rel=stylesheet media=all and (orientation: landscape) href=landscape_orientation.css />
Avoid horizontal scrolling, as some phones do not support horizontal scrolling and hide the content on the screen. Use buttons instead of providing many tiny links, as this can annoy the mobile users. This is also useful in situations where scaling of the page is disabled. Offer mobile users with the choice for viewing the site in the full version.
473 of 590
Concepts
Design of a mobile Web site that is simple to fit on small screens. The simplest layout which can be followed for mobile Web sites is a single column display.
Session
16
Building a Mobile Web Application 5. 6. Create cookies to store the users choice for viewing the full version of the site. This helps to restore the same view on every visit to the Web site. Avoid creating complex forms with many input fields, as data entry can be difficult on mobile devices compared to the desktops. Also, relevant input fields should be used for accepting the data. Limit the use of images due to bandwidth restrictions on mobile devices. Also, large and high-resolution images must be avoided. Add mobile specific functionalities, such as built-in GPS facility or call-in action links. This makes the Web sites similar to native applications. Use of good foreground and background colors is important as they makes the sites readable on small screens. Select technologies that are compatible with old mobile devices. Also, provide alternatives for functionalities, such as cookies, tables, style sheets, fonts, colors, and so on. Avoid use of pop-up windows, tables for layout, frames, and image maps in the mobile Web site design.
7. 8. 9. 10.
11.
Concepts
474 of 590
Session
16
Building a Mobile Web Application
2.
Which of the following elements should be avoided while designing a mobile Web site? (A) table (B)
image
(C) (D)
frame form
3.
Identify the factors that need to be considered while designing a mobile Web application. (A) Display scale (B) Orientation (C) (D) Input mechanism Operating system
4.
Match the different mobile operating systems with their respective descriptions.
Mobile OS Description
1. 2. 3. 4. (C) (D)
Based on Java platform Based on windows mobile platform Derived from MAC OS based on UNIX platform Open source OS developed by Google a-3, b-1, c-2, d-4 a-4, b-3, c-2, d-1
(D) BlackBerry (A) a-4, b-1, c-2, d-3 (B) a-1, b-3, c-4, d-2
475 of 590
Concepts
Session
16
Building a Mobile Web Application 5. Which of the following is the non-standard variation of <meta> tag? (A) Viewport meta tag (B) WebKit extensions (C) (D) Media queries link tag
Concepts
476 of 590
Session
16
Building a Mobile Web Application A A, C A, B D D
16.7.1 Answers
1. 2. 3. 4. 5.
477 of 590
Concepts
Session
16
Building a Mobile Web Application
Summary
A mobile device is a small portable computing device with a small display screen and keyboard. The different categories of mobile devices available in the market are: basic model, low-end mobile devices, mid-end mobile devices, high-end mobile devices, smartphones, and tablets. A mobile platform is basically responsible to interact with the device hardware and run software/services on the mobile device. Different platforms for mobile devices include: Palm OS, Blackberry, iOS, Symbian, Windows Mobile, and Android. An ideal mobile Web site is supported and rendered properly by maximum possible browsers and OS. Two factors that need to be considered while designing mobile Web application are its initial display (zoom) scale and orientation. The use of media query is to display HTML pages on different devices with different styles based on their media types.
Concepts
478 of 590
Session
16
Building a Mobile Web Application
Try it Yourself
1. Create a mobile Web site for a restaurant. The Web site should display details of the restaurant, such as cuisine, its specialty, and prices of food items served there. It should also allow the user to book a table or order food from the Web site. Some points to be followed while designing the application are as follows: a. b. c. The Web site need to be displayed on all types of mobile devices and should fit according to the display size. Use CSS3 properties to enhance the appearance of the Web site. Provide a facility for a user to make a phone call and place an order on the Web site.
479 of 590
Concepts
A wise man learns from the mistakes of others, a fool by his own
Session
16
Building a Mobile Web Application (Workshop)
Note - Please refer to the respective lab deliverable for demonstrations and guided
simulations.
Labs
482 of 590
17
Session
17
Canvas and JavaScript
17.1 Introduction
Canvas is one of the most interesting features added in HTML5. The <canvas> element supports advanced graphics and interactions in many forms. In earlier versions of HTML, you could achieve this by using plug-ins. Using the <canvas> element eliminates the need for such plug-ins and makes working with graphics easier and more efficient. The <canvas> element is a drawing area where the user can draw graphics, use images, add animations, and also add text for enhancing the user experience on Web pages.
Concepts
484 of 590
Session
17
Canvas and JavaScript
In the code, the <style> element is used to display the border of the <canvas> element. The height and width attributes specify the size of the <canvas> element on the page. Figure 17.1 displays the <canvas> element.
Figure 17.1: <Canvas> Element To draw a <canvas> element, the user can use a context object. The context object contains the drawing functions for a specific style of graphics. Two-Dimensional (2d) context is used to work with 2d operations. The <canvas> element in DOM exposes the HTMLCanvasElement interface. This interface provides the methods and properties for changing the presentation and layout of canvas elements. The HTMLCanvasElement has a getContext(context) method that returns the drawing context for the canvas. Code Snippet 2 demonstrates the 2d context object for the canvas.
Code Snippet 2: <!DOCTYPE HTML> <head> <title> Canvas </title> <script> window.onload = function() { <html>
485 of 590
Concepts
Session
17
Canvas and JavaScript
var canvas = document.getElementById(mCanvas); var ctext = canvas.getContext(2d); ctext.beginPath(); ctext.rect(18, 50, 200, 100); ctext.fillStyle = DarkBlue; ctext.fill(); }; </script> </head> <body> <canvas id=mCanvas width=578 height=200></canvas> </body> </html>
In the code, the height and width attributes define the height and width of the canvas element respectively. In the initializer function, the DOM object is accessed through the id attribute and gets a 2d context by using the getContext() method. Here, the rectangle is created by using the rect(18, 50, 200, 100) method with x, y, height, and width parameters and is positioned at left corner of the page. Figure 17.2 displays the canvas.
Concepts
Session
17
Canvas and JavaScript
where,
ctext - specifies a context object beginPath() - Specifies a new drawing path moveTo() - Specifies the creation of new sub path to the given position lineTo() - Specifies the drawing of a line from the context position to the given position stroke() - Specifies how to assign a color to the line and display it
487 of 590
Concepts
#mCanvas {
Session
17
Canvas and JavaScript
window.onload = function() { var canvas = document.getElementById(mCanvas); var ctext = canvas.getContext(2d); ctext.beginPath(); ctext.moveTo(100, 150); ctext.lineTo(250, 50); ctext.lineWidth = 5; ctext.strokeStyle = blue; ctext.stroke(); }; </script> </head> <body> <canvas id=mCanvas width=360 height=200></canvas> </body> </html>
In the code, the height and width attributes are defined. The initializer function has the DOM object which is accessed through the id attribute and gets a 2d context by using the getContext() method. The beginPath() method is called through the context object to draw the path of the line. The moveTo(100, 150) method is called that creates a new path for the given point to place the drawing cursor. This method moves the position of the window to the upper-left corner by giving the x and y coordinates. The lineTo(250, 50) method is called to draw the line from the context point to given point. The lineWidth property is specified as 5 to define the width of the line on the canvas. The strokeStyle property sets the color of the line to blue. The stroke() method assigns the color to the line.
Concepts
488 of 590
Session
17
Canvas and JavaScript
With HTML5 canvas, the user can create a rectangle using the rect() method. The HTML5 canvas is placed by using the x and y parameters and appropriately sized through height and width properties. There is a collection of methods and properties that are used to draw different types of shapes. Table 17.1 lists the common properties and methods of various shapes.
Description
489 of 590
Concepts
The values can be gradient, pattern, or a CSS color. The default property style is solid black, but the user can set the color according to the requirements. f i l R e c t ( x , y , w i d t h , Enables the user to draw a rectangle with the height) existing fill style. strokeStyle() The values can be gradient, pattern, or a CSS color.
Session
17
Canvas and JavaScript
s t r o k e R e c t ( x , y , Enables the user to draw a rectangle with the width, height) existing stroke style. This property is used to draw
Description
the edges of the rectangle. clearRect(x, y, width, Used to clear the pixels in a rectangle.
height)
Table 17.1: Common Properties and Methods of Various Shapes Code Snippet 4 demonstrates how to create a rectangle in HTML5 canvas.
Code Snippet 4: <!DOCTYPE HTML> <html> <head> <style> #mCanvas { border: 1px solid green; } body { margin: 0px; padding: 0px; } </style> <script> window.onload = function() { var canvas = document.getElementById(mCanvas); var ctext = canvas.getContext(2d); ctext.beginPath(); ctext.rect(30, 50, 150, 100); ctext.fillStyle = Magenta; ctext.fill(); ctext.lineWidth = 5; ctext.strokeStyle = black; ctext.stroke();
Concepts
490 of 590
Session
};
17
Canvas and JavaScript
In the code, the height and width attributes are defined. The initializer function has the DOM object which is accessed through the id attribute and gets a 2d context by using the getContext() method. The beginPath() method is called through the context object to draw the rectangle. The rect(30, 50, 150, 100) method takes x, y, height, and width as the parameters. The fillStyle property fills the rectangle with magenta color. The fill() method is used to paint the rectangle. The lineWidth property is specified as 5 to define the width of line on the canvas. The strokeStyle property sets the stroke style of the rectangle to black. The stroke() method assigns the color to the rectangle. Figure 17.4 displays a rectangle drawn on the canvas.
With HTML5 canvas, the user can create an arc by using the arc() method. Arcs are represented using a start angle, an end angle, a radius, a center point, and the drawing direction (anticlockwise or clockwise).
491 of 590
Concepts
Session
17
Canvas and JavaScript The syntax to draw an arc in HTML5 is as follows:
Syntax: arc(x, y, radius, startAngle, endAngle, anticlockwise)
where,
radius - Specifies the distance from the center to any point on the circle startAngle, endAngle - Specifies the start and end points in the arc
anticlockwise - Draws the arc clockwise or anticlockwise and accepts a boolean value
Concepts
492 of 590
Session
17
Canvas and JavaScript
ctext.beginPath(); ctext.arc(x, y, radius, startAngle, endAngle, ctrClockwise); ctext.lineWidth = 25; // line color ctext.strokeStyle = DarkGreen; ctext.stroke(); }; </script> </head> <body> <canvas id=mCanvas width=278 height=250></canvas> </body> </html>
In the code, the beginPath() method is called through the context object to draw an arc by using the arc() method which has x, y, and radius as the parameters. The x and y are the coordinates of the circle, radius is the distance from the center to draw the arc on the canvas. The startAngle and the endAngle are the start and end points of the arc respectively. The anticlockwise specifies the direction of the arc between the two start and end points.
493 of 590
Concepts
Session
17
Canvas and JavaScript Figure 17.5 displays an arc in HTML5 canvas.
In HTML5, you can draw a circle using the arc() method. You have to set the start angle with 0 and the end angle is specified as 2 * PI. The following is the syntax to draw a circle in HTML5 is as follows:
Syntax: arc(x, y, radius, startAngle, endAngle, anticlockwise)
where,
x, y - Specifies the coordinates of the center of a circle radius - Specifies the distance from the center to any point on the circle startAngle, endAngle - Specifies the start and end points in the circle anticlockwise - Draws the circle clockwise or anticlockwise and accepts a boolean value
Concepts
494 of 590
Session
17
Canvas and JavaScript
495 of 590
Concepts
Session
17
Canvas and JavaScript
<body> <canvas id=mCanvas width=356 height=150></canvas> </body> </html>
In the code, a circle is defined by using the arc() method which has ctrX, ctrY, and radius as the parameters. To define the arc with the points the startAngle is set to 0 and the endAngle is specified as 2*PI. The anticlockwise defines the direction of the path of an arc between the two start and end points. Figure 17.6 displays a circle in HTML5 canvas.
Using HTML5 canvas, you can create a Bezier curve using the bezierCurveTo() method. Bezier curves are represented with the two control points, context points, and an end point. Code Snippet 7 demonstrates how to create a Bezier curve using HTML5.
Code Snippet 7: <!DOCTYPE HTML> <html> <head> <style> body { margin: 0px;
496 of 590
Concepts
Session
}
17
Canvas and JavaScript
padding: 0px; #mCanvas { border: 1px solid maroon; } </style> <script> window.onload = function() { var canvas = document.getElementById(mCanvas); var ctext = canvas.getContext(2d); ctext.beginPath(); ctext.moveTo(188, 130); ctext.bezierCurveTo(140, 10, 388, 10, 288, 100); ctext.lineWidth = 15; // line color ctext.strokeStyle = purple; ctext.stroke(); }; </script> </head> <body> <canvas id=mCanvas width=378 height=200></canvas> </body> </html>
497 of 590
Concepts
In the code, the Bezier curve uses the bezierCurveTo() method. This method defines the current context point, two control points, and an end point. The context point uses the moveTo() method. The first portion of the curve is tangential to the imaginary line defined in the context point and first control point. The second portion of the curve is tangential to the imaginary line which is defined by the second control point and the ending point.
Session
17
Canvas and JavaScript Figure 17.7 displays a Bezier curve in canvas.
HTML5 canvas allows the user to create quadratic curves using the quadraticCurveTo() method. Quadratic curves are represented through the context point, an end point, and a control point. Code Snippet 8 demonstrates how to create a quadratic curve using HTML5.
Code Snippet 8: <!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } #mCanvas { border: 1px solid #9C9898; }
Concepts
498 of 590
Session
17
Canvas and JavaScript
window.onload = function() { var canvas = document.getElementById(mCanvas); var ctext = canvas.getContext(2d); ctext.beginPath(); ctext.moveTo(178, 150); ctext.quadraticCurveTo(220, 0, 320, 150); ctext.lineWidth = 15; // line color ctext.strokeStyle = Fuchsia; ctext.stroke(); }; </script> </head> <body> <canvas id=mCanvas width=378 height=200></canvas> </body> </html>
In the code, the control point defines the curve of the quadratic by two tangential lines that are connected to both the context point and the end point. The context point is represented using the moveTo() method. This method moves the control point from the context point and the end point to create a sharper curve. It also moves the control point close to the context point and end point to create broad curves. Figure 17.8 displays a quadratic curve in a canvas.
499 of 590
Concepts
Session
17
Canvas and JavaScript
Concepts
500 of 590
Session
<body>
17
Canvas and JavaScript
In the code, the onload property is used. The source of the object is defined by using the src property. The image has to be loaded first and then instantiated with the drawImage() method. This method takes image object as the parameter with the x and y coordinates of the image. Figure 17.9 displays an image drawn on a HTML5 canvas.
Figure 17.9: Image Drawn on a HTML5 Canvas You can also set the size of the image by adding two parameters width and height to the drawImage() method.
501 of 590
Concepts
Session
17
Canvas and JavaScript Code Snippet 10 demonstrates how to resize images with height and width attributes using HTML5.
Code Snippet 10: <!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } #mCanvas { border: 1px solid black; } </style> <script> window.onload = function() { var canvas = document.getElementById(mCanvas); var ctext = canvas.getContext(2d); var x = 69; var y = 50; var w = 150; var h = 137; var imgObj = new Image(); imgObj.onload = function() { ctext.drawImage(imgObj, x, y, w, h); }; imgObj.src = bird.jpg; }; </script> </head> <body>
Concepts
502 of 590
Session
</body> </html>
17
Canvas and JavaScript
In the code, the drawImage() method accepts two additional parameters height and width for resizing the image. Figure 17.10 displays resizing an image in a HTML5 canvas.
503 of 590
Concepts
Session
17
Canvas and JavaScript
margin: 0px; padding: 0px; } #mCanvas { border: 1px solid blue; } </style> <script> window.onload = function() { var canvas = document.getElementById(mCanvas); var ctext = canvas.getContext(2d); ctext.font = italic 30pt Calibri; ctext.fillStyle = MediumVioletRed; ctext.fillText(Welcome to HTML5!, 40, 100); }; </script> </head> <body> <canvas id=mCanvas width=380 height=170></canvas> </body> </html>
In the code, the font text is specified as Calibri, style as italic, and size is set to 30pt. The fillStyle property specifies the text color and the fillText property is used to set the text on the canvas.
Concepts
504 of 590
Session
17
Canvas and JavaScript
Figure 17.11: Working with Text in a HTML5 Canvas In HTML5 canvas, the user can set the stroke color by using the strokeText() method and strokeStyle property of the canvas context. Code Snippet 12 demonstrates the use of stroke text in HTML5 canvas.
Code Snippet 12: <!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } border: 1px solid black; } </style> <script> window.onload = function() {
505 of 590
Concepts
#mCanvas {
Session
17
Canvas and JavaScript
var canvas = document.getElementById(mCanvas); var ctext = canvas.getContext(2d); var x = 80; var y = 110; ctext.font = 40pt Calibri; ctext.lineWidth = 2; // stroke color ctext.strokeStyle = Brown; ctext.strokeText(HTML5, x, y); }; </script> </head> <body> <canvas id=mCanvas width=360 height=200></canvas> </body> </html>
In the code, the stroke color is set by using the strokeStyle property and the strokeText() method. Figure 17.12 displays the stroke text in HTML5 canvas.
Concepts
Session
17
Canvas and JavaScript
There are two ways to set the transparency for the text and shapes. The first method is to use the strokeStyle and fillStyle by using the rgb function. The second method is to use globalAlpha drawing state property, which can be applied universally. The globalAlpha property is a value that ranges between 0 (fully transparent) and 1 (fully opaque). Code Snippet 13 demonstrates the use of globalAlpha property.
Code Snippet 13: <!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } #mCanvas { border: 1px solid black; } </style> <script> window.onload = function() { var canvas = document.getElementById(mCanvas); var ctext = canvas.getContext(2d); ctext.fillStyle = Indigo; ctext.strokeStyle =black; ctext.lineWidth=2; ctext.fillText(HTML5, 40, 100); ctext.strokeText(HTML5, 40, 100);
507 of 590
Concepts
Session
17
Canvas and JavaScript
ctext.fillStyle=blue; }; </script> </head> <body> <canvas id=mCanvas width=350 height=170></canvas> </body> </html> ctext.globalAlpha=0.5; ctext.fillRect(100, 10, 150, 100);
In the code, the fillStyle and strokeStyle is used to color the text. The HTML5 text lineWidth is specified as 2 and the font-family is set to Calibri with italic style and font-size to 30pt. The fillText property fills the color and strokeText property applies the stroke color to the HTML5 text. The fillStyle is set to blue and globalAlpha property is set to 0.5. The fillRect(100, 10, 150, 100) specifies the x, y, height, and width of the rectangle. Figure 17.13 displays the transparency in text.
Concepts
508 of 590
Session
17
Canvas and JavaScript
The mouseenter and mouseleave are the two events often used together. For example, when a user moves a mouse over a menu, a tooltip appears and when the user moves the mouse off the menu, the tooltip disappears. Combining these two events is very common, therefore, jQuery provides a hover() function that accepts two parameters. The first parameter executes when the mouse moves over the element and the second function executes when the mouse moves away from the element. Code Snippet 14 demonstrates the hover event.
Code Snippet 14: <!DOCTYPE html> <html> <head> <script src=jquery-1.7.2.min.js></script> <script> $(document).ready(function(){ $(p).hover(function(){ $(p).css(background-color,red); },function(){ $(p).css(background-color,maroon); }); }); </script> </head> <body> <p>Hover the mouse on this line.</p> </body> </html>
In the code, the hover() method is used. When the mouse is placed on the text, then the background color changes to red. Similarly, when the user moves the mouse outside the text, the background-color changes to maroon.
509 of 590
Concepts
Session
17
Canvas and JavaScript Figure 17.14 displays the mouseenter effect.
Figure 17.14: Mouseenter Effect Figure 17.15 displays the mouseleave effect.
The toggle() event works in a similar manner as that of the hover() event, except that it responds to mouse clicks. The toggle() function accepts more than two functions as arguments. For example, you want to perform some action on the first click, another action on the second click, and one more action on the third click. All the functions passed to the toggle() event will react to its corresponding click action.
Concepts
510 of 590
Session
17
Canvas and JavaScript
In the code, the toggle() method is used. When the user clicks the text then the background-color of the document is changed to blue, pink, and grey respectively.
511 of 590
Concepts
Session
17
Canvas and JavaScript Figure 17.16 displays the toggle effect to blue.
Figure 17.16: Toggle Effect to Blue Click the text and it will change the background-color to pink. Figure 17.17 displays the toggle effect to pink.
Figure 17.17: Toggle Effect to Pink Click the text and it will change the background-color to grey.
Concepts
512 of 590
Session
17
Canvas and JavaScript
In the code, the src attribute specifies the path of an external file to embed.
513 of 590
Concepts
Session
17
Canvas and JavaScript
2.
The ___________ property can be a gradient, pattern, or a CSS color. (A) fillText (B) strokeText (C) (D) strokeStyle fillStyle
3.
Which of the following methods is used to draw a circle in HTML5 canvas? (A) line() (B)
stroke()
(C) (D)
arc() rect()
4.
Which of the following events respond to mouse clicks? (A) hover() (B)
pressed()
(C) (D)
toggle() changed()
5.
Which of the following methods are used to draw an image object on canvas? (A) drawImage() (B)
draw()
(C) (D)
hover() onload()
Concepts
514 of 590
Session
17
Canvas and JavaScript A D B C A
17.10.1 Answers
1. 2. 3. 4. 5.
515 of 590
Concepts
Session
17
Canvas and JavaScript
Summary
The <canvas> element is a drawing area where the user can draw graphics, use images, add animations, and also add text for enhancing the user experience on Web pages. To create a line, on a canvas one can use the stroke(), beginPath(), lineTo(), and moveTo() methods. Arcs are represented using a start angle, an end angle, a radius, a center point, and the drawing direction (anticlockwise or clockwise). With HTML5 canvas, the user can create a rectangle using the rect() method. Bezier curves are represented with the two control points, context points, and an end point. HTML5 canvas allows the user to create quadratic curves using the quadraticCurveTo() method. HTML5 canvas enables the user to draw image object on canvas using the drawImage() method.
Concepts
516 of 590
Session
17
Canvas and JavaScript
Try it Yourself
1. Jack is developing a Web site for his company named Decant Technologies, headquartered at Germany. The company Web site was developed on HTML 4. Now, they have decided to upgrade the Web site using HTML5. The Web site deals with different types of software products such as educational, applications, games, computer accessories, anti-virus, and many more. Recently, the company has launched some new software for kids education and Jack has to add some shapes, images, and text to the new Web pages. Jack has decided to use the canvas element. Help him to develop the application. Robin is creating a Web site for his company named Maxim Technologies, headquartered at California. He wants to create an HTML5 Web site for his company. The company Web site deals with different types of mobile products such as laptops, smartphones, ipads, tablets, and notebooks. Robin wants to develop their company Web site home page and add the details about the company. He also wants to add different types of images, text, videos, and arrange the content in an organized manner. He has decided to use canvas for the home page. Help him to develop the application.
2.
517 of 590
Concepts
Real generosity towards the future lies in giving all to the present
Session
17
Canvas and JavaScript (Workshop)
Note - Please refer to the respective lab deliverable for demonstrations and guided
simulations.
Labs
520 of 590
18
Session
18
HTML5 Web Storage
18.1 Introduction
Consider an e-mail client, such as Gmail. To log in to your mail account in Gmail, you need to enter your username and password. Figure 18.1 shows the login screen of Gmail.
Figure 18.1: Login Screen of Gmail As shown in figure 18.1, the Stay signed in check box, specifies that the login details, such as Username and Password, should be remembered by the computer. Traditionally, over the last few decades, Web applications have been using cookies to store small amounts of information on a users computer. A cookie is a file that stores user-related information and may either be temporary or permanent. Thus, in this case, a cookie can be created for login details which can be saved for a specified period on a users computer. However, the drawbacks of cookies are as follows: Cookies slow down the performance of Web application, as they are included with every HTTP request. Cookies cannot be considered as safe means for transmission of sensitive data. Cookies cannot store large amount of information, as they have a limitation of size of 4 KB.
Concepts
To overcome these drawbacks and offer a solution to store data on the client-side, W3C has designed a specification named Web Storage API. V 1.1 Aptech Limited
522 of 590
Session
18
HTML5 Web Storage
The Web storage provides the functionality using which data can be stored on the client-side for a session or beyond the session.
523 of 590
Concepts
Session
18
HTML5 Web Storage Table 18.1 lists the support of various browsers for HTML5 Web storage.
Version
8.0+ 3.6+ 4.0+ 5.0+ 10.5+
Concepts
Session
} </script> </head>
18
HTML5 Web Storage
Here, in the code, the if statement checks whether a property named sessionStorage exists in the global window object. If the property exists, it means that session storage is supported and an appropriate message is displayed to indicate the same. If however, the property does not exists, it means session storage is not supported on that browser, and an appropriate message is displayed to indicate the same. Figure 18.2 shows the Web storage support.
525 of 590
Concepts
Session
18
HTML5 Web Storage For example, the function, parseInt() is used to convert data into an appropriate JavaScript data type. Table 18.2 lists some examples of named key/value pairs belonging to various data types.
Key
Name book Email car age uservalid
Value
Sarah C Programming [email protected] Toyota Innova 28 true
Table 18.2: Key/Value Pairs There are several operations that can be performed with the sessionStorage object. These operations are described as follows:
Storing and retrieving data
The setItem() and getItem() methods are used to store and retrieve data from session storage respectively. The syntax to use the setItem() and getItem() methods is as follows:
Syntax: To assign data sessionStorage.setItem(key, value);
where,
key: Is the named key to refer to the data value: Is the data to be stored To retrieve data var item = sessionStorage.getItem(key);
where,
Concepts
item: Is the variable into which the data will be saved key: Is the named key to refer to the data
526 of 590
Session
18
HTML5 Web Storage
Code Snippet 2 demonstrates how to set and retrieve a name using sessionStorage object.
Code Snippet 2: <!DOCTYPE html> <html> <head> <title>Working with Session Storage</title> <script> function testStorage() { if ((sessionStorage in window) && window[sessionStorage] !== null) { sessionStorage.setItem(name, Sarah); alert(The name is: + sessionStorage.getItem(name)); } } </script> </head> <body onload= testStorage();> </body> </html>
The code stores the string literal Sarah in the key, name. This is done using the setItem() method. Then, the string literal is retrieved and displayed as an alert using the alert() method on the browser page. To retrieve the string literal, the getItem() method has been used in the code.
527 of 590
Concepts
Session
18
HTML5 Web Storage Figure 18.3 shows the output for storing and retrieving name on the Web page using sessionStorage object.
Key names need not necessarily be given as strings. Even, a number can be specified as a key name, though internally while storing, it will be converted to a string. Code Snippet 3 shows the script that uses number as the key.
Code Snippet 3: <script> function testStorage() { if ((sessionStorage in window) && window[sessionStorage] !== null) { sessionStorage.setItem(6, The book was wonderful); var feedback = sessionStorage.getItem(6); alert(feedback); } } </script>
Concepts
Here, in the code, the key is set to a numeric value 6, but that does not mean that it is the sixth key. The name of the key is defined as 6 that is stored internally in the browser. The getItem() method is used to retrieve the value stored with that key. Finally, the value having the key as 6 is displayed in the alert window.
528 of 590
Session
18
HTML5 Web Storage
Figure 18.4 shows the output that retrieves value stored at the key, 6.
Figure 18.4: Output Retrieves Value Stored at Key 6 Similar to other JavaScript objects, the sessionStorage object can be treated as an associative array. Instead of using the getItem() and setItem() methods, an array subscript can be used to retrieve and assign the data. For example, sessionStorage.setItem(name,John); can be written as
sessionStorage[name] =John; alert (sessionStorage[name]);
Similarly, alert (sessionStorage.getItem(name)); can be written as As mentioned earlier, it is also possible to store non-string values into session storage. Code Snippet 4 demonstrates the storage of an integer value for age and is later retrieved by using parseInt() method along with the getItem() method.
Code Snippet 4: <!DOCTYPE html> <html> <head> <meta charset=utf-8> <title> Session Storage </title> <script> function store() {
529 of 590
Concepts
Session
18
HTML5 Web Storage
sessionStorage.setItem(age, document.getElementById(age).value); var agevalue = parseInt(sessionStorage.getItem(age)); alert(data + is + agevalue + years old); } } </script> </head> <body> <form name=myform> <label> Enter Name: </label> <input type=text id=name> <br /> <label> Enter Age: </label> <input type=text id=age> <br/> <input type=button value=Submit onclick=store()/> </form> </body> </html>
In the code, the parseInt() method converts the specified argument to an integer format. Figure 18.5 shows the output for storing and retrieving the form data having integer values.
Concepts
530 of 590
Session
18
HTML5 Web Storage
It is also possible to remove and clear data from the session storage. The removeItem() method is used to remove a particular item from the list. The syntax for the removeItem() method is as follows:
Syntax: sessionStorage.removeItem(key);
where,
To remove the value associated with the key, username set in Code Snippet 4, the statement must be specified as follows:
sessionStorage.removeItem(username);
Similarly, in order to clear all items present in the session storage, use the clear() method as shown: Also, the length attribute determines the number of key/value pairs present in the storage.
var itemcount = sessionStorage.length; sessionStorage.clear();
Code Snippet 5 demonstrates the use of local storage to store the value of username field and later, retrieve the value in another Web page.
Code Snippet 5: <!DOCTYPE html> <head> <script> function store() {
531 of 590
Concepts
Session
18
HTML5 Web Storage
if ((localStorage in window) && window[localStorage] !== null) { var username = document.getElementById(username).value; localStorage.setItem(username, username); } function cancel_store() { if ((localStorage in window) && window[localStorage] !== null) { localStorage.removeItem(username); } </script> </head> <body> <form method=get action=success.html> Username: <input type=text id=username value= size=20 onblur=store()/> } else { alert (your browser does not support storage); } else { alert (your browser does not support storage); } }
Concepts
532 of 590
Session
</body> </html>
18
HTML5 Web Storage
Here, in the code, the support of localStorage object is checked in the current browser. If it is supported, then the contents of the username box are retrieved and stored in a variable named username. Then, the content of this variable is assigned to the local storage object with the key set as username. If localStorage object is not supported, an appropriate message is displayed in the alert window. Also, the function cancel_store() is invoked when the user clicks Cancel. In the cancel_store() function, the removeItem() method removes the specified key and its value from local storage. When the Submit button is clicked, the user is redirected to the Web page, success.html, which displays the value stored with the key, username. Code Snippet 6 shows the success.html page that retrieves value from the local storage and displays it in the browser.
Code Snippet 6: <!DOCTYPE html> <head> <title> Local Storage </title> <script> function print() { var username = localStorage.getItem(username);
document.getElementById(lblMsg).innerHTML = Username: is <b>+ username+</b>; } <body onload=print()> <label id=lblMsg></label><br> </body> </html> </script> </head>
533 of 590
Concepts
Session
18
HTML5 Web Storage Here, in the code, getItem() method of local storage retrieves the value from the username key and stores in the variable username. Then, the value of the variable username is displayed in the <label> tag. Figure 18.6 shows the output of the Web page with the user input, John.
Figure 18.6: Output Web page with User Input Figure 18.7 shows the output of success.html Web page that displays the value for username key stored in the local storage.
Concepts
534 of 590
Session
18
HTML5 Web Storage
Table 18.3 lists the browser support for the IndexedDB API.
IE
6.0 7.0 8.0 9.0 10.0ms
Firefox
3.6 8.0moz 9.0moz 10.0moz 11.0moz 12.0moz
Chrome
16.0webkit 17.0webkit 18.0webkit 19.0webkit
Safari
5.0 5.1 6.0 -
Opera
11.6 12.0 -
iOS Safari
3.2 4.0-4.1 4.2-4.3 5.0 -
database contains a name that identifies the origin of the database and a version number which identifies the lifetime of the database.
Object Store - Object store is the main mechanism to store data in a database. They
Keys - Each record stored in the database is identified by a unique key. Values - Values are the data stored in the records. Key Path - A key path is a string that defines how the browser should extract key
from a value. The key from a value can be extracted either in the object store or index. An empty string, a JavaScript identifier, and so on is some of the valid key paths.
Index - It is used when the data from the object store is retrieved based on some
other values other than a key. It is a specialized object store which searches for records in another object store known as referenced object store.
Transaction - Any addition or retrieval of the data in a database is performed by
using transaction. In other words, it is a mechanism used for interacting with the database. Each transaction has a mode, scope, and a request list. The mode determines the type of transaction that can be performed, scope identifies the object store on which the transaction will be performed, and finally request list determines the requests that have been made.
535 of 590
Concepts
Session
18
HTML5 Web Storage
Requests - Operations, such as reading or writing on the database is performed
using a request. Each request contains attributes, such as flag, source object, result, and error.
Cursor - Cursor is a mechanism used to retrieve multiple records from a database.
Key Range - Records from the object stores and indexes are retrieved using keys
or key ranges. A key range refers to retrieval of data between specified bounds based on the keys.
Open a database Create an object store Start a transaction Perform some database operations, such as add and retrieve Work with the retrieved results
Opening a Database
Concepts
536 of 590
Session
18
HTML5 Web Storage
Here, the code detects the support for IndexedDB API in different browsers and creates the indexedDB object. The indexedDB object contains a method named open() which opens the CompanyDB database. In case, if the database exists, then open() method simply opens it, otherwise creates the database. The open() method returns an IDBRequest object named request. The request object provides handlers, such as success and error. These handlers are invoked depending on the success or failure of opening the database. The onsuccess() handler contains an event of type success as its argument. Similarly, onerror() handler is invoked with an error event as its argument.
Updating Version of a Database
After the database is opened, it can be structured by providing a version number. This helps to set up the database. The version number will be specified to a database in the onsuccess() function. Code Snippet 8 shows the code that specifies the version number to the database CompanyDB.
Code Snippet 8: var setVrequest = db.setVersion(1.99); setVrequest.onsuccess = function(event) { ... } Creating the Object Store
The structure of IndexedDB database facilitates the storage of multiple object stores. In other words, there can be more than one object stores in the database. Object store is created using createObjectStore() method. The createObjectStore() methods accepts two arguments namely, the store name and a parameter object. The parameter object is used for defining an optional property which is important. In this case, a key path is defined that is used for identifying unique objects in the object store. For example, an employee store contains the id property as key path, which will be unique for each object and must be present for each object.
537 of 590
Concepts
Session
18
HTML5 Web Storage Code Snippet 9 demonstrates the code to create an object store named employee in the CompanyDB database.
Code Snippet 9: var employeeData = [ { name: John Smith, email: [email protected] },
];
var objectStore = db.createObjectStore(employee, { keyPath: id, autoIncrement: true }); for (i in employeeData) { objectStore.put(employeeData[i]); alert(Record added); }
The code creates an array named employeeData containing name and e-mail values. Then, the createObjectStore() method creates an employee store with its key path set to id attribute. The key path is used with autoIncrement option that automatically generates id for each of the objects. All the individual objects in the object store are identified based on the id. Finally, the for..in loop stores the data in the employee object store.
Creating a Transaction
To perform database operation, such as retrieving data from the object store, IndexedDB provides a IDBTransaction object. This object can be created in three mode namely, read-only, read-write, and snapshot. The read-write mode is used to update the object, whereas read-only mode is used for other operations.
Concepts
538 of 590
Session
18
HTML5 Web Storage
Code Snippet 10 demonstrates the code to retrieve data from the employee object store using the get() function of the transaction object.
Code Snippet 10: var trans = db.transaction([employee], IDBTransaction.READ_ WRITE).objectStore(employee); var request = trans.get(2); request.onerror = function(event) { // Handle errors! }; request.onsuccess = function(event) { // Do something with the request.result! alert(Name: + request.result.name); };
In the code, the transaction() method accepts two parameters. The second parameter is optional. The first parameter is the list of the object stores that are extended by the transaction object. In this case, there is a single object store named employee, created in the database. The optional second parameter specifies the type of the transaction, that is, read-only, read-write, or snapshot. Here, the transaction type is defined as IDBTransaction.READ_WRITE. This type allows reading as well as writing in the database. The employee object store is retrieved from the transaction object on which operations are performed. Here, the get() method is invoked on the employee object store which returns the value against the key path 2. Finally, the result of the get() method is stored in the request object on which callback functions, such as onsuccess and onerror are invoked.
Opening a Cursor
Cursor is used to retrieve multiple records from an object store. They can be used when the value of key path is not known. They are part of a transaction and are opened for a particular object store.
539 of 590
Concepts
Session
18
HTML5 Web Storage Code Snippet 11 demonstrates the code to retrieve multiple records from the employee object store.
Code Snippet 11: store = db.transaction(employee).objectStore(employee); store.openCursor().onsuccess = function(event) { var cursor = event.target.result; if (cursor) { alert(Name for id + cursor.key + is + cursor.value.name); cursor.continue(); } };
Here, in the code, the transaction object is created for the employee object store. Then, the openCursor() function is invoked on the object store. If the cursor is successfully opened, a cursor object is returned which will retrieve the data from the object store. Code Snippet 12 shows the complete code for opening, creating, and retrieving data from the object store using the IndexedDB API.
Code Snippet 12: <!DOCTYPE html> <html> <head> <title>IndexedDB API</title> <!--[if IE]> <script src=http://html5shim.googlecode.com/svn/trunk/ html5.js></script> <![endif]--> <script> // Detect the support for IndexedDB API
Concepts
var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB; var IDBTransaction = window.IDBTransaction || window. webkitIDBTransaction;
540 of 590
Session
18
HTML5 Web Storage
var db; var transaction;
var employeeData = [ { name: John Smith, email: [email protected] }, { name: Jill Patrick, email: [email protected] }, { name: Rock Ethan, email: [email protected] }, { name: Daniel Andrew, email: [email protected] } ]; function initDb() { var request = indexedDB.open(CompanyDB, 1); request.onsuccess = function (evt) { db = request.result; var setVrequest = db.setVersion(1.99); setVrequest.onsuccess = function(e) { if(db.objectStoreNames.contains(employee)) { db.deleteObjectStore(employee); } objectStore = db.createObjectStore(employee, { keyPath: id, autoIncrement: true }); alert (Employee Object Created); objectStore.createIndex(name, name, { unique: false }); true }); objectStore.createIndex(email, email, { unique: alert (Existing Employee Object Deleted);
541 of 590
Concepts
Session
18
HTML5 Web Storage
for (i in employeeData) { objectStore.put(employeeData[i]); } }; }; request.onerror = function (evt) { console.log(IndexedDB error: + evt.target.errorCode); }; } function employee_details() { store = db.transaction(employee).objectStore(employee); store.openCursor().onsuccess = function(event) { var cursor = event.target.result; if (cursor) { alert(Name for id + cursor.key + is + cursor. value.name); cursor.continue(); } }; } function search_employee() { trans = db.transaction([employee], IDBTransaction.READ_ WRITE).objectStore(employee); var request = trans.get(2); request.onerror = function(event) { // Handle errors! }; alert(Record added);
Concepts
542 of 590
Session
18
HTML5 Web Storage
// Work with the request.result alert(Name: + request.result.name);
request.onsuccess = function(event) {
}; } window.addEventListener(DOMContentLoaded, initDb, false); </script> </head> <body> <input type=button value=Print Employees Details onclick=employee_details()/> <br/> <input type=button value=Search Employee Based on Key onclick=search_employee()/> </body> </html>
The program execution starts with the creation of employee object store in which records are added. The alert window displays the message, Record added while storing the records in the object store. Then, the application allows the user to query the database by clicking the Print Employee Details and Search Employee Based on Key buttons. Figure 18.8 shows the output for the employee object store in the Chrome browser, when a user clicks Search Employee Based on Key button.
543 of 590
Concepts
Session
18
HTML5 Web Storage
Concepts
Figure 18.9: Different Platform Supporting Native Apps For example, BlackBerry Messenger (BBM) is a native app available on BlackBerry mobile devices.
544 of 590
Session
18
HTML5 Web Storage
With HTML5 release, a discussion started about HTML5 which involved whether HTML5 can develop native mobile apps (that is apps designed especially for Blackberry, iPhone, Android, and so on). HTML5 is the latest version of HTML language providing a simple building block for Web pages. This is the first version of markup language that supports the use of multimedia without using any additional plug-in and is supported by many devices and computer systems. HTML5 Web apps are accessible and used on any devices through Web browser similar to the mobile Web site. The Web apps have the ability of offline access which means that the user need not have a network connection. Table 18.4 lists the differences between the native apps and HTML5 apps.
Native Apps
Native Apps runs on iOS and Android devices that can be downloaded or purchased from the online app stores. Native Apps use programming language, such as Java for Android devices and Objective C for iOS devices.
HTML5 Apps
HTML5 Apps runs on a Web server, usually in a Web browser.
Web developers use HTML, JavaScript, and CSS. They need to acquire the skills of Java and objective C for writing native applications.
There are many instances where the users cannot identify whether they are working on a hybrid HTML5-native application or a fully native application or an HTML5 application.
545 of 590
Concepts
Session
18
HTML5 Web Storage
Users adjust styles for devices
HTML5 apps can be viewed on any devices that contains Web browser. Users can also use CSS3 for applying styles to change the look according to their requirements. HTML5 apps look similar to Web pages by using the same code.
Upcoming functionalities
HTML5 does not support all features on a device, but it is coming up with new functionalities. There are several APIs that exist for working on local databases, Web storage, drag-and-drop, offline Web pages, and many more. New APIs are being planned in future to provide Web pages access to the software and hardware of a device.
Improving performance
Many developers learn new methods to improve the performance of Web pages. These same methods are useful to mobile HTML5 apps. There are many apps, such as timer, mail, databases, and news apps that need not be faster.
Independent device
HTML5 apps work on mobile devices as well as Web browsers, as it is important for development purpose. There are millions of laptop and desktop users than mobile users. If the developers want that their application to be used by a large number of users, then they should design and develop the application for both mobile users as well as desktop users.
Developers are not locked in app stores
There are a number of app stores existing for Android and BlackBerry. If developers wish to sell the apps, then they are required to provide them into as many stores or marketplaces as possible. By using HTML5, developers are not restricted to an app store. Instead, they can create applications and sell them like any other Web application. HTML5 app acts a substitute to native apps, though in several conditions, native apps can be used for better purpose. Developers can create hybrid applications that are a combination of native and HTML apps.
Concepts
546 of 590
Session
18
HTML5 Web Storage
Native apps provide many more benefits over HTML5 apps. These benefits are as follows:
Providing access to device hardware
Many mobile devices contain hardware, such as accelerometer, GPS, a camera, and so on. The GPS is accessible through Geolocation API. At present, there are no APIs available for accelerometers, cameras, or any other device hardware for HTML5 apps.
Uploading Files
Native apps can access the file system in Android and some files in iOS. However, the HTML5 file API does not work on Android or iOS.
Push Notifications
The push notifications are sent always with an open Internet Protocol (IP) connection to applications on the iOS device. Android also has a same feature named Cloud to Device Messaging.
Accessing device files
Native apps communicate with files on devices, such as contacts and photos. However, these files cannot be seen from HTML5 apps.
Superior graphics than HTML5
HTML5 has a <canvas> element, but it will not be able to create a full 3D experience.
Offline access
HTML5 provides access to offline Web applications. However, a native app is stored on local machine, so the users do not require access to the Web to work with the application.
In-app purchasing and advertising
Native apps have an additional benefit, that is trust. Several users are comfortable using application downloaded from app stores than using a Web page. These app stores are preferred than search engines, by the users for finding tools.
547 of 590
Concepts
HTML5 apps allow developing in-app stores and advertising. Native apps have these features pre-built in them through app stores. Selling the apps in app store is easy, as HTML5 apps are Web pages that are difficult to sell.
Session
18
HTML5 Web Storage
PhoneGap is an HTML5 app that allows the user to create native apps with Web technologies and is accessible to app stores and APIs. PhoneGap controls the Web technologies.
Appcelerator
Appcelerator is a cross-platform mobile application development support. It allows the users to create Android, iOS, and mobile Web apps. Native applications are developed using a JavaScript code base with Eclipse as the IDE.
Concepts
548 of 590
Session
18
HTML5 Web Storage
Identify the methods that are used to store and retrieve the data from session storage. (A) setItem() (B)
getItem()
(C) (D)
retreiveItem() displayItem()
2.
_______________ runs on iOS and Android devices that can be downloaded or purchased from the online app stores. (A) Native apps (B) Web apps (C) (D) Web browser Web Server
3.
The ____________ is an HTML5 app tool that allows the user to author native apps with Web technologies and is accessible to app stores and APIs. (A) Appcelerator (B) Eclipse (C) (D) PhoneGap Opera
4.
________________ is a mechanism to store data in a database in the IndexedDB API. (A) Object store (B) Index (C) (D) Cursor Database
549 of 590
Concepts
Session
18
HTML5 Web Storage 5. Which of the following is the correct code to check the support for session storage in the browser?
function checkSupport() { if ((sessionStorage in window[!sessionStorage] !== null) window) &&
(A)
{ alert(Your browser supports Web Storage); return; } } function checkSupport() { if ((sessionStorage in window)) { alert(Your browser supports Web Storage); return; } } function checkSupport() { if ((sessionStorage in window[sessionStorage] !== null) window) ||
(B)
(C)
Concepts
550 of 590
Session
{
18
HTML5 Web Storage
window) &&
(D)
551 of 590
Concepts
Session
18
HTML5 Web Storage
18.7.1 Answers
1. 2. 3. 4. 5. A, B A C A D
Concepts
552 of 590
Session
18
HTML5 Web Storage
Summary
Web Storage is a W3C specification that provides functionality for storing data on the client-side for both temporary as well as permanent needs. HTML5 Web applications make use of Web storage to implement client-side persistent storage and they are: session storage and local storage. Session storage keeps track of data specific to one window or tab. The setItem() and getItem() methods are used to store and retrieve the data from session storage. Local storage enables to save data for longer periods on the users computer, through the browser. IndexedDB API is basically an object store that can be used to store and manipulate data on the client-side. A native application also called as native app is an application program that is built for a particular device or platform.
553 of 590
Concepts
Session
18
HTML5 Web Storage
Try it Yourself
1. Develop an HTML5 registration Web form with buttons, such as Add, Clear, Display, and Submit. When the user clicks Add, the data entered in the form should be persisted. When the user clicks clear, all the data stored on that page should be deleted. If user clicks Display, the page should print all the data stored in that session. Similarly, on clicking Submit, the next Web page will be displayed with the confirmation details of the user. Modify the CompanyDB database application designed earlier in this session. Add the functionality to delete the records from the employee object store. Also, design a form to accept the employee details and add those details to the employee object store.
2.
Concepts
554 of 590
Session
18
HTML5 Web Storage (Workshop)
Note - Please refer to the respective lab deliverable for demonstrations and guided
simulations.
Labs
556 of 590
19
Session
19
HTML5 Geolocation and APIs
19.1 Introduction
Consider a scenario where you are visiting a new city and are unaware of specific locations and routes. You want to get information regarding hotels in your locality, such as their exact address, tariffs, and so on. In such a situation, an application which can provide relevant information about the hotels based on your current location would be useful. A feature that can detect location and list relevant information based on that location is called Geolocation. Geolocation is a term used to identify the geographic location of a person, place, or an object. Today, modern devices, such as computers, smartphones, tablets, and so on provide Internet-enabled browsers through which the geographic locations of a user or an object can be detected.
19.2 Geolocation
Geolocation in computing terminology indicates a feature that determines the current location of a user on devices. The location of the user is represented as a single point that comprises two components: latitude and longitude. The components can be used further to retrieve more information for the user, such as businesses in the neighborhood or other users within the same coverage area. Figure 19.1 shows the representation of latitude and longitude with respect to a location on the globe.
Concepts
558 of 590
Session
19
HTML5 Geolocation and APIs
There are different sources through which devices can determine the information about the location. These are as follows:
GPS - GPS is a satellite navigation system that provides information about the
location on any part of the globe. The GPS system is maintained by the government of the United States and is used by modern mobile devices with GPS capability.
IP Address - Location information can be derived from IP Address. The IP Address is
WiFi and Bluetooth MAC address - These are used by devices that have wireless
network connection.
User Input - It is a software tool which can be used on any device requesting for
location information. The information retrieved by the tool is based on the data provided by the user, such as, a zip code.
559 of 590
Concepts
Browser
Version Support
Session
19
HTML5 Geolocation and APIs
Browser
iOS (Mobile Safari) Android BlackBerry
Version Support
3.2+ 2.0+ 6+
location of the device. For example, if the satellites are invisible to GPS, then it may not return the accurate location information.
where,
window: Is the top level object in JavaScript object hierarchy
Code Snippet 1 demonstrates the script that tests the existence of Geolocation object within a browser.
Code Snippet 1: <!DOCTYPE html> <html> <head> <title> Testing Support for Geolocation in Browsers</title> <script> function display_location_enabled() { // Default message var str = Geolocation is not supported in this browser;
Concepts
560 of 590
Session
{
19
HTML5 Geolocation and APIs
alert (str);
</head> <body>
</script>
</html>
</body>
onClick=display_location_enabled()></input>
In the code, the if statement checks existence of the geolocation property in the browser. If the browser provides an implementation for the property, then an alert window displays the message Geolocation is supported in this browser . Otherwise, the default message is displayed. Figure 19.2 shows the existence of Geolocation object in the Chrome browser.
Method
Description
user Retrieves the geographic information of the device at regular intervals V 1.1 Aptech Limited
561 of 590
Concepts
Session
19
HTML5 Geolocation and APIs
clearWatch()
Method
Description
Terminates the current watch process Table 19.2: Methods of Geolocation Object
Also, any changes in the user position is notified through the methods.
Concepts
} }
562 of 590
Session
{
19
HTML5 Geolocation and APIs
function showPosition(position) alert(Latitude: + position.coords.latitude + \n + Longitude: + position.coords.longitude); } </script> </head> <body> <input type=button value= Display Location onClick=getLocation()/> </body> </html>
In the code, the getCurrentPosition() function obtains the position which is passed as a parameter to the showPosition() function. The showPosition() function obtains the coordinates of a location through position object. The position object is defined in the Geolocation API and holds the current location of the device. It contains attribute named coords that retrieves the latitude and longitude of the location. The values retrieved for latitude and longitude are in decimal degrees. Table 19.3 lists the attributes of the position object.
Attribute
coords timestamp
Description
An object of type Coordinates that provides different properties, such as latitude, longitude, altitude, accuracy, speed, and so on An object of type DOMTimeStamp Table 19.3: Attributes of the position Object
Figure 19.3 shows the notifications for the Web page containing geolocation code. The browser seeks permission from the user to share their location information with the application.
563 of 590
Concepts
Session
19
HTML5 Geolocation and APIs Figure 19.4 shows a message displaying current location of the user, when the Share My Location button is clicked.
The PositionError object holds information related to errors occurred while finding the geographic location of the user. Table 19.4 lists the properties of PositionError object.
Property
code message
Description
Returns a numeric value for the type of error occurred Returns a detailed message describing the error encountered. The message can be used for debugging
Table 19.4: Properties of the PositionError Object Table 19.5 lists the different error codes returned by the code property of the PositionError object.
Code Concepts
1 2 3
Constant
PERMISSION_DENIED
Description
Application does not have permission to access Geolocation API POSITION_UNAVAILABLE Position of the device could not be obtained TIMEOUT Unable to retrieve location information within the specified interval Table 19.5: Error Codes V 1.1 Aptech Limited
564 of 590
Session
19
HTML5 Geolocation and APIs
Code Snippet 3 demonstrates the error handling routine for the geolocation code.
Code Snippet 3: <!DOCTYPE html> <html> <head> <title>Handling Error</title> <script> function getLocation() { function showPosition(position) { alert(Latitude: + position.coords.latitude + \n + Longitude: + position.coords.longitude); } function errorHandler(error) { switch (error.code) { case error.PERMISSION_DENIED: alert (You have denied access to your position.); break; case error.POSITION_UNAVAILABLE: position.); alert (There was a problem getting your break; case error.TIMEOUT: alert (The application has timed out attempting to get your position.); break; } } </script>
565 of 590
Concepts
Session
19
HTML5 Geolocation and APIs
</head> <body> <input type=button value=Display Location onClick=getLocation()/> </body> </html>
In the code, if the application fails to find the current location of the user, then the errorHandler() function is invoked. The function is passed as the second parameter in the getCurrentPosition() method and is used to handle the errors occurred in the application. It obtains the error object which is of type PositionError from the API and compares it with the error codes specified in the switch-case statement. Depending on the error that has occurred, the appropriate case statement is executed and an alert message is displayed to the user. Figure 19.5 shows the output displaying error message for geolocation application. The reason for displaying error is that the Chrome browser blocks the URL whose file path starts with file:///.
are used by an application while retrieving the geolocation information. Table 19.6 lists the attributes of PositionOptions object.
Concepts
Attribute
enableHighAccuracy
Description
Indicates that the application wants to receive the most accurate results for geolocation. The default value of the attribute is false
566 of 590
Session
19
HTML5 Geolocation and APIs
Attribute
maximumAge
Description
Obtains the cached position object whose age is less than the specified maximumAge limit (in milliseconds). If age limit is set to 0, then the application must obtain a new position object Indicates the maximum time length (in milliseconds) for which the application can wait to obtain the position object
timeout
Table 19.6: Attributes of the PositionOptions Object Code Snippet 4 demonstrates the script to set the attributes of PositionOptions object.
Code Snippet 4: <script> var options = { enableHighAccuracy: true, maximumAge: 50000, timeout: 60000 }; function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition, errorHandler, options); } else{ alert (Geolocation is not supported in this browser.); } } ... </script>
In the code, an object named options is set with attributes. The attribute maximumAge enables the application to use a cached position object which is not older than 50 seconds. Also, the timeout limit is set to 60 seconds for an application, before notifying an error. The options is passed as third parameter to the getCurrentPosition() method.
567 of 590
Concepts
Session
19
HTML5 Geolocation and APIs
where,
src: Is the URL of Google Maps API sensor: Parameter sent with the URL. It indicates whether application uses any
sensor, such as GPS system to obtain the location of a user. Its value must be explicitly set to true or false
Code Snippet 5 demonstrates how to load and initialize the Google Maps API in the <script> tag. The code will execute after the page is loaded completely and will invoke a function in response to the onload event.
Code Snippet 5: <!DOCTYPE html> <html> <head> <title> Load and Initialize Google Maps </title> <style> html { height: 100% } body { height: 100%; width: 100%; margin: 10% } #map_canvas { height: 50%; width: 50% } </style> <script src=http://maps.google.com/maps/api/js?sensor=false></ script> <script>
Concepts
568 of 590
Session
{
19
HTML5 Geolocation and APIs
function initialize() // Loading Google Maps var num = new google.maps.LatLng(51.528663,-0.173171); var myOptions = { zoom: 16, center: num, }; var mymap = new google.maps.Map(document.getElementById(map_ canvas), myOptions); var marker = new google.maps.Marker({ position: num, map: mymap, title:Lords Cricket Ground, London! }); } </script> </head> <body onload=initialize()> <div id=map_canvas></div> </body> </html> mapTypeId: google.maps.MapTypeId.HYBRID
In the function, var myOptions = {}, is an object of type options that contains properties, such as zoom, center, and mapTypeId. These properties are used to initialize the map. Then, statement new google.maps.Map (document.getElementById (map_canvas), myOptions); creates an instance of Map object. The object is displayed in a container on the Web page specified with the <div> element.
the
569 of 590
Concepts
In the code, the URL http://maps.google.com/maps/api/js?sensor=false defines all symbols and definitions to be loaded for the Google Maps API. Then, the function initialize() is invoked after the page is loaded completely. This function creates the object of type Map and initializes it with the map initialization variables.
Session
19
HTML5 Geolocation and APIs Finally, to display an icon on the identified location on the Google maps, the Marker object is created. The Marker objects constructor sets the value for the properties, such as position, map, and title. The position property is specified with the location of the marker on the map. The map property is specified with the Map object to attach the marker with the map. Also, the title property sets the title to be displayed as a tooltip on the map. As mentioned earlier, the myOptions object has several properties. Table 19.7 lists some of these properties.
zoom
Property
Description
Sets the initial resolution at which map is displayed. A lower zoom value 0 represents a full map of the Earth. Similarly, a higher zoom value displays a map with high resolution. In Code Snippet 5, the zoom level is set to 16. Centers the map on a specific point by creating an object of type LatLng which holds the location coordinates. In Code Snippet 5, the map is centered with the location coordinates 51.528663,0.173171. These coordinates display a map centered on Lords Cricket Ground in London, England. Sets an initial map type. The map types supported are: ROADMAP for normal, SATELLITE for photographic tiles, HYBRID for roads and city names, and TERRAIN for water features. In Code Snippet 5, the map type has been set as google.maps.MapTypeId.HYBRID. Table 19.7: Properties of the myOptions Object
center
mapTypeId
Figure 19.6 displays the Map object on the Web page that is centered on Lords Cricket Ground in London.
Concepts
Session
19
HTML5 Geolocation and APIs
The Geolocation object is used by the Google Maps API to display the geolocation information in the applications. Code Snippet 6 demonstrates the code that displays current location of a user on the map using Geolocation object.
Code Snippet 6: <!DOCTYPE html> <html lang=en> <head> <style> html, body { width: 100%; height: 100%; padding: 10% } #map_canvas { height: 50%; width: 50%; } </style> <script src=http://maps.google.com/maps/api/js?sensor=false> </script> <script> // Check support for Geolocation in the browser if (navigator.geolocation) { // Locate position and invoke function errorFunction); } else { alert(Geolocation is not enabled in your browser); } navigator.geolocation.getCurrentPosition(displayPosition,
571 of 590
Concepts
Session
19
HTML5 Geolocation and APIs
// Success function function displayPosition(position) { var my_lat = position.coords.latitude; var my_lng = position.coords.longitude; var div_info = document.getElementById(user_location); div_info.innerHTML = <h1> Latitude is : + my_lat + and Longitude is + my_lng + </h1>; // Load Google Maps var latlng = new google.maps.LatLng(my_lat, my_lng); var myOptions = { zoom: 2,//the initial resolution is set at which map is displayed center: latlng, //centers the map mapTypeId: google.maps.MapTypeId.ROADMAP //sets the map type }; // Creates the Map object var map = new google.maps.Map(document.getElementById(map_ canvas), myOptions); // Displays icon on the located position var marker = new google.maps.Marker({ } // Error callback function function errorFunction(pos) { alert(Error!); position: latlng, map: map, title:User location });
Concepts
} </script> </head>
572 of 590
Session
<body>
19
HTML5 Geolocation and APIs
The code uses the getCurrentPosition() method and retrieves the current position of the user. Then, it passes the information to displayPosition() function, which retrieves the coordinates, latitude and longitude. The retrieved coordinates are set into the properties of the Options object named myOptions and initialize the Map object. Finally, the Map object is displayed along with the current position information in the <div> element. Figure 19.7 shows the output displaying the current location of the user on the Google Maps.
HTML5 defines drag-and-drop operations that are based on events. The event-based mechanism allow the elements to be copied, reordered, or deleted on a Web page. The drag-and-drop operation involves the use of a pointing device, such as mouse on a visual medium. To perform the drag operation, a mousedown event is triggered followed by multiple mousemove events. Similarly, the drop operation is performed when a user releases the mouse. The benefit of drag-and-drop mechanism is that it has brought the drag-and-drop operations on the browser level. This makes the programming easier, thus eliminating the need of complex JavaScript code written in earlier HTML versions.
Session
19
HTML5 Geolocation and APIs Currently, drag-and-drop operations are supported by all major browsers.
Code Snippet 7 shows how to set the draggable attribute of an image element.
Code Snippet 7: <!DOCTYPE html> <html> <head> <title>Drag and Drop API</title> </head> <body> <div id=div style=border: red 2px solid; height:125px; width:75px; padding: 10px> <img src=image.jpg height=75 width=75 id=image1 draggable=true/> </div> </body> </html>
In the code, the <img> element contains draggable attribute that is set to true. The value true indicates that the element is eligible for dragging.
Concepts
574 of 590
Session
19
HTML5 Geolocation and APIs
Table 19.8 lists the various events triggered during the drag operation.
Events
dragstart drag dragleave
Description
Triggers when an element is started to be dragged by the user Triggers when an element is being dragged using a mouse Triggers when the drag and drop operation is completed Table 19.8: Drag Events
575 of 590
Concepts
Session
19
HTML5 Geolocation and APIs
<body> <div id=div1 style=border: blue 2px solid; height:125px; width:75px; padding: 10px> <img src=image.jpg height=75 width=75 id=image1 draggable=true ondragstart=drag_image(event)/> </div> </body> </html>
In the code, the <img> element has been set with an event listener for the dragstart event. When the image is dragged, then the dragstart event is fired and calls drag_image() function. The function uses the dataTransfer object to store the data during drag-and-drop operation. The string image represents the data type and event.target.id represents the value of id attribute of the draggable element. Figure 19.8 shows the output of the image element to be dragged.
576 of 590
Session
19
HTML5 Geolocation and APIs
Event
dragenter dragleave dragover drop
Description
Triggers when a draggable element is being dragged on the target element for the first time Triggers when an element is dragged outside the target element Triggers when an element is dragged inside the target element Triggers when an element is dropped in the target element Table 19.9: Drop Events
Code Snippet 9 demonstrates how to set up event listeners to drop the image element on the target element.
Code Snippet 9: <!DOCTYPE html> <html lang=en> <head> <title>Drag and Drop API</title> <script> function drag_image(event) { event.dataTransfer.setData(image, event.target.id); } function allow_drop(event) { event.preventDefault(); } { var data=event.dataTransfer.getData(image); event.target.appendChild(document.getElementById(data)); function drop_image(event)
577 of 590
Concepts
Session
19
HTML5 Geolocation and APIs
} </script> </head> <body> <div id=div1 style=border: blue 2px solid; height:125px; width:75px; padding: 10px> <img src=image.jpg height=75 width=75 id=image1 draggable=true ondragstart=drag_image(event)/> </div> <br/> <div id=div2 style=border: red 2px solid; height:125px; width:75px; padding: 10px ondrop=drop_image(event) ondragover=allow_drop(event)> </div> </body> </html>
In the code, the <div> element with id attribute, set as div2, is associated with two event listeners namely, ondragover and ondrop. The ondropover calls the allow_drop() function which prevents the default behavior of the target element. By default, the browsers do not support dropping of one elements on the other element. To prevent the default behavior, the statement, event.preventDefault() is invoked. Then, the drop event is fired on the target element. It calls the function drop_image() which uses getData() method to retrieves image that is set as image. Finally, it appends the dragged image as a element into the target element, div2.
Concepts
578 of 590
Session
19
HTML5 Geolocation and APIs
Figure 19.9 shows the output of the drop operation, after the image is dragged on the target element.
The following are the steps that can be taken to cache resources locally on the system: 1. 2. Create a manifest file to define the resources that need to be saved. Reference the manifest file in each Web page designed to use cached resources.
579 of 590
Concepts
The Application Cache enables all resources, such as HTML, JavaScript, images, and CSS pages of an Web application to be stored locally on the system.
Session
19
HTML5 Geolocation and APIs
FALLBACK: This section defines alternative resource to be used, when the actual resource is not available. For example, figure2.png is defined as a fallback image. If a browser cannot access figure1.jpg in the images folder, then figure2.png
will replace the unavailable image at the time of rendering the markup on the Web page. The unavailability of the image can be due to network connection or server problem.
NETWORK: This section specifies resources to be accessed when there is a network
Concepts
580 of 590
Session
19
HTML5 Geolocation and APIs
Code Snippet 11 demonstrates how to add the .manifest file in an HTML document.
Code Snippet 11: <!DOCTYPE html> <html manifest=appcache.manifest> <head> <title> Web Page </title> <link rel=stylesheet href=styles.css/> <script type=text/javascript src=check.js></script> </head> <body> <input type=button value=click Here... onClick=display()/> <img src=images/figure1.jpg width=100 height=100/> </body> </html>
In the code, the appcache.manifest is specified with the <html> tag. The interpretation of the manifest file is similar to any other file reference. The document uses a relative file path, as both the manifest file and HTML document are located in the same directory. By default, a Web page declaring manifest is cached automatically. The benefit of the Application Cache is that it improves the performance of a Web page by reducing the number of requests made to the Web server. The Web server hosts the Web application to be accessed on the network.
581 of 590
Concepts
Session
19
HTML5 Geolocation and APIs Figure 19.10 shows how to enable the Work Offline mode in the Opera browser. This enables to cache the resources of the Web application pages locally.
Figure 19.10: Work Offline Mode in Opera As shown in figure 19.10, Work Offline is enabled to cache the resources of the Web page. Figure 19.11 shows the cached Web page in the Opera browser.
Concepts
Session
19
HTML5 Geolocation and APIs
2.
Which one of the following new properties of the navigator object is supported by HTML5? (A) Location (B) Cookie (C) (D) Geolocation Script
3.
Which one of the following objects enables to get and set the data of the element being dragged? (A) dragstart (B) dataTransfer (C) (D) drop drag
4.
Identify the steps needed to cache the resources of a Web page locally on the system. (A) (B) Obtain the resource from online Reference the manifest file in a Web page (C) (D) Create a manifest file Create the object of the manifest file in JavaScript
583 of 590
Concepts
Session
19
HTML5 Geolocation and APIs 5. Which of the following is the correct code to load the coordinates on the Google Maps?
function displayPosition(position) { var my_lat = position.coords.latitude;
(A)
}
var my_lng = position.coords.longitude; var latlng = new google.maps.LatLng(my_lat, my_lng); function displayPosition(position) { var my_lat = position.coords.latitude; var my_lng = position.coords.longitude; var latlng = new google.maps.LatitudeLongitude(my_lat, my_lng); } function displayPosition(position) { var my_lat = coords.latitude; var my_lng = coords.longitude;
(B)
(C)
document.getElementById(user_
var latlng = new google.maps.LatitudeLongitude(my_ lat, my_lng); } function displayPosition(position) { var my_lat = position.coord.latitude;
(D)
}
Concepts
584 of 590
Session
19
HTML5 Geolocation and APIs A C B B, C A
19.7.1 Answers
1. 2. 3. 4. 5.
585 of 590
Concepts
Session
19
HTML5 Geolocation and APIs
Summary
Geolocation determines the current location of a user on devices. The location is represented as a single point on a map that comprises two components: latitude and longitude. The Goelocation API is a specification provided by the W3C which provides a consistent way to develop location-aware Web applications. Google Maps API is used to display the users location on the map. The object of type Map is created in JavaScript, before it can be referenced in an HTML document. The drag-and-drop operations defines an event-based mechanism using which elements on a Web page can be copied, reordered, or deleted. HTML5 supports offline Web applications that allow a user to work with them without being online.
Concepts
586 of 590
Session
19
HTML5 Geolocation and APIs
Try it Yourself
1. Develop a mobile Web application to display the current location of a user on Google Maps. The application will make use of jQuery API to handle success and failure conditions, while gathering information about the user location. Create a Web page with a container containing three images and two empty containers. The user can drag the images from the container and drop them in the empty containers back and forth. 2.
587 of 590
Concepts
A little knowledge that acts is worth infinitely more than much knowledge that is idle
Session
19
HTML5 Geolocation and APIs (Workshop)
Note - Please refer to the respective lab deliverable for demonstrations and guided
simulations.
Labs
590 of 590
Readers Response
Name Of Book: _______________________________________________________________________ Batch: ______________________________________________ Date: __________________________ The members of the design team at Aptech are always striving to enhance the quality of the books produced by them. As a reader, your suggestions and feedback are very important to us. They are of tremendous help to us in continually improving the quality of this book. Please rate this book in terms of the following aspects. Aspects Excellent Presentation style Suggestion: _____________________________________________________________________________________ _____________________________________________________________________________________ Simplicity of language Suggestion: _____________________________________________________________________________________ _____________________________________________________________________________________ Topics chosen Suggestion: _____________________________________________________________________________________ _____________________________________________________________________________________ Topic coverage Suggestion: _____________________________________________________________________________________ _____________________________________________________________________________________ Rating Very Good Good Poor
__________________________________________________________________________________ __________________________________________________________________________________ Quality of pictures/diagrams Suggestion: __________________________________________________________________________________ __________________________________________________________________________________ Overall suggestions: __________________________________________________________________________________ __________________________________________________________________________________ __________________________________________________________________________________ __________________________________________________________________________________ Please fill up this response card and send it to: The Design Centre, Aptech Ltd. Aptech House, A-65, MIDC, Marol, Andheri (East), Mumbai - 400 093. INDIA