POUL KLAUSEN
JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT PART SOFTWARE DEVELOPMENT
Download free eBooks at bookboon.com 2
Java 12: WWW and development of the client part: Software Development 1st edition © 2018 Poul Klausen & bookboon.com ISBN 978-87-403-1974-3 Peer review by Ove Thomsen, EA Dania
Download free eBooks at bookboon.com 3
Deloitte & Touche LLP and affiliated entities.
JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT PART: SOFTWARE DEVELOPMENT
Contents
CONTENTS Foreword
6
1 Introduction
8
2 HTML
10
2.1
HTML forms
13
2.2
Scalable Vector Graphics
15
Problem 1
16
3
Cascading style sheets
17
3.1
More selectors
22
3.2 Styles
25
360° thinking
Problem 2
30
.
360° thinking
.
360° thinking
.
Discover the truth at www.deloitte.ca/careers
© Deloitte & Touche LLP and affiliated entities.
Discover the truth at www.deloitte.ca/careers
© Deloitte & Touche LLP and affiliated entities.
Discoverfree theeBooks truth atatbookboon.com www.deloitte.ca/careers Download
Click on the ad to read more
4
Dis
JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT PART: SOFTWARE DEVELOPMENT
Contents
4 JavaScript
31
4.1
Nature of Languages
34
4.2
Basic syntax
55
Exercise 1
76
Exercise 2
81
4.3
Global objects and functions
89
Exercise 3
90
4.4 DOM
92
Problem 3
107
5
JavaServer Faces and Ajax
110
5.1
Valdation of fields
112
Exercise 4
115
5.2
Submit fields without reload
115
5.3 Converters
119
5.4
JSF Listeners
122
6
Component libraries
125
6.1
How to poll the server
136
6.2
A p:autocomplete element
138
8 WebSheet
143
8.1
144
The program’s functions
8.2 Design
145
8.3 Programming
149
8.4 Conclusion
154
Appendix A: jQuery
155
Appendix B: JSON
167
Download free eBooks at bookboon.com 5
JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT PART: SOFTWARE DEVELOPMENT
Foreword
FOREWORD This book is the twelfth in a series of books on software development. The programming language is Java, and the language and its syntax and semantics fills obviously much, but the books have also largely focus on the process and how to develop good and robust applications. This book is similar to the book Java 11 about development of web applications, but focusing on the client side. This means that key topics are style sheets and JavaScript, and in particular, the last part fills. Another topic is Ajax, like the book gives a brief introduction to PrimeFacses. The primary purpose of the book is to show that it is possible to perform complex client-side programming using JavaScript. The book requires knowledge of programming of the server side similar to what has been dealt with in the previous book, and together, the two books provide a relatively basic introduction to web application development. As the title says this series of books deals with software development, and the goal is to teach the reader how to develop applications in Java. It can be learned by reading about the subject and by studying complete sample programs, but most importantly by yourself to do it and write your own programs from scratch. Therefore, an important part of the books is exercises and problems, where the reader has to write programs that correspond to the substance being treated in the books. All books in the series is built around the same skeleton and will consist of text and examples and exercises and problems that are placed in the text where they naturally belongs. The difference between exercises and problems is that the exercises largely deals with repetitions of the substance that is presented in the text, and furthermore it is relatively accurately described what to do. Problems are in turn more loosely described, and are typically a little bigger and there is rarely any clear best solution. These are books to be read from start to finish, but the many code examples, including exercises and problems plays a central role, and it is important that the reader predict in detail studying the code to the many examples and also solves the exercises and problems or possibly just studying the recommended solutions. All books ends with one or two larger sample programs, which focus primarily is on process and an explanation of how the program is written. On the other hand appears the code only to a limited extent – if at all – and the reader should instead study the finished program code perhaps while testing the program. In addition to show the development of programs that are larger than the examples, which otherwise is presented, the aim of the concluding examples also is to show program examples from varying fields of application.
Download free eBooks at bookboon.com 6
JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT PART: SOFTWARE DEVELOPMENT
Foreword
Most books also ends with an appendix dealing with a subject that would not be treated in the books. It may be issues on the installation of software or other topics in computer technology, which are not about software development, but where it is necessary to have an introductory knowledge. If the reader already is familiar with the subject, the current appendix can be skipped. The programming language is, as mentioned Java, and besides the books use the following products: 1. NetBeans as IDE for application development 2. MySQL to the extent there is a need for a > …
but but many many development development tools tools add add their their own own elements elements to to the the header. header. HTML HTML define define more more structural structural elements elements where where the the most most important important are: are: --- section, section, that that represents represents aa section section in in aa document, document, and and itit can can together together with with h1–h6 h1–h6 elements elements be used to indicate the document’s structure, and a section must start with a h be used to indicate the document’s structure, and a section must start with a h element element --- article, that represents an independent piece of content in a document and article, that represents an independent piece of content in a document and as as the the name name says says an an article, article, and and an an article article must must start start with with aa hh element element --- aside, aside, that that represents represents aa content content that that isis only only slightly slightly related related to to the the rest rest of of the the page page --- header, that represents a header section header, that represents a header section --- footer, footer, that that represents represents aa footer footer section section and and will will often often contain contain information information about about the the author, author, copyright copyright information information and and so so on on --- nav, nav, that that represents represents aa section section in in the the document document intended intended for for navigation navigation (links) (links) --- dialog, that is used to mark up a conversation dialog, that is used to mark up a conversation --- figure, figure, that that can can be be used used to to associate associate aa caption caption together together with with some some embedded embedded content, content, such such as as aa graphic graphic or or aa video video
Download free eBooks at bookboon.com 10 10
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE CLIENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT
HTML HtML
It It is is not not aa requirement requirement that that aa HTML HTML document document uses uses these these elements elements (which (which are are introduced introduced in in HTML5), HTML5), but but itit is is recommended, recommended, among among other other things, things, that that they they can can be be styled styled in in aa style style sheet. sheet. Similarly, Similarly, the the following following structure structure is is recommended recommended for for an an HTML HTML document, document, where where there there may may be be more more sections sections and and where where some some elements elements can can be be omitted omitted completely: completely: Html5Document HTML5 Document Content
Section title Article title
Introdoction to this title
Here is the text.
Article title
Introdoction to this title
Here is the text.
About this section
References or other.
Copyright and similar
Download free eBooks at bookboon.com 11 11
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE JAVA 12:PART: WWW AND DEVELOPMENT OF THE CLIENT CLIENT PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT CLIENT PART: SOFTWARE DEVELOPMENT
HTML HtML HtML
There are many other HTML elements, and there are many new elements in HTML5, There are many other HTML elements, and there are many new elements in HTML5, but I do not want to mention the elements here. General is the form of a HTML element but I do not want to mention the elements here. General is the form of a HTML element content content
where there may be a number of attributes. If there is no content, it is allowed to write: where there may be a number of attributes. If there is no content, it is allowed to write:
even though though it is not actually intended intended to use this this notation in HTML5. HTML5. A very specific specific even even though it is not not actually intended to to use this notation notation in HTML5. A A very specific example could could be: example example could be: be: That is a header NY026057B
TMP PRODUCTION 6x4
4
12/13/2013
ACCCTR00
PSTANKIE
gl/rv/rv/baf
Bookboon Ad Creative
All rights reserved.
© 2013 Accenture.
Bring your talent and passion to a global organization at the forefront of business, technology and innovation. Discover how great you can be. Visit accenture.com/bookboon
Download free eBooks at bookboon.com 12 12 12 12
Click on the ad to read more
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE CLIENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT
HTML HtML
where there is one attribute that refers to a class in a style sheet. As a starting point for this chapter, I have created a web application called HTMLApplication, which for the moment only has a single page index.html. I do not want to display the content here as the page fills a lot, and the page should show only how the above structure elements are used to structure the content of a HTML document. When you test the document, note that the structural elements have no visual effect. They are used solely to structure the text, and the visual effects are solely intended to header elements (h1–h6) as well as a list of links. In any case, the visual effect is what is default. It should also be mentioned that it is allowed to define custom attributes and, if necessary, they should start with the word > Shows the use of the input element.
Enter line | |
Enter password | |
Enter number | |
Enter range |
Download free eBooks at bookboon.com 13 13
JAVA 12: WWW AND DEVELOPMENT OF THE JAVA 12:PART: WWW AND DEVELOPMENT OF THE CLIENT SOFTWARE DEVELOPMENT CLIENT PART: SOFTWARE DEVELOPMENT
HTML HtML
|
Enter email | |
Enter URL | |
|
The basic basic form form element element isis input, input, and and you you specifies specifies with with aa type type attribut attribut how how to to render render the the The element on on the the screen screen and and what what else else itit should should be be able able to to do do with with the the element. element. The The default default element type isis text, text, which which means means you you can can enter enter aa single single text text line. line. Note Note (the (the first first input input element) element) that that type you can can specify specify required required and and that that with with aa placeholder placeholder you you can can specify specify aa hint hint for for the the text text to to you be entered. entered. In In particular, particular, note note the the number number and and range range types types that that indicate indicate that that you you can can only only be enter numbers numbers (the (the last last isis rendered rendered as as aa slider), slider), and and note note the the two two last last ones ones to to enter enter an an email email enter address and and aa URL, URL, respectively. respectively. address
Download free eBooks at bookboon.com 14 14
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE CLIENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT
HTML HtML
Note Note that that the the form form isis used used solely solely as as an an example example of of which which input input elements elements exists exists and and how how to to validate validate > Scalable Vector Graphics
The Wake the only emission we want to leave behind
.QYURGGF'PIKPGU/GFKWOURGGF'PIKPGU6WTDQEJCTIGTU2TQRGNNGTU2TQRWNUKQP2CEMCIGU2TKOG5GTX 6JGFGUKIPQHGEQHTKGPFN[OCTKPGRQYGTCPFRTQRWNUKQPUQNWVKQPUKUETWEKCNHQT/#0&KGUGN6WTDQ 2QYGTEQORGVGPEKGUCTGQHHGTGFYKVJVJGYQTNFoUNCTIGUVGPIKPGRTQITCOOGsJCXKPIQWVRWVUURCPPKPI HTQOVQM9RGTGPIKPG)GVWRHTQPV (KPFQWVOQTGCVYYYOCPFKGUGNVWTDQEQO
Download free eBooks at bookboon.com 15 15
Click on the ad to read more
JAVA 12: WWW AND DEVELOPMENT OF THE JAVA 12:PART: WWW AND DEVELOPMENT OF THE CLIENT SOFTWARE DEVELOPMENT CLIENT PART: SOFTWARE DEVELOPMENT
HTML HtML
Opening Opening the the page page in in the the browser browser gives gives you you the the result: result:
The The code code isis easy easy enough enough to to understand understand and and you you are are encouraged encouraged to to investigate investigate what what else else isis available. available.
PROBLEM PROBLEM 11 The The directtory directtory for for this this book book contains contains aa document document java12, java12, that that isis aa text text document document with with the the text for the two first chapters in this book, where the text is saved as plan text without text for the two first chapters in this book, where the text is saved as plan text without formatting. formatting. The The directory directory also also has has two two png-files png-files called called screen1.png screen1.png and and screen2.png. screen2.png. The The files files are are the the screen screen dumps dumps shown shown in in this this chapter. chapter. The The task task isis to to create create aa web web application application with with aa HTML HTML document, document, that that shows shows the the content content of of the the file file java12 java12 and and the the two two images. images. The The page page should only structure the text (display the content), you should not format the text. This should only structure the text (display the content), you should not format the text. This isis the the subject subject of of aa later later problem. problem.
Download free eBooks at bookboon.com 16 16
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT CLIENT PART: SOFTWARE DEVELOPMENT
Cascading CasCadIng style styLe sheets sHeets CasCadIng styLe sHeets
3 3 CASCADING STYLE SHEETS 3 CASCADING CASCADING STYLE STYLE SHEETS SHEETS After After the above about HTML, I’m ready for short introduction on style sheets, and will After the the above above about about HTML, HTML, I’m I’m ready ready for for aaa short short introduction introduction on on style style sheets, sheets, and and III will will take take as as the the starting starting point point the the same same program program as as in in the the previous previous chapter. chapter. I I have have added added a a new new take as the starting point the same program as in the previous chapter. I have added a new HTML HTML document to the project and called styleddoc.html. The content the same as HTML document document to to the the project project and and called called itit it styleddoc.html. styleddoc.html. The The content content isis is the the same same as as index.html index.html and and the the goal goal is is to to show show how how the the document’s document’s visual visual presentation presentation can can be be changed changed index.html and the goal is to show how the document’s visual presentation can be changed using using style sheet. Initially have created directory resources and including subdirectory using aaa style style sheet. sheet. Initially Initially III have have created created aaa directory directory resources resources and and including including aaa subdirectory subdirectory css css and and added added a a style style sheet sheet named named styles.css: styles.css: css and added a style sheet named styles.css:
Initially, Initially, nothing but an empty file. The document that has to use style sheet must Initially, itit it isis is nothing nothing but but an an empty empty file. file. The The document document that that has has to to use use aaa style style sheet sheet must must have a link element in the header: have a link element in the header: have a link element in the header: HTML Application HTML Application
The syntax should be correct and you can easily drag the file into the document with the The syntax syntax should should be be correct correct and and you you can can easily easily drag drag the the file file into into the the document document with with the the The mouse, and NetBeans will automatically insert the correct link. mouse, and and NetBeans NetBeans will will automatically automatically insert insert the the correct correct link. link. mouse, The idea of style sheets as mentioned to separate content and presentation. style sheet The idea idea of of style style sheets sheets isis is as as mentioned mentioned to to separate separate content content and and presentation. presentation. AA A style style sheet sheet The consists of styles identified by selectors, and as an example, I have added the following style consists of of styles styles identified identified by by selectors, selectors, and and as as an an example, example, II have have added added the the following following style style consists for a h1 selector to the style sheet: for aa h1 h1 selector selector to to the the style style sheet: sheet: for h1 { h1 { font-size: 36pt; font-size: 36pt; font-weight: bold; font-weight: bold; color: darkslateblue; color: darkslateblue; } }
Download free eBooks at bookboon.com 17 17 17
JAVA 12: WWW AND DEVELOPMENT OF THE JAVA 12:PART: WWWSOFTWARE AND DEVELOPMENT DEVELOPMENT OF THE THE JAVA 12: WWW AND OF CLIENT DEVELOPMENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT CLIENT
CasCadIng styLe sHeets CasCadIng style styLe sheets sHeets Cascading
Such a selector is called a type selector or an element selector and means that all of the Such a selector is called a type selector or an element selector and means that all of the document’s h1 elements will use the style that the selector defines. You can thus define how document’s h1 elements will use the style that the selector defines. You can thus define how the headers of the document should be presented, and it will apply to all documents that the headers of the document should be presented, and it will apply to all documents that use that style sheet. Typically, you also wants to define a style for the body element, such use that style sheet. Typically, you also wants to define a style for the body element, such as defining the font to be used as default: as defining the font to be used as default: body { body { font-family: serif; font-family: serif; font-size: 10pt; font-size: 10pt; } }
You can also define styles for descendent selectors that occur with a space between two selectors: You can also define styles for descendent selectors that occur with a space between two selectors: section p { section p { margin-left: 20px; margin-left: 20px; } }
This selector selector indicates that that a paragraph element element must have have a left indentation indentation of 20, 20, but This This selector indicates indicates that aa paragraph paragraph element must must have aa left left indentation of of 20, but but only for for paragraphs paragraphs that that are are nested nested in in aa section section element. element. only only for paragraphs that are nested in a section element.
30 FR da EE ys tria
SMS from your computer ...Sync'd with your Android phone & number
l!
Go to
BrowserTexting.com
and start texting from your computer!
...
Download free eBooks at bookboon.com 18 18 18
BrowserTexting
Click on the ad to read more
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE JAVA 12: WWW AND OF JAVA 12:PART: WWWSOFTWARE AND DEVELOPMENT DEVELOPMENT OF THE THE CLIENT DEVELOPMENT CLIENT PART: SOFTWARE DEVELOPMENT CLIENT DEVELOPMENT CLIENT PART: SOFTWARE DEVELOPMENT JAVA 12:PART: WWWSOFTWARE AND DEVELOPMENT DEVELOPMENT OF THE THE JAVA 12: WWW AND OF CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT CLIENT
You You You You
can can can can
also also also also
define define define define
a aa a
so-called so-called so-called so-called
#content-list { #content-list #content-list { { font-size: 14pt; font-size: 14pt; #content-list { font-size: 14pt; font-weight: bold; font-weight: font-size: 14pt; font-weight: bold; bold; color: darkgray; color: darkgray; darkgray; font-weight: bold; color: } } color: darkgray; } }
ID ID ID ID
Cascading CasCadIng CasCadIng CasCadIng CasCadIng CasCadIng
selector, selector, selector, selector,
known known known known
This selector selector is used used by an an element whose whose id is is This This selector is is used by by an element element whose id id is should be unique, unique, there isanonly only one element element in isaa This selector is used by is element whose id should be there one in should be unique, there is only one element in a In this be case, it is is the the following element: In this case, it following element: should unique, there is only one element in a In this case, it is the following element: In this case, it is the following element:
Content
Finally, Finally, Finally, Finally,
you you you you
can can can can
define define define define
element element element element element
can can can can can
use use use use use
.default-text { .default-text .default-text { { width: 800px; width: 800px; 800px;{ .default-text width: color: #222222; color: #222222; width: color: 800px; #222222; } } }color: #222222; }
An An An An An
In
As another example As As another another example example the color as As another example the color color as as green: green: the green: the color as green:
starting starting starting starting
by by by by by
the the the the
book book book book
there there there there
is is is is
it it it it
aa a a
defined defined defined defined
11, 11, 11, 11,
aa a a
… … … …
class class class class
it it it it it
with with with with with
with with with with
the the the the
.forword { .forword .forword { { color: darkgreen; color: darkgreen; .forword { color: darkgreen; } } }color: darkgreen; } .forword h5 { .forword .forword h5 h5 { { color: darkred; color: darkred; darkred; .forword h5 { color: } } }color: darkred; }
Download free eBooks at bookboon.com 19 19 19 19
with with with with
the the the the
character character character character
# # # #
point: point: point: point:
specifying specifying specifying specifying specifying
Java Java Java Java
starts starts starts starts
sheets sHeets sHeets sHeets sHeets sHeets
content-list, and and as element’s element’s id attribute attribute content-list, content-list, and as as element’s id id attribute document that directly can use use this style. content-list,that anddirectly as element’s id this attribute document can style. document that directly can use this style. document that directly can use this style.
with with with with
directly directly directly directly directly
as as as as
style styLe styLe styLe styLe styLe
aa a aa
class class class class class
name name name name
attribute: attribute: attribute: attribute: attribute: forword forword forword forword
that that that that
defines defines defines defines
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT CLIENT PART: SOFTWARE DEVELOPMENT
Cascading CasCadIng style styLe sheets sHeets CasCadIng styLe sHeets
The The last style means that h5 element under an element whose style forword appears in The last last style style means means that that aaa h5 h5 element element under under an an element element whose whose style style isis is forword forword appears appears in in red text: red text: red text: Forword Forword About About this this book book
Here
Here is is the the text
text
You can also define selectors that relates to attributes. As an example, the following style means: You Youcan canalso alsodefine defineselectors selectorsthat thatrelates relatesto toattributes. attributes.As Asan anexample, example,the thefollowing followingstyle stylemeans: means: h4[id] { h4[id] { color: color: darkred; darkred; } }
that all h4 elements that have an id attribute must be displayed with a dark red text. As that that all all h4 h4 elements elements that that have have an an id id attribute attribute must must be be displayed displayed with with aa dark dark red red text. text. As As another example, the HTML element abbr can be used to display a tooltip: another example, the HTML element abbr can be used to display a tooltip: another example, the HTML element abbr can be used to display a tooltip: to HTML HTML syntax
Here, the value of the attribute title will be displayed as a tooltip ifif the mouse isis pointing Here, Here, the the value value of of the the attribute attribute title title will will be be displayed displayed as as aa tooltip tooltip if the the mouse mouse is pointing pointing to the word syntax. Consider the following styles: to the word syntax. Consider the following styles: to the word syntax. Consider the following styles: abbr[title] { abbr[title] { color: gray; color: gray; } } abbr[title]:hover { abbr[title]:hover { color: red; color: red; } }
They define that for all abbr elements with title attribute, the text should appear gray and They define define that that for for all all abbr abbr elements elements with with aaa title title attribute, attribute, the the text text should should appear appear gray gray and and They holding the mouse over the text (mouse ower), the text should appear red. holding the the mouse mouse over over the the text text (mouse (mouse ower), ower), the the text text should should appear appear red. red. holding
Download free eBooks at bookboon.com 20 20 20
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE JAVA 12:PART: WWW AND DEVELOPMENT OF THE CLIENT SOFTWARE DEVELOPMENT CLIENT PART: SOFTWARE DEVELOPMENT CLIENT PART: SOFTWARE DEVELOPMENT
Cascading CasCadIng style styLe sheets sHeets CasCadIng styLe sHeets
Attributes as selectors can be especially interesting for custom attributes. Consider the Attributes as selectors can be especially interesting for custom attributes. Consider the following paragraph: following paragraph:
*
> Apply now redefine your future
- © Photononstop
AxA globAl grAduAte progrAm 2015
axa_ad_grad_prog_170x115.indd 1
19/12/13 16:36
Download free eBooks at bookboon.com 24
Click on the ad to read more
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE CLIENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT
Cascading CasCadIng style styLe sheets sHeets
all all elements elements under under elements elements with with the the class class king. king. Finally, Finally, there there are are the the three three relate to attributes. Here they are used two a paragraph with the attribute relate to attributes. Here they are used two a paragraph with the attribute in in particular particular you you can can select select the the attributes attributes text: text:
last last styles styles that that ] attributes which starts with text - [attr$="text"] attributes which ends with text - [attr*="text"] attributes which contains text and there are actually a few more options.
3.2 STYLES 3.2 STYLES Above I have shown examples of how to refer from a style sheet to the individual elements in the HTML tree, but there are quite a few other areas where styles are available, and where you should know what they means – and there are really many. Styling an HTML document is an extensive topic, and an adequate processing of styles is beyond the scope of this book. In this section I will outline some of the basic principles, but there is much more, and in general, in software development it is an area that requires considerable expertise before designing modern web applications. However, I would like to emphasize once again that the development tool usually supports styling and is a significant help in practice, although it is by no means always easy to understand the effects of the many possibilities. Basics styling includes: -- how much the elements fill in the browser -- where the elements are located -- how the content of the individual elements is formatted, including fonts and colors Basically, an HTML element appears as a box:
Download free eBooks at bookboon.com 25 25
JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT PART: SOFTWARE DEVELOPMENT
Cascading style sheets
In the middle you have the content (if there is a content) and without having padding, which indicates how much space there should be outside of the content. For an element with a style, the width and height will in most cases mean the size of the content area inclusive padding, but it can be changed with box-sizing. Around the padding there may be a border, and finally there may be a margin about all of it. For example, if you specify a background color, it will relate to the entire padding area. You should especially note that the margin area is transparent and is thus only used to create spaces between the elements. You should be aware that if elements are vertically aligned and two margins (top and bottom) meet, they are automatically collapsed to one whose height is the largest of the two. Many elements such as p, h, and article elements behave as described above and show the contents as a block and are therefore called block boxes. Others such as strong and span are called inline boxes as they format the content of a line. How the different elements show their content can be defined by display and thus override how they as default shows their content. Elements can be laid out by the browser in several ways, but the default is static, and for block boxes, it means that they are placed vertically underneath each other, whereas for inline boxes it means that they are laid out horizontally on the same line and wraps as required. As mentioned, the position of elements is defined as static, which means that the elements float in the window, but you can define other options, as are best illustrated by an example. If you open the application PositionDocument in the browser, you get the window:
The elements are all span elements that are rendered in the following order: 1. Gorm den gamle 2. Harald Blåtand 3. Svend Tveskæg 4. Harald d. 2. 5. Knud den store 6. Hardeknud
Download free eBooks at bookboon.com 26
JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT PART: SOFTWARE DEVELOPMENT
Cascading style sheets
Unless otherwise stated, they would be laid out in one row which would wrap if the line was too long. In this case, the two first and the last are laid out in default (static) positions, while the third has relative position, which means that it is laid out relative to the previous element, as is Harald Blåtand. You should note that the last element (Hardeknud ) is laid out as if the element Svend Tveskeg was laid out in default position and that the position of the previous two is ignored as they are laid out as absolute and fixed position respectively. Absolute means that the element is placed in a fixed position relative to the upper left corner of the document. Fixed is a variant, but here the element is also placed in a fixed position, but this time relative to the part of the document that is visible. You can illustrate the difference by changing the size of the window and then scrolling it:
LIGS University based in Hawaii, USA is currently enrolling in the Interactive Online BBA, MBA, MSc, DBA and PhD programs:
▶▶ enroll by October 31st, 2014 and ▶▶ save up to 11% on the tuition! ▶▶ pay in 10 installments / 2 years ▶▶ Interactive Online education ▶▶ visit www.ligsuniversity.com to find out more!
Note: LIGS University is not accredited by any nationally recognized accrediting agency listed by the US Secretary of Education. More info here.
Download free eBooks at bookboon.com 27
Click on the ad to read more
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE CLIENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT
Cascading CasCadIng style styLe sheets sHeets
The The code code isis shown shown below: below: TODO supply a title
Download free eBooks at bookboon.com 28 28
JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT SOFTWARE DEVELOPMENT JAVA 12:PART: WWW AND DEVELOPMENT OF THE
Cascading style sheets
CLIENT PART: SOFTWARE DEVELOPMENT
CasCadIng styLe sHeets
Gorm den gamle Harald Blåtand Svend Tveskæg Harald d. 2. Knud den store Hardeknud
Styling includes includes much much more more than than what what has has been been said said in in this this chapter, chapter, but but the the above above should should Styling be enough enough to to get get an an idea idea of of what what isis possible. possible. Often Often you you are are in in the the situation situation that that you you want want be to achieve achieve aa certain certain effect effect on on an an element, element, but but you you do do not not know know what what to to write. write. Here Here isis the the to best source source actually actually the the Internet, Internet, where where there there are are countless countless examples examples of of how how to to style style different different best HTML elements. elements. As As aa conclusion, conclusion, II have have added added aa document document called called styledform.html styledform.html to to the the HTML project HtmlApplication. HtmlApplication. The The document document shows shows the the same same form form as as previously previously mentioned, mentioned, but but project this time time no no table table isis used used and and the the elements elements are are placed placed only only by by styling: styling: this
You are are encouraged encouraged to to study study the the document document and and especially especially the the corresponding corresponding style style sheet, sheet, You and how how the the individual individual elements elements are are styled. styled. and
Download free eBooks at bookboon.com 29 29
JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT PART: SOFTWARE DEVELOPMENT
Cascading style sheets
PROBLEM 2 Start with a copy of the project from problem 1. You must then add a style sheet to the project so you uses styles to format the document so it looks like the finished version of the book. All styles should be in the style sheet and you must expand the document with the necessary ID and class definitions.
Download free eBooks at bookboon.com 30
Click on the ad to read more
JAVA JAVA12: 12:WWW WWWAND ANDDEVELOPMENT DEVELOPMENTOF OFTHE THE CLIENT CLIENTPART: PART:SOFTWARE SOFTWAREDEVELOPMENT DEVELOPMENT
JavaScript JavasCrIpt
4 JAVASCRIPT 4 JAVASCRIPT II will will then then give give an an introduction introduction to to JavaScript, JavaScript, which which isis the the preferred preferred language language for for code code on on the the client client side. side. The The language language has has essentially essentially the the same same syntax syntax asas Java, Java, but but otherwise otherwise the the two two languages languages do do not not have have anything anything in in common, common, and and JavaScript JavaScript isis even even aa language language that that isis very very different different from from Java, Java, but but ifif you you want want to to work work professional professional asas aa web web developer, developer, you you has has to to know know JavaScript. JavaScript. Therefore, Therefore, this this chapter. chapter. JavaScript JavaScriptisisan aninterpreted interpretedprogramming programminglanguage, language,and andthe thesource sourcecode codeare areasasJava Javajust justtext, text, but but unlike unlike Java, Java, the the code code isis not not translated, translated, but but isis sent sent asas text text to to the the browser, browser, which which has has aa built-in built-ininterpreter interpreterthat thatinterprets interpretsthe theJavaScript JavaScriptcode. code.ItItisisaareal realinterpreter interpreterwho whointerprets interprets the the code code statement statement for for statement statement and and execute execute each each statement statement before before the the next next isis interpreted interpreted and and performed. performed. To To show show what what JavaScript JavaScript is, is, II want want to to start start with with aa very very simple simple example, example, called called LoadingDocument. LoadingDocument. There There isis only only one one file file index.html index.html whose whose content content is: is: LoadingDocument Welcome Go on OK
Download free eBooks at bookboon.com 3131
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE CLIENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT
JavaScript JavasCrIpt
In In the the head head section section there there isis aa script script element element and and itit isis an an element element that that can can contain contain JavaScript JavaScript code. code. In In this this case, case, aa variable variable and and aa function function are are defined. defined. The The variable variable isis called called hello, hello, and and itit isis initialized initialized with with the the text text “Hello”. “Hello”. In In principle, principle, JavaScript JavaScript uses uses variables variables as as other other programming programming languages, including Java, but you should primarily note that the variable languages, including Java, but you should primarily note that the variable has has no no type. type. The The script script block block also also has has aa function function that that basically basically works works as as aa method method in in Java Java and and can can be be executed executed by by calling calling it. it. In In this this case case the the function function isis called called show() show() and and itit has has two two statements. statements. The first is an alert() which opens a simple popup that shows the value of the The first is an alert() which opens a simple popup that shows the value of the variable variable hello. The next statement changes the value of the variable, and here you should notice hello. The next statement changes the value of the variable, and here you should notice that that the the syntax syntax is, is, as as you you know know itit from from Java. Java. IfIf the the application application isis opend opend in in the the browser, browser, itit will will render render the the body body of of the the document document from from start start to to finish, finish, starting starting with with the the following following window window where the h1 element is rendered (see below). After the h1 element is rendered there where the h1 element is rendered (see below). After the h1 element is rendered there isis aa new new script script element element
which calls calls the the JavaScript JavaScript function function show(), show(), that that means means that that the the browser browser stops stops and and opens opens which popup: aa popup:
Download free eBooks at bookboon.com 32 32
JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT PART: SOFTWARE DEVELOPMENT
JavaScript
The browser will continue to render the document when clicking OK, and the browser will then render the h2 element:
Download free eBooks at bookboon.com 33
Click on the ad to read more
JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT PART: SOFTWARE DEVELOPMENT
JavaScript
Then immediately a script element follows, which this time just performs an alert() which in a popup shows the value of the variable hello:
Here you should note that the variable has been changed in the show() function. After the above popup is displayed, the browser resumes until clicked on OK, after which the browser renders the last h3 element, and only then the entire document is parsed and displayed in the browser:
The above example shows a bit about what JavaScript is and how to add JavaScript to an HTML document, but not what JavaScript can be used for what is the goal of the following. First, however, I would like to see a little more on the syntax of the language.
4.1 NATURE OF LANGUAGES When you start with JavaScript and come from other languages such as Java, there are primarily three things that may seem very different: -- Variables scope -- Types -- Objects and inheritance
Download free eBooks at bookboon.com 34
JAVA JAVA12: 12:WWW WWWAND ANDDEVELOPMENT DEVELOPMENTOF OFTHE THE CLIENT CLIENTPART: PART:SOFTWARE SOFTWAREDEVELOPMENT DEVELOPMENT
JavaScript JavasCrIpt
and and it’s it’s actually actually the the three three things things that that make make programming programming in in JavaScript JavaScript much much different different than, than, for for example, example, Java Java programming. programming. As As mentioned, mentioned, JavaScript JavaScript isis an an interpreted interpreted language language and and JavaScript JavaScript code code isis sent sent to to the the browser browser along along with with the the HTML HTML code. code. The The browser browser then then has has aa built-in built-in interpreter interpreter that that interprets interprets and and executes executes the the code’s code’s statements. statements. The The execution execution ends ends when when all all the the code code isis executed executed correctly correctly or or when when the the interpreter interpreter comes comes to to aa statement statement that that fails. fails. ItIt isis not, not, therefore, therefore, as as aa Java Java program, program, where where the the entire entire program program isis translated translated to to Java Java Byte Byte Code Code before before the the program program can can be be run run by by the the Java Java runtime runtime system. system. JavaScript JavaScript isis aa typetypeweak weaklanguage, language,where wherevariables variablesshould shouldnot notbe bedeclared declaredby byaaparticular particulartype. type.ItItisisnot notthe thesame same as as that that the the language language isis typeless, typeless, but but itit means means that that aa variable variable can can change change type type and and that that the the current current type type isis determined determined by by the the value value of of the the variable variable and and how how the the variable variable isis used. used. There There are are aa number number of of rules rules for for the the language’s language’s type type compatibility, compatibility, rules rules that that are are quite quite complex complex and and some some of of the the things things that that II will will explain explain below. below. JavaScript JavaScript isis not not object-oriented object-oriented in in classical classical sense, sense, but but conversely, conversely, objects objects play play aa major major role role in in the the language. language. However, However, compared compared to to Java, Java, for for example, example, there there isis aa very very big big difference difference in in how how to to create create and and inherit inherit objects. objects. Perhaps Perhaps the the biggest biggest difference difference between between JavaScript JavaScript and and other other languages languages are are functions, functions, since since functions functions are are actually actually objects objects that that may may have have properties properties and and methods. methods. The The aim aim of of this this section section isis to to illustrate illustrate some some of of these these many many concepts concepts without without having having all all the the details, details,but butto tosuch suchan anextent extentthat thatyou youcan canuse useJavaScript JavaScriptin inconnection connectionwith withweb webapplication application development. development. When When the the browser browser parses parses aa HTML HTML document, document, itit builds builds aa tree tree consisting consisting of of the the document’s document’s elements. elements. The The tree tree isis called called DOM DOM (for (for Document Document Object Object Model Model),), and and the the purpose purpose of of JavaScript JavaScript isis accurately accurately to to modify modify this this tree. tree. The The DOM DOM tree tree JavaScript JavaScript can can be be placed placed anywhere anywhere in in the the document, document, but but when when the the document document isis loaded, loaded, the the browser browserparses parsesthe thedocument documentand andbuilds buildsthe theDOM DOMtree. tree.IfIfthe thebrowser browsermeets meetsany anyJavaScript, JavaScript, itit will will also also perform perform it, it, and and therefore therefore itit may may only only work work ifif the the element element that that the the script script refers refers to to isis already already part part of of the the DOM DOM tree. tree. Consider Consider the the following following example: example: Simple HTML5 document DOM
This article deals with Regnar Lodbrog
A Danish vikings
Svend
Knud
Valdemar
The example should show what happens when the browser loads a document with JavaScript The example should show what happens when the browser loads a document with JavaScript and how to refer to an item in the DOM hierarchy. Note first that a style sheet has been and how to refer to an item in the DOM hierarchy. Note first that a style sheet has been defined in the header. In addition, a script element has been defined that defines a single defined in the header. In addition, a script element has been defined that defines a single JavaScript function called print(). The function prints a name as a paragraph, which means that JavaScript function called print(). The function prints a name as a paragraph, which means that the function inserts a paragraph element in the place where the function is called. The browser the function inserts a paragraph element in the place where the function is called. The browser will not perform the function at this location, it is only a definition of a function. The body will not perform the function at this location, it is only a definition of a function. The body part starts with a h1 element and two paragraphs, and the browser starts displaying these items part starts with a h1 element and two paragraphs, and the browser starts displaying these items
Download free eBooks at bookboon.com 37 37
JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT PART: SOFTWARE DEVELOPMENT
JavaScript
It’s not that much mystery in it, but after the browser has interpreted the above elements, a script part comes, and here an alert() that shows a text. This means, as shown in the previous example, that the browser stops and waits for the user to click on OK. When that happens, the browser continues to process the document and the next element is another alert() that shows the text in the first paragraph. You should note how to refer to an element with a specific ID and how to refer to the element’s text with innerText. The alert() shows the entire text, including the text in the span element, but the last part is not bold, as JavaScript does not interpret HTML. When you click OK, the browser continues to interpret and execute JavaScript statements. Here is pars an array of all p elements – at that time there are 2 – and the subsequent loop sets their class to redStyle, after which the text becomes red – also the text in the 2 span elements. Once that happens, a new alert() is performed, which shows the length of the array pars, and the primary purpose is to have the parser stop so that you can see that all the text in the two paragraphs is red:
93%
OF MIM STUDENTS ARE WORKING IN THEIR SECTOR 3 MONTHS FOLLOWING GRADUATION
MASTER IN MANAGEMENT • STUDY IN THE CENTER OF MADRID AND TAKE ADVANTAGE OF THE UNIQUE OPPORTUNITIES THAT THE CAPITAL OF SPAIN OFFERS • PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR PROFESSIONAL GOALS • STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS EXPERIENCE
5 Specializations
Personalize your program
www.ie.edu/master-management
#10 WORLDWIDE MASTER IN MANAGEMENT FINANCIAL TIMES
[email protected]
Download free eBooks at bookboon.com 38
Length: 1O MONTHS Av. Experience: 1 YEAR Language: ENGLISH / SPANISH Format: FULL-TIME Intakes: SEPT / FEB
55 Nationalities
in class
Follow us on IE MIM Experience
Click on the ad to read more
JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT PART: SOFTWARE DEVELOPMENT
JavaScript
When you click OK, the browser continues to perform JavaScript. spans is similarly an array with all span elements (there are 2) and the following loop sets the text to green. The last part of the script starts by determining an array classes that contain all elements with the class boldStyle. Next, the font for these elements is italicized, and the result is that the browser shows the following:
Download free eBooks at bookboon.com 39
JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT PART: SOFTWARE DEVELOPMENT
JavaScript
The three names of Danish kings are simple HTML paragraphs, and they help to show that the browser first inserts these elements into the DOM tree after the first script block is completed. Then follow another script block. Here, nodes are an array with all child nodes to a div element. There are 7 child nodes that were not what you would expect, but the reason is that the plain text between the individual paragraphs also counts as a node. Next, a variable parent is created that refers to the div element. The subsequent loop iterates over all child nodes to parent starting from the first node. The loop skips the blank text elements and prints the text for paragraph elements. Please note that the loop stops with a break when you get to lastChild. There are a few things that you should notice. JavaScript uses the dot notation to refer to objects’ properties and methods – just as it is known from Java. In addition, please note that an alert() stops the browser’s parsing of the document, and alert() may therefore be a useful tool for debugging JavaScript. Objects in JavaScript JavaScript is an object-oriented language, but there is nothing similar to a class, and the only method of constructing new objects is by prototyping, which is a form of copying an existing object. In this way, a new object is created, which one can best think of as a copy of another object. A bit more precisely, any object in JavaScript has a property called prototype, and this property refers to all properties (properties and methods) inherited from the parent object. This means that if you try to refer to a property or method of an object, the interpreter will first check if that property is defined for the object in question. If this is not the case, the object to which prototype refers is checked, and neither is the property found in the hierarchy until it reaches an object where the property is defined or the interpreter can conclude that the object is undefined. Properties and methods can be overridden, and any overrides will affect the object where the override is defined and down in the inheritance hierarchy. It is best to think of this form of inheritance as a simple list, where prototype refers to the previous (parent) element. An important consequence of this inheritance is that a change of property of an object is important for all objects down in the hierarchy hierarchy.
Download free eBooks at bookboon.com 40
JAVA JAVA12: 12:WWW WWWAND ANDDEVELOPMENT DEVELOPMENTOF OFTHE THE CLIENT CLIENTPART: PART:SOFTWARE SOFTWAREDEVELOPMENT DEVELOPMENT
JavaScript JavasCrIpt
The The following following example example should should illustrate illustrate some some of of these these concepts, concepts, and and especially especially the the syntax syntax for for how how to to create create objects: objects: Prototypal inheritance Prototypal arv
In In the the document’s document’s header header isis aa script script block block that that creates creates three three objects. objects. The The first first isis obj0 obj0 and and has hastwo twoproperties propertieswith withthe thevalues values23 23and and29 29respectively. respectively.Next, Next,two twoobjects objectsobj1 obj1and andobj2 obj2 are created, both of which are extensions of obj0, but at that time the three objects have are created, both of which are extensions of obj0, but at that time the three objects have the the same same properties. properties.
Download free eBooks at bookboon.com 4141
JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT PART: SOFTWARE DEVELOPMENT
JavaScript
The body part starts rendering an h1 element, but otherwise the rest is a script block. Next, an alert() is used to show the value of the property a at obj0 and the result is a popup that displays the value 13. Next, a is changed to 19 and then the value of a for obj1 and obj2 are shown, which in both cases is 19, corresponding to that obj1 and obj2 inherit the value from obj0. As a next step is assigned a property c to obj1 with the value 41. Here you should note that you can immediately create a property for an object and assign it a value, and this property is not known from the parent object. Therefore, the three next alert() statements will show undefined, 41 and 41, since c is not known from obj0, but from obj1 and obj2 (obj2 inherit obj1). obj0 inherits an empty top object called Object and thus particular has a toString() method. Therefore, both obj1 and obj2 have a toString() method and the next statement overrides toString() for obj0. The two last alert() statements will show 89 (the sum of the three properties a, b and c, known from obj1) and NaN, since toString() can not perform the function from obj0, where c is not known.
DO YOU WANT TO KNOW:
What your staff really want?
The top issues troubling them?
How to retain your top staff FIND OUT NOW FOR FREE
How to make staff assessments work for you & them, painlessly?
Get your free trial Because happy staff get more done
Download free eBooks at bookboon.com 42
Click on the ad to read more
JAVA JAVA12: 12:WWW WWWAND ANDDEVELOPMENT DEVELOPMENTOF OFTHE THE CLIENT CLIENTPART: PART:SOFTWARE SOFTWAREDEVELOPMENT DEVELOPMENT
JavaScript JavasCrIpt
Scope Scope In In JavaScript, JavaScript, there there are are slightly slightly different different rules rules for for the the scope scope of of variables variables than than in in Java, Java, since since variables variables have have functional functional scope. scope. That That isis to to say, say, aa variable variable defined defined in in aa function function isis known known only only in in the the function, function, but but in in return return throughout throughout the the function function wherever wherever itit isis defined. defined. The The variable variable isis also also known known in in any any nested nested functions. functions. You You should should also also be be aware aware that that JavaScript JavaScript uses uses hoisting, hoisting, which which means means that that aa variable variable can can be be used used anywhere anywhere in in the the function function where where itit isis created created –– even even before before itit isis defined. defined. The The reason reason isis that that the the interpreter interpreter starts starts creating creating variables variables as as that that the the variables variables all all were were defined defined atat the the start start of of the the function. function. However, However, you you must must note note that that aa variable variable atat that that time time isis not not necessarily necessarily assigned assigned aa value. value. AA variable variable can can also also have have global global scope, scope, which which isis the the case case ifif itit isis defined defined outside outside of of aa function, function, and and such such aa variable variable can can be be used used anywhere anywhere in in the the document. document. Normally, Normally, you you write write var var in in front front of of aa variable variable when when created, created, but but itit isis actually actually not not necessary necessary (but (but can can be be recommended). recommended). AA variable variable defined defined without without var var has has automatic automatic global global scope scope wherever wherever itit isis created. created. In In most most programming programming languages, languages, aa variable variable isis removed removed when when the the program program leave leave the the scope scope where where the the variable variable isis defindes, defindes, and and itit isis also also the the case case in in JavaScript. JavaScript. That That is, is, variables variables are are created created when when the the function function in in which which they they are are defined defined isis performed. performed. ItIt isis atat least least the the basic basic rule, rule, but but itit does does not not necessarily necessarily apply. apply. The The reason reason isis that that in in JavaScript JavaScript aa function function isis itself itself an an object, object, and and aa function function can can thus thus return return aa function, function, and and for for example example itit can can return return an an internal internal function. function. This This inner inner function function can can refer refer to to aa variable variable in in the the enclosing enclosing function, function, and and thus thus there there may may be be aa reference reference to to aa local local variable variable after after aa function function has has been been completed. completed. IfIf so, so, the the variable variable will will not not be be removed, removed, aa fact fact called called closures. closures. Basically, Basically, in in JavaScript, JavaScript, there there are are not not so so many many challenges challenges regarding regarding variables’ variables’ scope scope (maybe (maybe just just except except closures), closures), and and the the following following document, document, called called ScopeDocument, ScopeDocument, should should illustrate illustrate the the most most important important scope scope rules: rules: Scope Test scope
++i) document.write(f() + " "); ++i) document.write(g() + " "); ++i) document.write(f() + " "); ++i) document.write(g() + " ");
Download free eBooks at bookboon.com 44 44
JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT PART: SOFTWARE DEVELOPMENT
JavaScript
If you start in the script block in the header of the document, a variable c is defined. It is defined outside of all functions and has global scope and is known everywhere. Next, a function test1() is defined with two local variables a and b. They are known only in the function test1() and are thus also known in principle in the nested function test2(). However, only b applies, since test2() also defines a local variable a that hides the variable a defined in test1(). The function test2() shows the value of its local variable a and the local variable b from test1(). In addition, test2() initializes the global variable c and shows its value. The function test2() is called from the external function test1(), which finally shows the value of its local variable a. There is also defined a function power2(), which will illustrate the term closure. power2() has a local variable n, and it returns a function next() that uses (refers) to this variable. This means that there is a reference to the variable n after prowe2() terminates and hence n is not removed – that is called closure. The body part starts with an h1 element, after which test1() is called. Note that this means that the internal function test2() is also performed. Next, the value of the global variable c is displayed. If you try to show the value of the variable a, it is not defined in this location, and rendering of the document would be interrupted.
Challenge the way we run
EXPERIENCE THE POWER OF FULL ENGAGEMENT… RUN FASTER. RUN LONGER.. RUN EASIER…
READ MORE & PRE-ORDER TODAY WWW.GAITEYE.COM
1349906_A6_4+0.indd 1
22-08-2014 12:56:57
Download free eBooks at bookboon.com 45
Click on the ad to read more
JAVA JAVA12: 12:WWW WWWAND ANDDEVELOPMENT DEVELOPMENTOF OFTHE THE CLIENT CLIENTPART: PART:SOFTWARE SOFTWAREDEVELOPMENT DEVELOPMENT
JavaScript JavasCrIpt
As As the the next next step, step, two two references references ff and and gg are are defined defined for for power2() power2() and and the the result result isis that that the the function function power2() power2() isis performed performed twice, twice, and and partly partly that that ff and and gg refer refer to to aa function function with with each each their their copy copy of of the the local local variable variable n. n. ItIt isis illustrated illustrated by by the the following following loops loops that that perform perform the the functions functions that that ff and and gg refers refers to, to, and and thus thus each each works works on on their their copy copy of of the the local local variable variable n. n. IfIf the the page page isis opened opened in in the the browser, browser, the the following following popups popups will will appear appear and and shows shows the the values: values: 2 3 5 1 5
and and finally finally the the page page shows shows
> Types
Note that that in in the the header header isis defined defined aa simple simple function function with with two two parameters. parameters. The The parameters parameters Note have no no type type and and all all you you can can see see isis that that the the function function performs performs the the plus plus operator operator on on the the have two parameters parameters and and returns returns the the value. value. The The script script block block in in the the body body section section creates creates an an array array two of 55 elements elements of of the the following following types: types: of 1. the the first first isis aa String String 1. 2. the the second second isis aa Number Number 2. 3. the the third third isis aa Boolean Boolean (that (that isis true true due due to to special special conversion conversion rules rules in in JavaScript) JavaScript) 3. 4. the the fourth fourth isis aa Number Number 4. 5. the the last last isis an an Object Object 5. You should should note note that that the the array array arr arr itself itself isis an an Object. Object. The The next next statement, statement, which which isis aa for for You loop, prints prints the the array’s array’s elements elements as as well well as as their their types, types, and and the the next next statement statement again again does does loop, the same same for for the the array. array. Note Note the the typeof typeof operator, operator, which which determines determines the the type type of of aa variable. variable. the Finally, there there isis the the last last statement statement that that performs performs the the function function add() add() and and prints prints its its type. type. The The Finally, type of of function function isis Object, Object, but but you you should should note note that that typeof typeof displays displays itit as as aa function. function. IfIf the the type page isis shown shown in in the the browser browser the the result result is: is: page
Download free eBooks at bookboon.com 47 47
JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT PART: SOFTWARE DEVELOPMENT
JavaScript
This e-book is made with
SETASIGN
SetaPDF
PDF components for PHP developers
www.setasign.com Download free eBooks at bookboon.com 48
Click on the ad to read more
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE CLIENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT
JavaScript JavasCrIpt
Patterns Patterns In In this this section section II have have shown shown some some basic basic concepts concepts regarding regarding JavaScript, JavaScript, and and of of course course there there are are many many more more details, details, but but the the above above should should be be sufficient sufficient to to illustrate illustrate that that JavaScript JavaScript isis aa much much different different language language than than Java. Java. In In the the time time that that JavaScript JavaScript has has existed, existed, the the language language has developed a lot, and at the same time there have been several patterns for how has developed a lot, and at the same time there have been several patterns for how to to write write JavaScript code. In particular, it appears that a function is an object, and when a function JavaScript code. In particular, it appears that a function is an object, and when a function defines defines aa scope, scope, itit allows allows functions functions to to implement implement aa form form of of >
IfIfititopens opensininthe thebrowser, browser,the thefirst firstalert() alert()will willshow show11and andthe thenext nextalert() alert()show show2.2.IfIfyou you consider considerthe thefunction functionf(), f(),itithas hasa alocal localvariable variablet tthat thatisisassigned assignedthe thevalue value1.1.The Theinternal internal function functiong() g()shows showsthe thevalue valueofofthis thisvariable, variable,after afterwhich whichititisiscounted countedup upwith with1.1.The Thefunction function f()f()returns the internal function g(). Note that it is legal, since a function is specifically returns the internal function g(). Note that it is legal, since a function is specificallyanan object. object.InInthe thebody bodysection, section,the thefunction functionf()f()isisperformed performedand anditsitsreturn returnvalue valueisisstored storedinin the thevariable variableh,h,which whichnow nowrefers referstotoa afunction functionand andthe thefunction functionf()f()terminates. terminates.Next, Next,h() h() isisperformed, performed,which whichmeans meansthat thatititisisthe thefunction functiong() g()that thatisisperformed performedasaswith withananalert() alert() shows the value 1, which is the value of the local variable t in f(). When h() is executed shows the value 1, which is the value of the local variable t in f(). When h() is executedthe the second secondtime, time,ititwill willdisplay display2.2.There Thereititisisstill stillthe thevalue valueofoft tand andyou youcan cansee seethat thatt tisisnot not initialized initializedagain againand andthus thusnot notremoved removedafter afterf()f()isisterminated. terminated.The Thereason reasonisisthat thatthere thereisisanan indirect indirectreference referencetotot tvia viag(). g().When Whenf()f()terminates, terminates,t tisisnot notremoved removedsince sincehhrefers referstotog() g() which refers to t. That a local variable in this way will not be removed after the function which refers to t. That a local variable in this way will not be removed after the function that thatcreates createsthe thevariable variableterminates terminatesisiscalled calledclosures. closures.
Download free eBooks at bookboon.com 61 61
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE CLIENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT
JavaScript JavasCrIpt
Types In JavaScript, you should not specify any >
Download free eBooks at bookboon.com 64 64
JAVA 12: WWW AND DEVELOPMENT OF THE JAVA 12:PART: WWW AND DEVELOPMENT OF THE CLIENT SOFTWARE DEVELOPMENT CLIENT PART: SOFTWARE DEVELOPMENT
JavaScript JavasCrIpt
+ "
"); "
"); + "
"); "
");
there are defined two objects where the latter overrides toString() and valueOf(). Opening there are defined two objects where the latter overrides toString() and valueOf(). Opening the code in the browser is the result: the code in the browser is the result:
Here you can see that toString() and valueOf() as default return the string [object object], Here you can see that toString() and valueOf() as default return the string [object object], but otherwise the value of the overridden methods. but otherwise the value of the overridden methods. For automatic type conversion, JavaScript uses three internal methods called toPrimitive(), For automatic type conversion, JavaScript uses three internal methods called toPrimitive(), toNumber() and toBoolean(). toPrimitive() has an argument and returns a primitive following toNumber() and toBoolean(). toPrimitive() has an argument and returns a primitive following the algorithm: the algorithm: 1. if the argument is an object returns valueOf() if it is a primitive, and else returns 1. if the argument is an object returns valueOf() if it is a primitive, and else returns toString() if it returns a primitive and else reports an error toString() if it returns a primitive and else reports an error 2. if the argument is a primitive return the argument 2. if the argument is a primitive return the argument toNumber() also has an argument and returns a number according to the following algorithm: toNumber() also has an argument and returns a number according to the following algorithm: 1. if the argument has the type Number returns the argument 1. if the argument has the type Number returns the argument 2. if the argument has the type Boolean returns 1, if the value is true and else 0 2. if the argument has the type Boolean returns 1, if the value is true and else 0 3. if the argument is Null returns 0 3. if the argument is Null returns 0 4. if the argument has the type object returns toNumber(toPrimitive(argument)) 4. if the argument has the type object returns toNumber(toPrimitive(argument)) 5. it the argument is undefined returns NaN 5. it the argument is undefined returns NaN 6. if the argument is a string returns the value of parseInt(), if the argument can be 6. if the argument is a string returns the value of parseInt(), if the argument can be parsed to a Number and else NaN parsed to a Number and else NaN
Download free eBooks at bookboon.com 65 65
JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT PART: SOFTWARE DEVELOPMENT
JavaScript
Allso toBoolean() has an argument and returns a boolean according to the following algorithm: 1. it the argument has the type boolean returns the argument 2. if the argument is Null returns false 3. if the argument is undefined returns false 4. if the argument has the type object returns true 5. if the argument has the type number returns false if the value is 0 or NaN and else true 6. if the argument has the type string returns false if the string is empty and else true As can be seen from these rules, it may be difficult to figure out the value of an expression, but in practice it rarely presents the big problems, since the value will usually be the expected, almost the value of a condition (an expression of the type Boolean) as well sometimes may results in a value other than expected, and here it is especially the operator == which causes problems. For this operator, the following table is used:
> Apply now redefine your future
- © Photononstop
AxA globAl grAduAte progrAm 2015
axa_ad_grad_prog_170x115.indd 1
19/12/13 16:36
Download free eBooks at bookboon.com 66
Click on the ad to read more
JAVA JAVA 12: WWW AND DEVELOPMENT OF THE JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE CLIENT CLIENT PART: SOFTWARE DEVELOPMENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT
JavaScript JavasCrIpt JavasCrIpt
arg1 arg1 arg1
arg2 arg2 arg2
result result result
Null Null Null
Undefined Undefined Undefined
true true true
Undefined Undefined Undefined
Null Null Null
true true true
Number Number Number
String String String
arg1 arg1 == toNumber(arg2) arg1 == == toNumber(arg2) toNumber(arg2)
String String String
Number Number Number
toNumber(arg1) toNumber(arg1) == arg2 toNumber(arg1) == == arg2 arg2
Boolean Boolean Boolean
any any any
toNumber(arg1) toNumber(arg1) == ang2 toNumber(arg1) == == ang2 ang2
any any any
Boolean Boolean Boolean
arg1 arg1 == toNumber(arg2) arg1 == == toNumber(arg2) toNumber(arg2)
String String or Number String or or Number Number
Object Object Object
arg1 arg1 == toPrimitive(arg2) arg1 == == toPrimitive(arg2) toPrimitive(arg2)
Object Object Object
String String or Number String or or Number Number
toPrimitive(arg1) toPrimitive(arg1) == arg2 toPrimitive(arg1) == == arg2 arg2
A A classic classic example example of of the the problems problems that that comparison comparison may may cause cause are are the the following following code: code:
If you you try try the the code, code, you you will will get get two two alert(), alert(), both both of of which which will will show show false false and and itit is is not not If entirely obvious. obvious. The The condition condition for for ifif has has the the value value true, true, which which immediately immediately follows follows from from entirely the toBoolean() toBoolean() algorithm. algorithm. The The first first alert() alert() will will apply apply the the third third last last row row in in the the above above table table the and will will thus thus evaluate evaluate and "Hello" "Hello" == == toNumber(true) toNumber(true) "Hello" == "Hello" == 1 1 toNumber("Hello") toNumber("Hello") == == 1 1 NaN == == 1 1 NaN
that that is is false. false. The The last last alert() alert() essentially essentially makes makes the the same same thing: thing: "Hello" "Hello" == == toNumber(true) toNumber(true) "Hello" == "Hello" == 0 0 toNumber("Hello") == toNumber("Hello") == 0 0 NaN == 0 NaN == 0
Download free eBooks at bookboon.com 67 67 67
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE CLIENT PART: SOFTWARE DEVELOPMENT CLIENT PART: SOFTWARE DEVELOPMENT JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE CLIENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT
JavasCrIpt JavasCrIpt JavaScript JavasCrIpt
The result is that it is not always easy to find out the result of a comparison with == (or The The result result isis that that itit is is not not always always easy to find findintroduced out out the the result result of!==) aa comparison comparison with with == == (or (or !=). Therefore, the operator ===easy has to been (andof which simply means !=). !=). Therefore, Therefore, the the operator operator === === has hasand been been introduced introduced (and !==) !==)rather which whichthan simply simply means comparison without type conversion, many prefer to(and use === ==. means comparison comparison without without type type conversion, conversion, and and many many prefer prefer to to use use === === rather rather than than ==. ==.
Another thing that can cause problems is null and undefined. null means that a variable Another Another thing thingand that that can cancan cause cause problems problems isis null null and and undefined. undefined. null null means means that variable has no value you assign a variable the value null. undefined means that that aaa variable variable has hasnot no noyet value value and and you you can can assign assign aa variable variable the value null. undefined means means that that aa variable variable is assigned a value, and for example,the thevalue codenull. will undefined isis not not yet yet assigned assigned aa value, value, and and for for example, example, the the code code will will document.write(a);
results in in results results in undefined undefined null undefined null null
As As an an example example of of some some of of the the above above conversion conversion rules, rules, you you can can consider consider the the document: document: As an example of some of the above conversion rules, you can consider the document: CastDocument CastDocument
the document opened in the browser, you get the result: IfIf the thedocument documentisisis isopened openedin inthe thebrowser, browser,you youget getthe theresult: result: IfIf the document opened in the browser, you get the result:
Objects Objects Objects Objects Anobject objectisis issimply simplyaaacollection collectionofof ofproperties propertiesthat thatmay maybe beofof ofsome somevalue. value.The Thetype typeofof ofaa An An object simply collection properties that may be some value. The type An object is simply a collection of properties that may be of some value. The type of aa property can be anything and especially an object, and since function an object, an property propertycan canbe beanything anythingand andespecially especiallyan anobject, object,and andsince sinceaaaafunction functionisisis isan anobject, object,an an property can be anything and especially an object, and since function an object, an object can also contain functions. You creates an object as follows: object can also contain functions. You creates an object as follows: object can can also also contain contain functions. functions. You You creates creates an an object object as as follows: follows: object var var var { { { a: a: a: b: b: b: c: c: c: } } }var var var
obj1 obj1 = = obj1 = 2, 2, 2, 3, 3, 3, 5 5 5 obj2 obj2 = = {} {} obj2 = {}
where two objects have been created. The first has three properties, while the other an wheretwo twoobjects objectshave havebeen beencreated. created.The Thefirst firsthas hasthree threeproperties, properties,while whilethe theother otherisisis isan an where where two objects have been created. The first has three properties, while the other an empty object. object. In In JavaScript, JavaScript, you you do do not not have have classes, classes, as as you you know know it from from Java, Java, and and you you empty empty object. empty object. In In JavaScript, JavaScript, you you do do not not have have classes, classes, as as you you know know itititfrom from Java, Java, and and you you can not inherit the same way you know from this language, but in JavaScript you use cannot notinherit inheritthe thesame sameway wayyou youknow knowfrom fromthis thislanguage, language,but butin inJavaScript JavaScriptyou youuse useaaaa can can not inherit the same way you know from this language, but in JavaScript you use form of inheritance called prototyping that in short means that you can create objects by formof ofinheritance inheritancecalled calledprototyping prototypingthat thatin inshort shortmeans meansthat thatyou youcan cancreate createobjects objectsby by form form of inheritance called prototyping that in short means that you can create objects by expanding existing objects. For example, if you write expandingexisting existingobjects. objects.For Forexample, example,ifififyou youwrite write expanding expanding existing objects. For example, you write var var obj3 obj3 var obj3= obj3.d obj3.d = obj3.d =
= = Object.create(obj1); Object.create(obj1); =7;Object.create(obj1); 7; 7;
Download free eBooks at bookboon.com 70 70 70
JAVA 12: WWW AND DEVELOPMENT OF THE JAVA JAVA12: 12:WWW WWWAND ANDDEVELOPMENT DEVELOPMENTOF OFTHE THE JAVA 12: WWW AND DEVELOPMENT OF THE JAVA 12: WWW AND DEVELOPMENT OF THE JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT PART: SOFTWARE DEVELOPMENT CLIENT PART: SOFTWARE DEVELOPMENT CLIENT PART: SOFTWARE DEVELOPMENT CLIENT PART: SOFTWARE DEVELOPMENT CLIENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT
JavasCrIpt JavaScript JavasCrIpt JavasCrIpt JavasCrIpt JavasCrIpt
an object has been created that inherits obj1 and expands this object with an additional an an object object has has been been created created that that inherits inherits obj1 obj1 and and expands expands this this object object with with an an additional additional an object has been created that inherits obj1 and expands this object with an additional an an object object has has been been created created that that inherits inherits obj1 obj1 and and expands expands this this object object with with an an additional additional property. For example, you performs the following statements: property. you property. For For example, example, ifif you performs performs the the following following statements: statements: property. For example, if performs the following statements: property. For example, ifif you you performs the following statements: property. For example, if you performs the following statements: alert(obj3.a alert(obj3.a alert(obj3.a alert(obj3.a alert(obj3.a obj1.a obj1.a = = 11; 11; obj1.a = 11; obj1.a = 11; obj1.a = 11; alert(obj3.a alert(obj3.a alert(obj3.a alert(obj3.a alert(obj3.a
++ obj3.b ++ obj3.c obj3.c obj3.d); obj3.b + obj3.c + obj3.d); + obj3.b ++ obj3.d); + + obj3.b obj3.b + + obj3.c obj3.c + + obj3.d); obj3.d); ++ obj3.b ++ obj3.c obj3.c obj3.d); obj3.b + obj3.c + obj3.d); + obj3.b ++ obj3.d); + + obj3.b obj3.b + + obj3.c obj3.c + + obj3.d); obj3.d);
the the first alert() will show 17 and the other 26. Here, you should note that changing the the first first alert() alert() will will show show 17 17 and and the the other other 26. 26. Here, Here, you you should should note note that that changing changing the the the first alert() will show 17 and the other 26. Here, you should note that changing the the the first first alert() alert() will will show show 17 17 and and the the other other 26. 26. Here, Here, you you should should note note that that changing changing the the value value of the property on the object obj1 also has an effect on the object obj3, which value of of the the property property aaaa on on the the object object obj1 obj1 also also has has an an effect effect on on the the object object obj3, obj3, which which value of the property on the object obj1 also has an effect on the object obj3, which value value of of the the property property aa on on the the object object obj1 obj1 also also has has an an effect effect on on the the object object obj3, obj3, which which justifies the relationship between obj1 and obj3 being a form of inheritance. Technically, justifies the relationship between obj1 and obj3 being form of inheritance. Technically, itit justifies the the relationship relationship between between obj1 obj1 and and obj3 obj3 being being aaa form form of of inheritance. inheritance. Technically, Technically, itit justifies justifies justifies the the relationship relationship between between obj1 obj1 and and obj3 obj3 being being aa form form of of inheritance. inheritance. Technically, Technically, it it isis implemented by the fact that each object has aaaa property called prototype. This property implemented by the fact that each object has property called prototype. This property is implemented by the fact that each object has property called prototype. This property is implemented by the fact that each object has property called prototype. This property is is implemented implemented by by the the fact fact that that each each object object has has aa property property called called prototype. prototype. This This property property refers to properties inherited from the parent object (the object from which the current refers to properties inherited from the parent object (the object from which the current refers to properties inherited from the parent object (the object from which the current refers to properties inherited from the parent object (the object from which the current refers refers to to properties properties inherited inherited from from the the parent parent object object (the (the object object from from which which the the current current object object created based on). When you try to refer property on an object, the interpreter object isis created based based on). on).When When you you try try to to refer refer aaaa property property on on an an object, object, the the interpreter interpreter object isis created created based on). When you try to refer property on an object, the interpreter object object is is created created based based on). on). When When you you try try to to refer refer aa property property on on an an object, object, the the interpreter interpreter will first search for this property in the current object and if it not find the property will first search for this property in the current object and ifif it itit not not find the property the will first first search search for for this this property property in in the the current current object object and and if not find find the the property property the the will the will will first first search search for for this this property property in in the the current current object object and and if if it it not not find find the the property property the the interpreter interpreter will search in its parent via prototype. This continues until you either find the interpreter will will search search in in its its parent parent via via prototype. prototype. This This continues continues until until you you either either find find the the interpreter will search in its parent via prototype. This continues until you either find the interpreter interpreter will will search search in in its its parent parent via via prototype. prototype. This This continues continues until until you you either either find find the the desired desired property or can not find it. This chain may be interrupted by overriding property. desiredproperty propertyor orcan cannot notfind findit. it.This Thischain chainmay maybe beinterrupted interruptedby byoverriding overridingaaaaproperty. property. desired property or can not find it. This chain may be interrupted by overriding property. desired desired property property or or can can not not find find it. it. This This chain chain may may be be interrupted interrupted by by overriding overriding aa property. property. As As an example shown another object that expands obj1 using method: As an an example example isis shown another another object object that that expands expands obj1 obj1 using using aaaa method: method: As an example isis shown shown another object that expands obj1 using method: As As an an example example is is shown shown another another object object that that expands expands obj1 obj1 using using aa method: method: var obj4 = Object.create(obj1); var obj4 = Object.create(obj1); var obj4 = Object.create(obj1); var obj4 = Object.create(obj1); var obj4 = Object.create(obj1); obj4.f = function (t) { return t * (this.a + this.b + this.c); } obj4.f = function (t) { return t * (this.a + this.b + this.c); } obj4.f = function (t) { return t * (this.a + this.b + this.c); } obj4.f = function (t) { return t * (this.a + this.b + this.c); } obj4.f = function (t) { return t * (this.a + this.b + this.c); }
Note that although the method f() property in the object obj4 which extends obj1, the Notethat thatalthough althoughthe themethod methodf() f()isis propertyin inthe theobject objectobj4 obj4which whichextends extendsobj1, obj1,the the Note Note that although the method f() isisaaaaaproperty property in the object obj4 which extends obj1, the Note Note that that although although the the method method f() f() is is a property property in in the the object object obj4 obj4 which which extends extends obj1, obj1, the the method can not immediately refer to the object’s other properties, but can be solved with methodcan cannot notimmediately immediatelyrefer referto tothe theobject’s object’sother otherproperties, properties,but butitit canbe besolved solvedwith with method method can not immediately refer to the object’s other properties, but ititcan can be solved with method method can can not not immediately immediately refer refer to to the the object’s object’s other other properties, properties, but but it it can can be be solved solved with with this as referring to the current object. The following statement this as as referring referring to to the the current current object. object. The The following following statement statement this this as referring to the current object. The following statement this this as as referring referring to to the the current current object. object. The The following following statement statement alert(obj4.f(2)); alert(obj4.f(2)); alert(obj4.f(2)); alert(obj4.f(2)); alert(obj4.f(2));
will will alert() alert() the the value value 20. 20. As As another another example example of of how how to to define define an an object object using using aaa method, method, will alert() the value 20. As another example of how to define an object using method, will alert() the value 20. As another example of how to define an object using method, will alert() alert() the the value value 20. 20. As As another another example example of of how how to to define define an an object object using using aaa method, method, will you you can can consider consider the the following: following: you can consider the following: you can consider the following: you can can consider consider the the following: following: you var var obj5 obj5 = var obj5 == var obj5 var obj5 = = { { { { { x: 3.14, x: 3.14, x: 3.14, x: 3.14, x: 3.14, y: 1.41, y: 1.41, y: 1.41, y: 1.41, y: 1.41, g: g: function function (z) (z) { return (this.x (this.x + this.y)/z; }} g: function (z) {{ return return ++ this.y)/z; this.y)/z; g: return (this.x (this.x this.y)/z; } } g: function function (z) (z) { { return (this.x + + this.y)/z; } } } } } }
If If you you perform perform the the following following statement statement If you perform the following statement If If you perform the following statement If you you perform perform the the following following statement statement alert(obj5.g(3)); alert(obj5.g(3)); alert(obj5.g(3)); alert(obj5.g(3)); alert(obj5.g(3));
you you get get the the result result 1.5166666666666. 1.5166666666666. you get the result 1.5166666666666. you 1.5166666666666. you get get the the result result 1.5166666666666.
Download free eBooks at bookboon.com 71 71 71 71 71 71
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE JAVA 12:PART: WWW AND DEVELOPMENT OF THE CLIENT SOFTWARE DEVELOPMENT CLIENT PART: SOFTWARE DEVELOPMENT CLIENT PART: SOFTWARE DEVELOPMENT
JavaScript JavasCrIpt JavasCrIpt
Since Since obj1 obj1 isis as as above, above, you you usually usually refer refer to to the the individual individual properties properties using using the the dot dot notation, notation, Since obj1 is as above, you usually refer to the individual properties using the dot notation, but but you you can can also also use use array array notation, notation, which which uses uses the the name name of of the the property property as as an an index: index: but you can also use array notation, which uses the name of the property as an index: alert(obj1.a); alert(obj1.a); alert(obj1["a"]); alert(obj1["a"]);
Both of of these these statement statement will will display display an an alert() alert() with with the the value value 2. 2. The The main main application application of of Both Both of these statement will display an alert() with the value 2. The main application of the last last notation notation isis that that itit allows allows to to loope loope over over an an object’s object’s properties properties without without knowing knowing the the last notation is that it allows to loope over an object’s properties without knowing their names: names: their their names: for (var t in obj1) alert(obj1[t]); for (var t in obj1) alert(obj1[t]);
This statement statement will will alert alert 2, 2, 33 and and 5. 5. This This statement will alert 2, 3 and 5. You can can create create objects objects in in three three ways. ways. You You can can create create objects objects directly directly as as shown shown above above with with You You can create objects in three ways. You can create objects directly as shown above with obj1 and and obj5, obj5, that that is, is, you you directly directly write write the the properties properties that that the the object object should should have. have. You You can can obj1 obj1 and obj5, that is, you directly write the properties that the object should have. You can also create create an an object object with with Object.create() Object.create() such such as as obj3 obj3 and and obj4, obj4, where where an an object object isis created created as as also also create an object with Object.create() such as obj3 and obj4, where an object is created as an extension extension of of another another object. object. Finally, Finally, you you can can create create objects objects using using aa constructor. constructor. Consider Consider an an extension of another object. Finally, you can create objects using a constructor. Consider the following following function: function: the the following function:
Download free eBooks at bookboon.com 72 72 72
Click on the ad to read more
JAVA 12: WWW AND DEVELOPMENT OF THE JAVA 12: 12: WWW AND DEVELOPMENT DEVELOPMENT OF THE THE CLIENT PART: SOFTWARE DEVELOPMENT JAVA WWW AND OF CLIENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT
JavaScript JavasCrIpt JavasCrIpt
function function pointConstructor(x, pointConstructor(x, y) y) { { this.x this.x = = x; x; this.y = this.y = y; y; this.dist this.dist = = function function (p) (p) { { return Math.sqrt((this.x – p.x) * (this.x – p.x) + return Math.sqrt((this.x – p.x) * (this.x – p.x) + (this.y – p.y) * (this.y – p.y)); (this.y – p.y) * (this.y – p.y)); } } this.toString this.toString = = function() function() { { return return "( "( " " + + this.x + ", " + this.y + " )"; } this.x + ", " + this.y + " )"; } } }
The function creates an object with properties, where the last two are methods. An object The function function creates creates an an object object with with 44 4 properties, properties, where where the the last last two two are are methods. methods. An An object object The is perceived as a point in a coordinate system, and the method dist() has a parameter that perceived as as aa point point in in aa coordinate coordinate system, system, and and the the method method dist() dist() has has aa parameter parameter that that isis perceived is to be interpreted as a point. The method returns the distance between the current point to be be interpreted interpreted as as aa point. point. The The method method returns returns the the distance distance between between the the current current point point isis to and the parameter p. The last method is an override of toString(). You should note that and the the parameter parameter p.p. The The last last method method isis an an override override of of toString(). toString(). You You should should note note that that and the method has parameters, but not necessary. Below how to use the constructor the method method has has parameters, parameters, but but itit it isis is not not necessary. necessary. Below Below isis is how how to to use use the the constructor constructor the method to create two objects: method to to create create two two objects: objects: method var var var var
p1 p1 p2 p2
= = = =
new new new new
pointConstructor(2, pointConstructor(2, pointConstructor(5, pointConstructor(5,
3); 3); 7); 7);
The The following following statement statement alert(p1 alert(p1 + + "\n" "\n" + + p2 p2 + + "\n" "\n" + + p1.dist(p2)); p1.dist(p2));
will will opens popup as shown belove: will opens opens aaa popup popup as as shown shown belove: belove:
In In principle, does not matter whether an object created in one way or another and you In principle, principle, itit it does does not not matter matter whether whether an an object object isis is created created in in one one way way or or another another and and you you use the most appropriate way. However, you must note that the constructor way resembles use the most appropriate way. However, you must note that the constructor way resembles use the most appropriate way. However, you must note that the constructor way resembles how how to to create create objects objects in in Java. Java. how to create objects in Java.
Download free eBooks at bookboon.com 73 73 73
JAVA JAVA12: 12:WWW WWWAND ANDDEVELOPMENT DEVELOPMENTOF OFTHE THE CLIENT CLIENTPART: PART:SOFTWARE SOFTWAREDEVELOPMENT DEVELOPMENT
JavaScript JavasCrIpt
II will will finish finish this this section section on on objects objects with with an an example example of of aa cup cup object object representing representing aa 5-cube 5-cube rafle rafle cup cup where where aa cube cube should should be be represented represented by by aa cube cube object. object. The The example example applies applies in in addition addition more more control control statements statements (loops) (loops) and and also also arrays arrays that that are are dealt dealt with with in in the the next next section. section. The The example example will will also also use use the the module module concept concept described described in in the the previous previous section. section. The The code code isis as as follows: follows: CubesProgram Play Yatzy You've got yatzy after attempts
Download free eBooks at bookboon.com 75 75
Click on the ad to read more
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE CLIENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT
JavaScript JavasCrIpt
In In the the header header section section isis defined defined aa module module called called cup, cup, which which represented represented aa cup cup with with 55 cubes cubes and and three three public public attributes: attributes: 1. 1. toss(), toss(), that that isis aa method, method, which which simulates simulates the the use use of of the the cup cup 2. 2. yatzy(), yatzy(), which which isis aa method, method, that that tests tests where where all all 55 cube cube values values are are the the same same 3. 3. toString(), toString(), that that isis an an override override of of toString() toString() Initially, Initially, aa constructor constructor method method isis defined defined that that creates creates aa cube cube object. object. An An object object public public isis defined defined which which uses uses the the constructor constructor method method to to create create an an array array of of 55 cube cube objects. objects. The The public public object object has has three three functions functions that that implement implement the the above above methods. methods. The The body body part part simulates simulates using the cup until all cubes have the same value. using the cup until all cubes have the same value.
EXERCISE EXERCISE 11 Create Create aa copy copy of of the the program program CupProgram. CupProgram. You You must must then then create create aa folder folder resources resources and and aa subfolder subfolder jsjs and and to to that that folder folder aa JavaScript JavaScript file: file:
You You must must then then move move all all your your script script code code from from index.xhtml index.xhtml to to tools.js tools.js –– but but without without the the script script elements. elements. index.xhtml index.xhtml must must have have aa link link in in the the header header to to the the JavaScript JavaScript file. file. You You du du that by draging til file name to the header. The result of index.xhtml should be: that by draging til file name to the header. The result of index.xhtml should be: CubesProgram Play Yatzy You've got yatzy after attempts
Test the program, at it should works as before. When using JavaScript, you will usually place the code in its own file, as shown in this exercise. Arrays Arrays works immediately in the same way as in other programming languages and with the same syntax known from Java, but there are also important differences. In JavaScript arrays are dynamic and should not be allocated for a certain size. The following function opens a popup that shows the length of an array as well as the array’s elements: function show(arr) { var str = arr.length + "\n"; for (var i = 0; i < arr.length; ++i) str += "\n" + arr[i]; alert(str); }
If you consider this function, note that syntactically, an array is used in the same way as in Java. An array has a length property, and the individual elements are referenced via an 0-based index. var arr1 = ["Svend", "Knud", "Valdemar"];
The statement statement creates creates an an array array of of three three elements elements and and sends sends this this array array to to the the function function show(), show(), The you receives receives an an alert alert as as shown shown below: below: you
Download free eBooks at bookboon.com 77 77
JAVA 12: WWW AND DEVELOPMENT OF THE JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE CLIENT PART: SOFTWARE DEVELOPMENT CLIENT PART: SOFTWARE DEVELOPMENT CLIENT PART: SOFTWARE DEVELOPMENT
JavaScript JavasCrIpt JavasCrIpt
Since Since an array has no type, an array can contain elements of different types: Since an an array array has has no no type, type, an an array array can can contain contain elements elements of of different different types: types: var arr2 = ["Gorm", 3.13, { x: 2, y: 3 }, obj1]; var arr2 = ["Gorm", 3.13, { x: 2, y: 3 }, obj1];
where the array contains string, number and two objects. You can also create an array where where the the array array contains contains aaa string, string, aaa number number and and two two objects. objects. You You can can also also create create an an array array with constructor function: with with aaa constructor constructor function: function: var var arr3 arr3 = = new new Array(); Array(); show(arr3); show(arr3);
and the result is an empty array. If you have an array, you can immediately add items, and and and the the result result is is an an empty empty array. array. If If you you have have an an array, array, you you can can immediately immediately add add items, items, and and the array will dynamically expand: the array array will will dynamically dynamically expand: the expand: arr3[0] = 11; arr3[0] = 11; arr3[1] = 13; arr3[1] = 13; arr3[2] = 17; arr3[2] = 17; arr3[3] = 19; arr3[3] = 19; show(arr3); show(arr3);
Download free eBooks at bookboon.com 78 78 78
Click on the ad to read more
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE CLIENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT
JavaScript JavasCrIpt
and and the the array array now now have have 44 elements: elements:
An An array array may may also also have have “holes”, “holes”, and and thus thus elements elements that that are are not not defined: defined: arr1[5] = "Erik"; show(arr1);
Constructor Constructor functions functions can can have have parameters: parameters: var arr4 = new Array(4); var arr5 = new Array(23, 29, 31, 37);
and and here here the the first first creates creates an an array array of of length length 44 with with 44 undefined undefined elements, elements, while while the the other other creates creates an an array array with with 44 elements. elements. Finally, Finally, you you should should note note that that you you can can change change the the value value of of the the property property length length and and thus thus delete delete items items in in an an array. array. As As mentioned, mentioned, you you reference reference the the elements elements in in an an array array using using aa numeric numeric index, index, but but indexing indexing isis actually actually more more flexible flexible than than you you would would expect. expect. Consider Consider the the following following code: code: var arr = new Array(); arr[0] = 2; arr[1] = 3; arr["3"] = 5; arr["abc"] = 7; show(arr);
Download free eBooks at bookboon.com 79 79
JAVA JAVA 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE JAVA 12: 12: WWW AND DEVELOPMENT OF THE CLIENT CLIENT PART: SOFTWARE DEVELOPMENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT
JavaScript JavasCrIpt JavasCrIpt
First, First, note note that that the the code code does does not not fail fail and and itit will will display display the the following following alert: alert:
If the the index index isis not not aa number, number, the the interpreter interpreter will will try try to to convert convert itit to to an an integer integer and and the the If result of of result arr["3"] = 5; arr["3"] = 5;
isis therefore therefore the the element element with with index index 3. 3. On On the the other other hand, hand, itit isis not not immediately immediately clear clear what what arr["abc"] = 7; arr["abc"] = 7;
means when means when “abc” “abc” can can not not be be converted converted to to aa number. number. An An array array isis an an object, object, and and therefore therefore you can can specifically specifically define define its its own own properties. properties. This This isis exactly exactly what what happens happens here here as as arr[“abc”] arr[“abc”] you interpreted as as aa property property named named abc, abc, which which then then gets gets the the value value 7. 7. There There isis reason reason to to be be isis interpreted aware aware of of this this interpretation interpretation as as itit isis easy easy to to accidentally accidentally add add properties properties to to an an array. array. In In this this case case the the statement statement alert(arr.abc); alert(arr.abc);
will show show 7. 7. The The elements elements in in an an array array can can be be anything anything and and hence hence especially especially other other arrays. arrays. will It allows allows to to simulate simulate multidimensional multidimensional arrays. arrays. For For example example will will the the following following code code display display It an an alert alert with with the the value value 130: 130: var v1 = [2, 3, 6, 7]; var v1 = [2, 3, 6, 7]; var v2 = [11, 13, 17, 19]; var v2 = [11, 13, 17, 19]; var v3 = [23, 29]; var v3 = [23, 29]; var v = [v1, v2, v3]; var v = [v1, v2, v3]; var s = = 0; 0; var s for (var i = 0; i < v.length; ++i) for (var j = 0; j < v[i].length; ++j) s += v[i][j]; for (var i = 0; i < v.length; ++i) for (var j = 0; j < v[i].length; ++j) s += v[i][j]; alert(s); alert(s);
Download free eBooks at bookboon.com 80 80 80
JAVA 12: WWW AND DEVELOPMENT OF THE JAVA WWW AND OF JAVA 12: 12:PART: WWWSOFTWARE AND DEVELOPMENT DEVELOPMENT OF THE THE CLIENT DEVELOPMENT CLIENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT
JavasCrIpt JavaScript JavasCrIpt
In particular, note how to iterates the array v as a 2-dimensional array, but it is the In In particular, particular, note note how how to to iterates iterates the the array array vv as as aa 2-dimensional 2-dimensional array, array, but but itit is is the the programmer’s responsibility that the elements in v are actually arrays. Otherwise, you will programmer’s programmer’s responsibility responsibility that that the the elements elements in in vv are are actually actually arrays. arrays. Otherwise, Otherwise, you you will will get an error. Also note that v illustrates a heterogeneous array and thus an array where the get get an an error. error. Also Also note note that that vv illustrates illustrates aa heterogeneous heterogeneous array array and and thus thus an an array array where where the the rows do not have the same length. rows rows do do not not have have the the same same length. length. In fact, JavaScript is quite flexible as to how to define an array. Below is defined an array In In fact, fact, JavaScript JavaScript is is quite quite flexible flexible as as to to how how to to define define an an array. array. Below Below is is defined defined an an array array consisting of two arrays, and these arrays have elements of different types. The one even consisting consisting of of two two arrays, arrays, and and these these arrays arrays have have elements elements of of different different types. types. The The one one even even has an element that is not defined. has has an an element element that that is is not not defined. defined. var konger = [["Gorm", , 958], ["Harald Blåtand", 958, 986]]; var konger = [["Gorm", , 958], ["Harald Blåtand", 958, 986]]; for (var i = 0; i < konger.length; ++i) show(konger[i]); for (var i = 0; i < konger.length; ++i) show(konger[i]);
You should should note note that that there there are are aa number number of of standard standard functions for arrays that I mentions You You should note that there are a number of standard functions for arrays that I mentions in aa later later section. section. in in a later section.
EXERCISE 2 EXERCISE 2
The Fibonacci Fibonacci numbers numbers are, are, as as you you know, know, the the following following sequence: sequence: The The Fibonacci numbers are, as you know, the following sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, …. 0, 1, 1, 2, 3, 5, 8, 13, 21, ….
93%
OF MIM STUDENTS ARE WORKING IN THEIR SECTOR 3 MONTHS FOLLOWING GRADUATION
MASTER IN MANAGEMENT • STUDY IN THE CENTER OF MADRID AND TAKE ADVANTAGE OF THE UNIQUE OPPORTUNITIES THAT THE CAPITAL OF SPAIN OFFERS • PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR PROFESSIONAL GOALS • STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS EXPERIENCE
5 Specializations
Personalize your program
www.ie.edu/master-management
#10 WORLDWIDE MASTER IN MANAGEMENT FINANCIAL TIMES
[email protected]
Download free eBooks at bookboon.com 81 81 81
Length: 1O MONTHS Av. Experience: 1 YEAR Language: ENGLISH / SPANISH Format: FULL-TIME Intakes: SEPT / FEB
55 Nationalities
in class
Follow us on IE MIM Experience
Click on the ad to read more
JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT PART: SOFTWARE DEVELOPMENT
JavaScript
Create a new project, that you can call FiboProgram. The project must have a start page index.html that shows the first 95 fibonacci numbers in a table (se the window belove). The program should be written as follows: 1. The project must have a JavaScript file, that contains a module called fibonacci, which automatically creates a private array, that contains the fibonacci numbers. The module must have two public properties, where the first is called length, and is a simple property whose value is the length of the array, while the other property is a function get(n), that returns the n’th fibonacci number. 2. The table and the header text should be styled by a simple style sheet. 3. The start page index.html must dynamic generate the table in JavaScript.
Functions In JavaScript is a function as mentioned an object. That means more things, for example that a function can be return value from another function and that a function can be a parameter to another function. It also means that a function may have properties and methods like any other object. These relationships means that functions in many ways are different from functions in other languages like Java.
Download free eBooks at bookboon.com 82
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE JAVA 12: WWW AND OF CLIENT SOFTWARE DEVELOPMENT JAVA 12:PART: WWW AND DEVELOPMENT DEVELOPMENT OF THE THE CLIENT PART: SOFTWARE DEVELOPMENT JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT CLIENT PART: SOFTWARE DEVELOPMENT
JavaScript JavasCrIpt JavasCrIpt JavasCrIpt JavasCrIpt
AA function function isis usually usually created created with with the the reserved reserved word word function: function: A function is usually created with the reserved word function: A function is usually created with the reserved word A function is usually created with the reserved word function: function: function function function { function { { } { } } }
factorial(n) factorial(n) factorial(n) factorial(n)
and the the function function may may have have an an arbitrary arbitrary number number of of parameters parameters and and especially especially none. none. Since Since and and the function may have an arbitrary number of parameters and especially none. Since and the function may have an arbitrary number of parameters and especially none. Since and the function may have an arbitrary number of parameters andcan especially none.refer Since a function can refer to all variables in its own scope, the function specifically to aaa function can refer to all variables in its own scope, the function can specifically refer to function can refer to all variables in its own scope, the function can specifically refer to function can refer to all variables in its own scope, the function can specifically refer aitself function cancan refertherefore to all variables in its own scope, the function can specifically refer to to and you write recursive functions: itself and you can therefore write recursive functions: itself and you can therefore write recursive functions: itself and you can therefore write recursive functions: itself and you can therefore write recursive functions: function factorial(n) function factorial(n) function factorial(n) { function factorial(n) { { if (n < 1) return 1; { if (n < 1) return 1; if (n < return n * factorial(n – 1); if (n < 1) 1) return return 1; 1; return n * factorial(n – 1); return n * factorial(n – 1); } return n * factorial(n – 1); } } }
It is allowed to declare a function multiple times in the same scope, which simply means allowed to declare function multiple times in the same scope, which simply means ItIt isis to aaa function in which means It is allowed to declare function multiple multiple times in the the same same scope, scope, which simply means It is allowed allowed to declare declare multiple times times scope, which simply simply means that the function name aisfunction given a different value. in It the can same also give unexpected results. For that the function name is given aa different different value. It can also give unexpected results. For that the function name is given a value. It can also give unexpected results. For that the function name is given different value. It can also give unexpected results. For that the function name isthe given a different example, if you consider following code:value. It can also give unexpected results. For example, if you consider the following code: example, example, you consider the following code: example, ifif if you you consider consider the the following following code: code: function f() function f() function f() { function f() { { {return 23; return 23; }return return 23; 23; } } alert(f()); } alert(f()); alert(f()); function f() alert(f()); function f() function f() { function f() { { return 29; { return 29; return 29; } return 29; } } }
it will alert 29. The reason is that JavaScript collects all definitions at the start of a scope it will alert 29. The reason is that JavaScript collects all definitions at the start of a scope will alert 29. The reason that JavaScript collects all definitions at the start of scope itit will 29. isis JavaScript it will alert 29.isThe The reason is that thatto: JavaScript collects collects all all definitions definitions at at the the start start of of aaa scope scope and thealert above thusreason equivalent and the above is thus equivalent to: and the above is thus equivalent to: and and the the above above isis thus thus equivalent equivalent to: to: function f() function f() function f() { function f() { { {return 23; return 23; }return return 23; 23; } } function f() } function f() function f() { function f() { { return 29; { return 29; return 29; } return 29; } } alert(f()); } alert(f()); alert(f()); alert(f());
Download free eBooks at bookboon.com 83 83 83 83 83
JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE JAVA JAVA 12:PART: WWW AND DEVELOPMENT OF THE CLIENT PART: SOFTWARE DEVELOPMENT CLIENT SOFTWARE DEVELOPMENT CLIENT PART: SOFTWARE DEVELOPMENT
JavasCrIpt JavaScript JavasCrIpt
In JavaScript, JavaScript, you you can can also also define define aa function function as as an an expression: expression: In In JavaScript, you can also define a function as an expression: var show = function (arr) var show = function (arr) { { var str = arr.length + "\n"; var str = arr.length + "\n"; for (var i = 0; i < arr.length; ++i) str += "\n" + arr[i]; for (var i = 0; i < arr.length; ++i) str += "\n" + arr[i]; alert(str); alert(str); } } show([2, 3, 5, 7]); show([2, 3, 5, 7]);
The Varablen show refers to an anonymous function, and the use of anonymous functions The The Varablen Varablen show show refers refers to to an an anonymous anonymous function, function, and and the the use use of of anonymous anonymous functions functions is widely used in JavaScript. Consider the following example: isis widely widely used used in in JavaScript. JavaScript. Consider Consider the the following following example: example: function validate(x, ok) function validate(x, ok) { { if (ok(x)) return true; if (ok(x)) return true; alert(x + " er en ulovlig værdi"); alert(x + " er en ulovlig værdi"); return false; return false; } }
DO YOU WANT TO KNOW:
What your staff really want?
The top issues troubling them?
How to retain your top staff FIND OUT NOW FOR FREE
How to make staff assessments work for you & them, painlessly?
Get your free trial Because happy staff get more done
Download free eBooks at bookboon.com 84 84 84
Click on the ad to read more
JAVA JAVA12: 12:WWW WWWAND ANDDEVELOPMENT DEVELOPMENTOF OFTHE THE CLIENT CLIENTPART: PART:SOFTWARE SOFTWAREDEVELOPMENT DEVELOPMENT
JavaScript JavasCrIpt
The Thefunction functionhas hastwo twoparameters, parameters,the thelatter latterbeing beinginterpreted interpretedas asaafunction functionthat thatwill willvalidate validate the the first first parameter. parameter. The The function function could, could, for for example, example, be be used used as as follows: follows: validate(1234, function (t) { return t >= 100 && t More text about
DOM objects
All rights reserved.
© 2013 Accenture.
Bring your talent and passion to a global organization at the forefront of business, technology and innovation. Discover how great you can be. Visit accenture.com/bookboon
Download free eBooks at bookboon.com 96 96
Click on the ad to read more
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE CLIENT SOFTWARE DEVELOPMENT CLIENT PART: SOFTWARE DEVELOPMENT JAVA 12:PART: WWW AND DEVELOPMENT OF THE
JavaScript JavasCrIpt
CLIENT PART: SOFTWARE DEVELOPMENT
JavasCrIpt
The The page page defines defines in in the the header header two two classes, classes, called called respectively respectively blueClass blueClass and and plainClass. plainClass. The The The page defines in the header two classes, called respectively blueClass and plainClass. The document document has has 44 elements elements as as aa h1 h1 element, element, aa h3 h3 element element and and two two paragraphs. paragraphs. The The first first document contains has 4 elements as the a h1 element, h3 element twoaa paragraphs. first paragraph aa link other aa span Then follow script starting paragraph contains link and and the other spanaelement. element. Thenand follow script block, block,The starting paragraph contains a link and the other a span element. Then follow a script block, starting with an with an alert: alert: with an alert: alert(par.innerText); alert(par.innerText);
which shows the text in the last paragraph. The paragraph is referred to by its ID, and which shows the text in The paragraph isis referred to by and which showsnote thethat textyou in the the last paragraph. Theshould paragraph referred toHTML by its its ID, ID, and you should can last do itparagraph. directly. You also note that the element you that can do itit directly. You should element you should should note that you you can of doinnerText. directly.The Youresult should also note that the HTML element span is not note displayed as part is also thatnote afterthat the the pageHTML is opened, the span is not displayed as part of innerText. The result is that after the page is opened, the span is not displayed as part of innerText. The result is that after the page is opened, the browser displays the following: browser browser displays displays the the following: following:
and next the following alert: and and next next the the following following alert: alert:
The next alert: The The next next alert: alert: alert(par.innerHTML); alert(par.innerHTML);
shows the same element, but this time it’s innerHTML. Unlike innerText, innerHTML shows shows the same same element, but but this time time it’s innerHTML. innerHTML. Unlike Unlike innerText, innerText, innerHTML innerHTML shows shows shows the element, this it’s the entire text including HTML elements: the entire entire text text including including HTML HTML elements: elements: the
Download free eBooks at bookboon.com 97 97 97
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE JAVA 12: WWW AND OF JAVA 12:PART: WWW AND DEVELOPMENT DEVELOPMENT OF THE THE CLIENT SOFTWARE DEVELOPMENT CLIENT PART: SOFTWARE DEVELOPMENT CLIENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT
JavaScript JavasCrIpt JavasCrIpt JavasCrIpt
The first The first paragraph paragraph has has an an id id named named adr. adr. This This paragraph paragraph has has aaa link link (an (an element) element) as as aaa child child The The first first paragraph paragraph has has an an id id named named adr. adr. This This paragraph paragraph has has a link link (an (an element) element) as as a child child element, and the variable link isis set to refer to this element. Here you should especially element, and the variable link set to refer to this element. Here you should especially element, and the variable link is set to refer to this element. Here you should especially element, and the variable link is set to refer to this element. Here you should especially note the note the method method querySelector() querySelector() and and the the syntax syntax to to refer refer to to aaa child child element element for for the the element element note note the the method method querySelector() querySelector() and and the the syntax syntax to to refer refer to to a child child element element for for the the element element with id adr :: with id adr with id adr : with id adr : var link = document.querySelector("#adr a"); var link = document.querySelector("#adr a"); var link = document.querySelector("#adr a");
The The following following statements statements are are used used to to modify modify properties properties of of this this element. element. The The following following statements statements are are used used to to modify modify properties properties of of this this element. element. The The variable variable txt txt refers refers to to the the h3 h3 element. element. An An HTML HTML element element has has (in (in HTML5) HTML5) aaa list list for for The The variable variable txt txt refers refers to to the the h3 h3 element. element. An An HTML HTML element element has has (in (in HTML5) HTML5) a list list for for class objects. The reference txt used to add class objects to the element h3. The result class objects. The reference txt isis used to add class objects to the element h3. The result isis class objects. The reference txt is used to add class objects to the element h3. The result class objects. The reference txt is used to add class objects to the element h3. The result is is that h3 gets aaa blue background and the text isis displayed as normal. The next statement: that h3 gets blue background and the text displayed as normal. The next statement: that h3 gets blue background and the text is displayed as normal. The next statement: that h3 gets a blue background and the text is displayed as normal. The next statement: document.getElementsByTagName("h1")[0].innerText = "Hello World"; document.getElementsByTagName("h1")[0].innerText = "Hello World"; document.getElementsByTagName("h1")[0].innerText = "Hello World";
changes the text in the element h1 by changing the element’s innerText. You must primarily changes changes the text in the element h1 by changing the element’s innerText. You must primarily changes the the text text in in the the element element h1 h1 by by changing changing the the element’s element’s innerText. innerText. You You must must primarily primarily note the reference (the h1 element has no id), and getElementsByTagName() is an array with all note the reference (the h1 element has no id), and getElementsByTagName() is an array note with all note the the reference reference (the (the h1 h1 element element has has no no id), id), and and getElementsByTagName() getElementsByTagName() is is an an array array with with all all h1 elements, and you get the first (and in this case only) by referring the item with index 0. h1 elements, and you get the first (and in this case only) by referring the item with index h1 elements, and you get the first (and in this case only) by referring the item with index 0. h1 elements, and you get the first (and in this case only) by referring the item with index 0. 0. par are id for a paragraph containing some HTML and the following statement replaces par par are id for paragraph containing some HTML and the following statement replaces par are are id id for for aaa paragraph paragraph containing containing some some HTML HTML and and the the following following statement statement replaces replaces this HTML with a list of 3 elements: this HTML with a list of 3 elements: this this HTML HTML with with aa list list of of 3 3 elements: elements: par.innerHTML = "
"; par.innerHTML = "
"; par.innerHTML = "
";
You can therefore specifically change a DOM object to something completely different. You can therefore specifically change DOM object to something completely different. You You can can therefore therefore specifically specifically change change aaa DOM DOM object object to to something something completely completely different. different. Next, two variables head and elem are defined, which refer respectively to the document’s Next, two variables head and elem are defined, which refer respectively to the document’s Next, Next, two two variables variables head head and and elem elem are are defined, defined, which which refer refer respectively respectively to to the the document’s document’s header as well as aa new element that is aa script element. You can in that way create new header as well as new element that is script element. You can in that way create new header header as as well well as as aa new new element element that that isis aa script script element. element. You You can can in in that that way way create create new new HTML elements: HTML elements: HTML HTML elements: elements: elem = document.createElement("script"); var var var elem elem = = document.createElement("script"); document.createElement("script");
Download free eBooks at bookboon.com 98 98 98 98
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE CLIENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT
JavaScript JavasCrIpt
Next, Next, this this element’s element’s innerText innerText isis defined defined as as aa JavaScript JavaScript function. function. The The new new script script element element isis added added to to the the head head variable variable as as aa child child node. node. This This means means that that in in the the header header part part of of the the document there dynamically is added a script element with a Javascript function. Next, document there dynamically is added a script element with a Javascript function. Next, two two more more variables variables are are defined. defined. body body isis aa reference reference to to the the body body of of the the document, document, and and txt txt isis aa reference reference to to aa paragraph paragraph element. element. The The new new (and (and empty) empty) paragraph paragraph isis assigned assigned an an id id and and isis added added to to the the body body of of the the page, page, meaning meaning itit isis inserted inserted as as an an empty empty node node in in the the DOM DOM tree. Finally, the content of the new paragraph is changed to some HTML. Note that tree. Finally, the content of the new paragraph is changed to some HTML. Note that itit includes includes the the dynamically dynamically added added Javascript Javascript function function being being executed executed and and the the value value isis inserted inserted in in the the new new paragraph: paragraph: document.getElementById("fact").innerHTML = "10! = " + factorial(10) + " for="date"/> style="width:
Youshould shouldnote notethat thatthere thereis nolonger longerany anyajax ajaxfunction functionassociated associatedwith withthe thecomponent, component, You should note that there isisno no longer any ajax function associated with the component, You andIIIhave havealso alsochanged changedthe thetext textin thecorresponding correspondinglabel. label. and have also changed the text ininthe the corresponding label. and Inorder orderto toinitialize initializethe thefield fielddate dateIIIhave havein theclass classPerson Personchanged changedthe theconstructor constructorso soititit In order to initialize the field date have ininthe the class Person changed the constructor so In initializesthe thedate datefield fieldto tothe thecurrent currentdate: date: initializes the date field to the current date: initializes Person() public public Person() {{ Calendar cal cal == Calendar.getInstance(); Calendar.getInstance(); Calendar date = String.format("%02d-%02d-%04d", cal.get(Calendar.DATE), date = String.format("%02d-%02d-%04d", cal.get(Calendar.DATE), cal.get(Calendar.MONTH) ++ 1, 1, cal.get(Calendar.YEAR)); cal.get(Calendar.YEAR)); cal.get(Calendar.MONTH) }}
Finally, Finally,the theajax ajaxfunction functionof thesubmit submitbutton buttonin index.xhtmlis changed: Finally, the ajax function ofofthe the submit button ininindex.xhtml index.xhtml isischanged: changed: value="Send" action="#{indexController.add()}" action="#{indexController.add()}" >>
Download free eBooks at bookboon.com 121 121 121 121
JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE JAVA CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT CLIENT
Javaserver Faces FaCes and and Ajax aJax JavaServer
Looking at at the the input input component component date, date, itit has has both both aa validator validator and and aa converter, converter, and and here here you you Looking should be be aware aware of of the the order order of of when when the the methods methods are are performed: performed: should 1. getAsObject() // getAsObject() // the the class class DateConverter DateConverter 1. 2. validate() validate() // // the the class class DateValidator DateValidator 2. 3. getAsString() // getAsString() // the the class class DateConverter DateConverter 3.
5.4 JSF JSF LISTENERS LISTENERS 5.4 JSF components components can can raise raise different different events events when when rendered rendered (where (where the the names names tells tells when when the the JSF events occurs): occurs): events ---------
preRenderComponent, preRenderComponent, postAddToView postAddToView preValidate preValidate postValidate postValidate
You can can define define listeners listeners for for these these events, events, which which are are Java Java code, code, which which are are performed performed on on the the You server. As As an an example, example, II have have created created aa copy copy of of the the project project ChangeAddress4 ChangeAddress4 and and called called the the server. copy ChangeAddress5. ChangeAddress5. First First of of all, all, II have have changed changed the the code code for for index.xhtml index.xhtml so so that, that, like like in in copy ChangeAddress1, itit has has an an ajax ajax function function for for each each input input component. component. As As the the next next step, step, the the ChangeAddress1, IndexController isis expanded expanded with with two two methods: methods: IndexController public String isWeekend() { String[] elems = person.getDate().split("-"); Calendar date = new GregorianCalendar(Integer.parseInt(elems[2]), Integer.parseInt(elems[1]) – 1, Integer.parseInt(elems[0])); return date.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY || date.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY ? "red" : "darkgreen"; } public void checkForWeekend(ComponentSystemEvent event) { UIOutput output = (UIOutput) event.getComponent(); if (isWeekend().equals("red")) output.setValue("Weekend"); else output.setValue("Everyday"); }
Download free eBooks at bookboon.com 122 122
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE CLIENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT
JavaServer Javaserver Faces FaCes and and Ajax aJax
The The class class Person Person has has aa property property date date initialized initialized with with today, today, and and the the first first method method test test where where this this date date is is for for aa weekend weekend (Saturday (Saturday or or Sunday). Sunday). If If that that is is the the case, case, the the method method returns returns the the text text red red and and otherwise otherwise the the text text darkgreen. darkgreen. The The next next method method is is aa listener listener method. method. Its Its parameter parameter is an event and the method determines a reference to the component to which is an event and the method determines a reference to the component to which the the event event relates. relates. If If the the Person Person object’s object’s date date property property is is aa date date of of aa weekend, weekend, the the component’s component’s value value is is set set to to Weekend Weekend and and otherwise otherwise to to Everyday. Everyday. The The two two methods methods are are basically basically simple simple Java Java methods, methods, and and II will will now now show show how how they they can can be be used used as as event event handlers handlers in in index.xhtml. index.xhtml. The The form form is is expanded expanded with with aa new new element element of of the the type type outputText outputText (the (the only only requirement requirement is is that that itit is is aa component component with with aa value value property): property):
93%
OF MIM STUDENTS ARE WORKING IN THEIR SECTOR 3 MONTHS FOLLOWING GRADUATION
MASTER IN MANAGEMENT • STUDY IN THE CENTER OF MADRID AND TAKE ADVANTAGE OF THE UNIQUE OPPORTUNITIES THAT THE CAPITAL OF SPAIN OFFERS • PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR PROFESSIONAL GOALS • STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS EXPERIENCE
5 Specializations
Personalize your program
www.ie.edu/master-management
#10 WORLDWIDE MASTER IN MANAGEMENT FINANCIAL TIMES
[email protected]
Download free eBooks at bookboon.com 123 123
Length: 1O MONTHS Av. Experience: 1 YEAR Language: ENGLISH / SPANISH Format: FULL-TIME Intakes: SEPT / FEB
55 Nationalities
in class
Follow us on IE MIM Experience
Click on the ad to read more
JAVA 12: WWW AND DEVELOPMENT OF THE JAVA 12:PART: WWW AND DEVELOPMENT OF THE CLIENT SOFTWARE DEVELOPMENT CLIENT PART: SOFTWARE DEVELOPMENT
JavaServer Faces and Ajax Javaserver FaCes and aJax
The new new elements elements have have an an id id with with the the value value weekend weekend as as well well as as aa style style attribute, attribute, where where you you The should primarily primarily note note that that the the value value of of color color isis determined determined by by the the return return value value from from the the should method isWeekend(), isWeekend(), which which isis either either red red or or darkgreen. darkgreen. As As aa result, result, the the text text appears appears either either method as red red or or green. green. Finally, Finally, the the element element defines defines an an event event of of the the type type preRenderComonent. preRenderComonent. That That as is, the the event event handler handler (the (the element’s element’s listener) listener) isis performed performed before before the the element element isis rendered rendered is, and the the handler handler isis the the method method checkForWeekend() checkForWeekend() in in the the controller controller class. class. ItIt isis executed executed each each and time the the element element isis rendered, rendered, which which naturally naturally occurs occurs when when the the page page isis rendered, rendered, but but itit also also time happens when when the the input input component component to to date date isis changed, changed, as as the the ajax ajax function function indicates indicates that that happens the element element with with id id weekend weekend must must be be rendered. rendered. the
Download free eBooks at bookboon.com 124 124
JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT PART: SOFTWARE DEVELOPMENT
Component libraries
6 COMPONENT LIBRARIES As shown in the previous chapter, JSF and especially in combination with Ajax provide a range of facilities that makes it easy to develop attractive and dynamic web applications, but there is a lot more to do with, and among other things there are several thirds parts JSF component libraries. In this chapter I will give an introductory note to one of these libraries, called PrimeFaces. Basically, it’s a library that essentially defines its own component for each of the standard JSF components as well as expanding with a skeleton for a web applcatation that makes it easy to develop a stable application from scratch. The motivation for using PrimeFaces is primarily to make it easy to develop user-friendly web applications, but also that the library offers other services that JSF does not immediately provide, and in fact, the idea is that the user to the least extent should work with style sheets and JavaScript – two things that in practice can be quite time consuming. As mentioned, there are other JSF component libraries, but I would like to introduce PrimeFaces, as the library is directly supported by NetBeans, without the need to install the libraries in question (which is also quite easy). One can achieve significant benefits with PrimeFaces, but the price is that you must know the library (a bit like jQuery) and you should be aware that the developers of PrimeFaces have an idea of how web applications should look and work, and if you want to deviate from it, it is not always that easy. I want to start with a usual web application, which I have called ChangeAddress6. When I come to Frameworks, I’ve chosen JavaFaces as usual, and here I clicked on the Components tab and chose PrimeFaces:
Download free eBooks at bookboon.com 125
JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT PART: SOFTWARE DEVELOPMENT
Component libraries
When I then click Finish, NetBeans as usually creates a web application with three files added:
In addition to index.xhtml and web.xml, another welcomePrimefaces.xhtml page has been created, which is the application’s start page. The result is a fully completed web application and opens it in the browser, you get the following window:
DO YOU WANT TO KNOW:
What your staff really want?
The top issues troubling them?
How to retain your top staff FIND OUT NOW FOR FREE
How to make staff assessments work for you & them, painlessly?
Get your free trial Because happy staff get more done
Download free eBooks at bookboon.com 126
Click on the ad to read more
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE CLIENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT
Component CoMponent libraries LIbrarIes
It It is is index.xhtml, index.xhtml, but but clicking clicking on on the the link link opens opens the the window: window:
which which is is welcomePrimefaces.xhtml. welcomePrimefaces.xhtml. That That is, is, NetBeans NetBeans has has generated generated aa skeleton skeleton for for aa page, page, and and itit is is then then the the task task of of the the programmer programmer to to fill fill in in with with something something sensible. sensible. You You should should note note that that the the page’s page’s design design is is made made without without the the use use of of style style sheets sheets or or JavaScript, JavaScript, but but all all built into the library. built into the library. index.xhtml index.xhtml does does not not contain contain anything anything new new or or anything anything about about PrimeFaces, PrimeFaces, and and of of course, course, the the goal goal is is to to change change itit for for the the specific specific task. task. The The new new things things are are found found in in welcomePrimes. welcomePrimes. xhtml, where NetBeans has created the following page: xhtml, where NetBeans has created the following page:
Download free eBooks at bookboon.com 127 127
JAVA 12: WWW AND DEVELOPMENT OF THE JAVA 12: 12:PART: WWW AND DEVELOPMENT DEVELOPMENT OF THE THE CLIENT SOFTWARE DEVELOPMENT JAVA WWW AND OF CLIENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT
Component libraries CoMponent CoMponent LIbrarIes LIbrarIes
PrimeFaces PrimeFaces Header Header Footer Footer collapsible="true"> * > tr, .ui-panelgrid > * > tr > td.ui-panelgrid-cell { border: none; } .ui-message.ui-widget { font-size: 10pt; }
Download free eBooks at bookboon.com 133 133
JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE JAVA CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT CLIENT
CoMponent libraries LIbrarIes Component
and here it’s not so easy to know what classes to override. In addition, be aware that the style sheet must be loaded after PrimeFaces’ own style sheets are used and one way is to do it at the start the body section as shown in the code above. Then there is the page list.xhtml: Adresses Addresses Enter your address, your job position and from when this information applies
Entered addresses in this session Name
Download free eBooks at bookboon.com 134 134
JAVA 12: WWW AND DEVELOPMENT OF THE JAVA CLIENT 12: WWW ANDSOFTWARE DEVELOPMENT OF THE PART: DEVELOPMENT CLIENT PART: SOFTWARE DEVELOPMENT
Deloitte & Touche LLP and affiliated entities.
Component libraries CoMponent LIbrarIes
Address City Title Mail Date
Download free eBooks at bookboon.com 137 137
JAVA 12: WWW AND DEVELOPMENT OF THE CLIENT PART: SOFTWARE DEVELOPMENT
CoMponent Component LIbrarIes libraries
You should note that the element p:poll automatically uses ajax, so it is only the current label that is being updated. To display the clock well, the style sheet is expanded with the following class: .time-text { margin-top: 30px; color: darkmagenta; font-weight: bold; font-size: 40pt; }
and again, you should note that conventional web technologies can be combined with PrimeFaces without difficulty. The opposite also applies to the use of a function such as p:poll without else using PrimeFaces. NY026057B
TMP PRODUCTION
6.2 6.2 A P:AUTOCOMPLETE ELEMENT
6x4
4
12/13/2013
ACCCTR00
PSTANKIE
As another gl/rv/rv/baf
application of PrimeFaces, I want to show a so-called autocomplete. Bookboon AdThe Creative application ChangeAddress8 is another extension, and if you in the field for the city name begin to enter the name, you get a dropdown list with the name that matches:
All rights reserved.
© 2013 Accenture.
Bring your talent and passion to a global organization at the forefront of business, technology and innovation. Discover how great you can be. Visit accenture.com/bookboon
Download free eBooks at bookboon.com 138
Click on the ad to read more
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE CLIENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT
Component CoMponent libraries LIbrarIes
Specifically, Specifically, the the program program has has been been modified modified so so that that ifif you you are are in in the the field field for for zip zip code code and and enter enter an an existing existing zip zip code code (only (only existing existing zip zip codes codes are are legal), legal), then then the the city city name name will will be be filled filled in in automatically automatically and and ifif you you enter enter in in the the city city name name field field and and enter enter text, text, you you will will see see above above aa list list of of city city names names that that match match (contains) (contains) the the entered entered text text and and select select aa city city name, name, the the field field for for zip zip code code isis automatically automatically updated. updated. To To solve solve the the task task II have have first first added added the the following following class, class, which which isis aa table table of of Danish Danish zip zip codes: codes: package changeaddress.validators; import java.util.ArrayList; import java.util.List;
Download free eBooks at bookboon.com 139 139
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE JAVA 12:PART: WWW AND DEVELOPMENT OF THE CLIENT CLIENT PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT CLIENT PART: SOFTWARE DEVELOPMENT
Component CoMponent libraries LIbrarIes CoMponent LIbrarIes
public public class class Zipcodes Zipcodes { { public public static static String String getCity(String getCity(String code) code) { { for (String[] elem : codeArray) if (elem[0].equals(code)) return elem[1]; for (String[] elem : codeArray) if (elem[0].equals(code)) return elem[1]; return null; null; return } } public static static String String getCode(String getCode(String city) city) public { { city = = city.toLowerCase(); city.toLowerCase(); city for (String[] elem : codeArray) for (String[] elem : codeArray) if (elem[1].toLowerCase().equals(city)) return elem[0]; if (elem[1].toLowerCase().equals(city)) return elem[0]; return null; return null; } } public static static List List getCities(String getCities(String text) text) public { { text = = text.toLowerCase(); text.toLowerCase(); text List res res = = new new ArrayList(); ArrayList(); List for (String[] elem : codeArray) for (String[] elem : codeArray) if (elem[1].toLowerCase().contains(text)) res.add(elem[1]); if (elem[1].toLowerCase().contains(text)) res.add(elem[1]); return res; return res; } } private static String codeArray [][] = { private static String codeArray [][] = { { "0800", "0800", "Høje "Høje Taastrup" Taastrup" }, }, { { "0900", "København C" }, { "0900", "København C" }, … … } } } }
The The methods do not require any particular explanation, but more dynamic solution would The methods methods do do not not require require any any particular particular explanation, explanation, but but aaa more more dynamic dynamic solution solution would would of course be to load the zip codes from a Zip code:" code:" for="code" for="code" /> />
Regarding entering the zip code, there isis not much new, but note that there is another Regarding Regarding entering entering the the zip zip code, code, there there is not not much much new, new, but but note note that that there there is is another another validator attached. Note that it is also defined that the field for the city name must be validator attached. Note that it is also defined that the field for the city name must validator attached. Note that it is also defined that the field for the city name must be be updated. The most important isis by entering city name, where the element has now been updated. The most important by entering city name, where the element has now been updated. The most important is by entering city name, where the element has now been changed to aa p:autoComplete element. When you see the syntax, it’s easy enough to figure changed changed to to a p:autoComplete p:autoComplete element. element. When When you you see see the the syntax, syntax, it’s it’s easy easy enough enough to to figure figure out what’s happening, but note the special way to bind the complete() method that returns out what’s happening, but note the special way to bind the complete() method that returns out what’s happening, but note the special way to bind the complete() method that returns > Click to open an alert()
Download free eBooks at bookboon.com 156 156
Click on the ad to read more
JAVA JAVA 12: 12: WWW WWW AND AND DEVELOPMENT DEVELOPMENT OF OF THE THE CLIENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT
Appendix appendIx A: a: jQuery JQuery
First, First, note note that that in in the the header header there there isis aa script script element element that that refers refers to to the the jQuery jQuery file. file. In In addition, addition, there there isis aa script script element element with with some some JavaScript JavaScript code code that that uses uses jQuery. jQuery. Here Here means means $(document).ready
that the following JavaScript code is executed – after the DOM tree is constructed, but that the following JavaScript code is executed – after the DOM tree is constructed, but before the tree’s elements are rendered by the browser. In this case, it means performing before the tree’s elements are rendered by the browser. In this case, it means performing an anonymous function that has one statement that associates a click event handler with an anonymous function that has one statement that associates a click event handler with an alert() to all div elements. Specifically, note the syntax $(), which is a jQuery function, an alert() to all div elements. Specifically, note the syntax $(), which is a jQuery function, which refers to a collection of elements in the DOM tree, and you can then perform a which refers to a collection of elements in the DOM tree, and you can then perform a JavaScript function on these items. In this case, the body part has only a single div element JavaScript function on these items. In this case, the body part has only a single div element and if you opens the document in the browser, the result is: and if you opens the document in the browser, the result is:
What is not very mysterious, but if you click on the text, you get a popup: What is not very mysterious, but if you click on the text, you get a popup:
The example shows two things. First of all, what is technically necessary to use jQuery, and The example shows two things. First of all, what is technically necessary to use jQuery, and second, what is the idea of jQuery, that is, in an easy way to select items in the DOM tree second, what is the idea of jQuery, that is, in an easy way to select items in the DOM tree and do something with them. The first goes quite easily and you simply copy the library and do something with them. The first goes quite easily and you simply copy the library to the project (in fact there is an option since multiple browser vendors make the library to the project (in fact there is an option since multiple browser vendors make the library available and you can just link to the current library). As for the other, it all builds on available and you can just link to the current library). As for the other, it all builds on the $() function, which is just an alias for jQuery(), and the above script block could be the $() function, which is just an alias for jQuery(), and the above script block could be written as follows: written as follows:
Download free eBooks at bookboon.com 157 157
JAVA 12: WWW AND DEVELOPMENT OF THE JAVA 12:PART: WWW AND DEVELOPMENT OF THE CLIENT SOFTWARE DEVELOPMENT JAVA 12:PART: WWWSOFTWARE AND DEVELOPMENT DEVELOPMENT OF THE THE CLIENT DEVELOPMENT JAVA 12: WWW AND OF CLIENT CLIENT PART: PART: SOFTWARE SOFTWARE DEVELOPMENT DEVELOPMENT
Appendix A: jQuery appendIx a: JQuery appendIx appendIx a: a: JQuery JQuery
(the project JQueryExample2). Viewed from the program, it does not matter what you (the (the project project JQueryExample2). JQueryExample2). Viewed Viewed from from the the program, program, itit it does does not not matter matter what what you you (the from does not what write,project but it JQueryExample2). is standard to writeViewed $(), what canthe be program, recommended. The usematter of jQuery isyou so write, but itit isis standard to write $(), what can be recommended. The use of jQuery isis so write, but standard to write $(), what can be recommended. The use of jQuery so write, but it is standard to write $(), what can be recommended. The use of jQuery is so widespread that most developers perceives $() as jQuery code. widespread that most developers perceives $() as jQuery code. widespread that most developers perceives $() as jQuery code. widespread that most developers perceives $() as jQuery code. A whole different thing is what you can use as an argument for the function $() and which AA A whole whole different different thing thing isis is what what you you can can use use as as an an argument argument for for the the function function $() $() and and which which whole different you can use argument for the $() and functions you canthing specify what should work on as theanelements (click() is function an example) andwhich here functions you can specify should work on the elements (click() isis an example) and here functions you can specify should work on the elements (click() an example) and here functions you can specify should work on the elements (click() is an example) and there are simply many options, a lot more than can be accommodated in this book so here it is there are simply many options, aaa lot more than can be accommodated in this book so itit there are simply many options, lot more than can be accommodated in this book so there are simply many options, lot more than can be accommodated in this book so it isis is necessary to read the documentation: necessary to read the documentation: necessary to read the documentation: necessary to read the documentation: http://www.tutorialspoint.com/jquery/jquery_tutorial.pdf http://www.tutorialspoint.com/jquery/jquery_tutorial.pdf http://www.tutorialspoint.com/jquery/jquery_tutorial.pdf
which provides an adequate and easily readable documentation. I would like to justify, with which provides provides an an adequate adequate and and easily easily readable readable documentation. documentation. I would would like like to to justify, justify, with with which provides an like to justify, with which a few examples of adequate what youand can easily with readable jQuery. documentation. II would few examples of what you can with jQuery. few examples examples of of what what you you can can with with jQuery. jQuery. aaa few Generally, the parameter of $() may be any selector corresponding to what is discussed Generally, the parameter of $() may be any selector corresponding to what discussed Generally, the parameter of $() $()Consider, may be be any any selector corresponding toHTML what isis is document discussed Generally, parameter of may what discussed in chapterthe 3 on style sheets. for selector example,corresponding the followingto in chapter chapter 33 3 on on style style sheets. sheets. Consider, Consider, for for example, example, the the following following HTML HTML document document in chapter on style sheets. Consider, for example, the following HTML document in (JQueryExample3): (JQueryExample3): (JQueryExample3): (JQueryExample3): html>