Sie sind auf Seite 1von 61

Project Training

Date:06.02.2018 Version: 1.0


SAP UI5 Project Training

1
Copyright © 2018. BluePrint Technologies. All rights reserved.
Document Statistics:
DOCUMENT IDENTIFICATION
The following is current information about the document: (Maintain all relevant section)

Object ID

Title SAP UI5 Project Training

Version 1.0

Level ID

Process Team

Area/Sub Module

Technical Contact

Author

SAP Version SAP System Version

Development Type

FSD Name

REVISION HISTORY
The following is a history log of revisions to the document:

Version Author Of Revision Creation Date Comments


First revision
Reference section number:
Name of the author of
1.0 MM-DD-YY Changes made under a section
the revision
Reference section number:
Changes made under a section

REVIEW , APPROVALS AND SIGN OFF


The following is a approval section for the document:

Name Role Signature Date


Technical Specification Design Owner 01-01-18
Offshore Development Coordinator MM-DD-YY
Offshore QA Reviewer MM-DD-YY
Development Lead MM-DD-YY

2
Copyright © 2018. BluePrint Technologies. All rights reserved.
Table of Contents

TABLE OF CONTENTS ................................................................................................. 3


1.0 INTRODUCTION TO HTML5 ................................................................................... 4
1.1 HTML 5 new Features ..................................................................................................................4
1.2 Browser Support and Editors .....................................................................................................4
1.3 Basic Framework.........................................................................................................................5
1.4 HTML Elements ...........................................................................................................................5
1.5 HTML Attributes ..........................................................................................................................6
1.6 Displaying an HTML document...................................................................................................7
1.7 Adding comments to HTML ........................................................................................................8
1.8 Making your HTML code readable ..............................................................................................9
2.0 INTRODUCTION TO CSS3 ................................................................................... 11
2.1 CSS3 modules ............................................................................................................................... 11
2.2 CSS Boders ............................................................................................................................... 13
2.3 Multi Background ........................................................................................................................... 15
2.4 CSS3 Colors .............................................................................................................................. 16
2.5 CSS Gradients ............................................................................................................................... 17
2.6 CSS - Validations ............................................................................................................................ 17
3.0 INTRODUCTION TO JAVASCRIPT ...................................................................... 18
3.1 Where JavaScript is used ......................................................................................................... 18
3.2 JavaScript history ..................................................................................................................... 18
3.3 Basics of JavaScript ................................................................................................................. 19
3.4 Data types .................................................................................................................................. 22
3.5 Working with variables ............................................................................................................. 24
3.6 Operators in JavaScript ............................................................................................................ 27
3.7 Working with loops ................................................................................................................... 31
3.8 Creating JavaScript functions .................................................................................................. 34
4.0 INTRODUCTION TO SAPUI5 ................................................................................ 39
4.1 Versioning ................................................................................................................................. 39
4.2 SAPUI5 Architecture Overview ................................................................................................. 40
4.3 Model View Controller ............................................................................................................... 41
4.4 Controls and Libraries .............................................................................................................. 42
4.5 Types of Views, Model, Bindings ............................................................................................. 44
5.0 INTRODUCTION TO SAPUI5 CONTROLS AND API ........................................... 46
5.1 Controls in SAP UI5: ................................................................................................................. 46
5.2 API Reference: ........................................................................................................................... 48
6.0 EXERCISES ........................................................................................................... 49
6.1 SAP HCP URL ............................................................................................................................ 49
6.2 WEB IDE Configuration ............................................................................................................. 50
6.3 Configuring ODATA Services in Web IDE ................................................................................ 53
6.4 Creating a sample project in Web IDE ...................................................................................... 56
7.0 DO’S AND DON’TS ............................................................................................... 61
7.1 JavaScript Code Issues ............................................................................................................ 61
7.2 CSS Styling Issues .................................................................................................................... 61
7.3 Performance Issues .................................................................................................................. 61

3
Copyright © 2018. BluePrint Technologies. All rights reserved.
1.0 Introduction to HTML5
HTML5 is the next major revision of the HTML standard superseding HTML 4.01, XHTML 1.0,
and XHTML 1.1. HTML5 is a standard for structuring and presenting content on the World Wide
Web.HTML5 is a cooperation between the World Wide Web Consortium (W3C) and the Web.
Hypertext Application Technology Working Group (WHATWG).The new standard incorporates
features like video playback and drag-and-drop that have been previously dependent on third-party
browser plug-ins such as Adobe Flash, Microsoft Silverlight, and Google Gears.

1.1 HTML 5 new Features


 New Semantic Elements:
o These are like <header>, <footer>, and <section>.
 Forms 2.0:
o Improvements to HTML web forms where new attributes have been introduced for <input>
tag.
 Persistent Local Storage:
o To achieve without resorting to third-party plugins.
 Web Socket:
o A next-generation bidirectional communication technology for web applications.
 Server-Sent Events:
o HTML5 introduces events, which flow from web server to the web browsers, and they are
called Server-Sent Events (SSE).
 Canvas:
o This supports a two-dimensional drawing surface that you can program with JavaScript.
 Audio & Video:
o You can embed audio or video on your webpages without resorting to third-party plugins.
 Geolocation:
o Now visitors can choose to share their physical location with your web application.
 Microdata:
o This lets you create your own vocabularies beyond HTML5 and extend your web pages
with custom semantics.
 Drag and drop:
o Drag and drop the items from one location to another location on the same webpage.
1.2 Browser Support and Editors
The latest versions of Apple Safari, Google Chrome, Mozilla Firefox, and Opera all support
many HTML5 features and Internet Explorer 9.0 will also have support for some HTML5 functionality.
The mobile web browsers that come pre-installed on iPhones, iPads, and Android phones all have
excellent support for HTML5.
We need only notepad for creating html files in windows systems and the one equivalent in
Mac is Text Edit.

4
Copyright © 2018. BluePrint Technologies. All rights reserved.
1.3 Basic Framework
An HTML document has two main parts:
 Head.
o The head element contains title and Meta data of a web document.
 Body.
o The body element contains the information that you want to display on a web page.
In a web page, the first tag (specifically, <html>) indicates the markup language that is being
used for the document. The <head> tag contains information about the web page. Lastly, the content
appears in the <body> tag.

Figure 1.3 Pictorial representation of HTML Program

1.4 HTML Elements


In HTML, an element refers to two different things:

 Element of structure of a document (for example, paragraph, web page title, etc.).
 element in the sense of a tag (for example, <p>, <title>)
 Because of the different meanings of the word "element", it can be confusing what the word
"element" means in a particular context. The following discussion may help you to understand
the differences in the meaning. When we talk about the element in the sense of element of
structure of a document, we are referring to the structure of the document; for example,
document's header information (head), title, body, etc. When, however, we use the word
element to refer to a tag, we are talking about a specific HTML instruction that uses angled
brackets like <>. As the following table shows,

5
Copyright © 2018. BluePrint Technologies. All rights reserved.
Table 1.4 Element Representation in different ways

Examples of elements of structure of a document head Body p


Examples of elements as tags <head> <body> <p>

An element becomes a tag when we use the angled brackets around it. To create a web page, we use
tags. A tag instructs the browser what specific instruction to execute. Assume in your web page you
want to emphasize some text as bold. To do this, HTML requires three pieces of information from you:

 With what tag do you want to emphasize the text? (Answer to this question determines
what and where a specific HTML instruction will begin. In other words, this starts an HTML
instruction.)
 What text do you want to make bold?
 Where do you want to stop the instruction? (An instruction should be ended with the same
tag that started the instruction. See below.)
So how would be write the necessary markup? Begin by answering to the three questions listed above.
Here are the answers to each corresponding question:

 We will use the <b> tag. Think of this as turning ON the bold feature in HTML.
 We want to display "World Wide Web Consortium" as bold. Remember this text must be
immediately following the <b> tag.
 Stop the instruction with </b> tag. This will turn OFF the bold feature of HTML.
So our HTML markup will become:
The <b>World Wide Web Consortium</b> (W3C) is a rule-making body for the Web.

Important Points
 Every element has a name such as head, title, p, b, and I.
 A tag is the element name surrounded by the angled brackets. This refers to a start tag
such as <p>, <title>, and <i>. A start tag starts a particular HTML instruction.
 An end tag is the same as a start tag except the end tag has a forward slash between the
< and the element name. An end tag stops a particular HTML instruction.
 Most elements have content, which is placed between the start and the end tags. Example,
this is <b>bold</b>.
 Some elements have no content. Such elements/tags are known as empty tags.
 Some elements have no end tags. These are referred to as one-sided tags. A tag that has
an opening and closing tag is referred to as two-sided tag.

1.5 HTML Attributes


In HTML, elements (or tags) have attributes or properties. As an HTML writer, attributes allow
you to add extra instruction to your tags. Because each tag has its own unique attributes, you have to
learn which attribute(s) belongs which tag.
An attribute has two parts: attribute name and attribute value. Because of these two-parts, they are
also referred to as pairs. The attribute name identifies (or defines) what special instruction you want
to add to a particular tag. The attribute value, on the other hand, indicates (usually predefined) option

6
Copyright © 2018. BluePrint Technologies. All rights reserved.
for that attribute. Therefore, if you are going to use an attribute, you will need to have value for that
attribute.
Let us go over the actual HTML, for example
Align="right" is an example of attribute-value pair. The word align is the attribute. The value of this
attribute is right. A value of an attribute is enclosed in double quotation marks.
The following shows the HTML code for the top paragraph:
<p align="right">This is my paragraph. Normally, text and other object on a web page are left-aligned.
Because this paragraph has an extra instruction (align="right") to start this particular paragraph from
the right, the paragraph is right-aligned.</p>

Keep the following points in mind while working with attributes:

 Some attributes have predefined values. For example, for the align attribute, possible
values include, left, center, justify and right. So if you use the align attribute, you should
use one of these acceptable values.
 Some attributes accept numerical values. For instance, for the width attribute, you can
specify a numerical value such as 5 (which indicates 5 pixels), or 20% (which indicates
20% of the screen width).
Main points to remember for attributes:

 Attributes are specific to tag names. For example, for the <p> tag, you can use the align
attribute but not the width attribute. The width attribute can only be used with tags such as
<table>, <td>, and <img>.
 Attributes have values. Make sure to use the correct value for the correct attribute. For
instance, you should not use colour="20", or align="brown"; instead use, color="red", and
align="justify".
 Attribute values needs to be enclosed in double quotation marks. This is true especially if
the value contains one or more spaces, for example, face="Times New Roman".
 Attribute values could come from a predefined list (such as color names red, green, blue,
etc.) or from you (width of a table 50% or 800 pixels.)

1.6 Displaying an HTML document


After creating or as you create your web page, you should view your page at least one browser
to detect any errors. If your webpage does not look the way you expect, then, you should make the
necessary changes to correct any problem.

Figure 2 A simple web page with basic tags

7
Copyright © 2018. BluePrint Technologies. All rights reserved.
As the web page shows, the content of the title tag is displayed on the top of the web page in
the blue bar of Internet Explorer. If you wanted to have "My First Web Page" appear in the title bar,
your title tag will look like :
<title>My First Web Page</title>

Next, figure 1 shows the location of the web page. The address box shows the web page is located at
"C:\HTMLExamples\basic-page.htm". But why is it important to know where a web page is located?
So you can view the web page in a browser. In this example, the webpage is saved to a local C drive
in the HTML Examples folder. To access the web page, first you would open the c drive and then the
HTML examples folder. Finally, you will click on the web page file you want to open.
Finally, the web page shows the content that is placed inside the body tag. Suppose you want to
display the following text (with a white background) on a web page:
Before a webpage can be viewed in a browser, it must be saved.
To display that text your body tag will look something like this:

<body>Before a webpage can be viewed in a browser, it must be saved.</body>


In summary, the title tag contains the title information of a web page. The body tag contains the content
of the web page. Once a web page is saved, it can be viewed by double-clicking on the web page file.
Alternatively, you can type the location of the web page in the address box.

1.7 Adding comments to HTML


As you first start working with HTML, you may start by adding comments to every single
line to remind you of what the code does. As you develop more experience and gather more
knowledge about HTML, you will learn to comment only major parts of your web page. You may,
for example, comment the width of nested tables you are using in your web page:

Figure 3Adding Comments

In HTML, a comment begins with <!-- and ends with -->. Any text you place after <!-- is comment.
Browsers ignore comment text.

8
Copyright © 2018. BluePrint Technologies. All rights reserved.
Example of a single line comment:
<!--This is a small comment-->
Example of a multi-line comment:

<!--This comment is long. It is displayed on more than one line. Adding multi-line comments in HTML
is easy as adding a single line comment. Whether the comment is single line or multi-line, it starts
with <-- and ends with -->-->.
Important points about comments:

 Use comments as a reference guide. Avoid use of excessive comments.

 Add comments to major parts of your code; or for parts, that you are unsure of.

 Use of comments is a great way to communicate with other people working on the same
web page.

 Start your comment with <-- and end with -->

 Browsers and search engines ignore comments.

1.8 Making your HTML code readable


If you do not use space effectively in your HTML code, your code may look as:
<!DOCTYPE html><html><body><section><h1>WWF</h1><p>The World Wide Fund for Nature
(WWF) is an international organization working on issues regarding the conservation, research and
restoration of the environment, formerly named the World Wildlife Fund. WWF was founded in
1961.</p></section><section><h1>WWF's Panda symbol</h1><p>The Panda has become the
symbol of WWF. The well-known panda logo of WWF originated from a panda named Chi Chi that
was transferred from the Beijing Zoo to the London Zoo in the same year of the establishment of
WWF.</p></section></body></html>

Reading and understanding this code is difficult because it is so disorganaized. Becuase extra
white space is ignored by the browsers, you can use that to your advantage to orgnaize your code.
Use of white space to seperate tags helps you better understand and maintain your pages. The
following shows the updated code with the approriate amount of space:

<!DOCTYPE html>
<html>
<body>
<section>

<h1>WWF</h1>
<p>The World Wide Fund for Nature (WWF) is an international organization working on issues
regarding the conservation, research and restoration of the environment, formerly named the World
Wildlife Fund. WWF was founded in 1961.</p>
</section>

9
Copyright © 2018. BluePrint Technologies. All rights reserved.
<section>
<h1>WWF's Panda symbol</h1>
<p>The Panda has become the symbol of WWF. The well-known panda logo of WWF originated
from a panda named Chi Chi that was transferred from the Beijing Zoo to the London Zoo in the same
year of the establishment of WWF.</p>
</section>
</body>
</html>

Reference:1 https://www.w3schools.com/html/default.asp
Reference 2 http://www.scriptingmaster.com/html/html.asp

10
Copyright © 2018. BluePrint Technologies. All rights reserved.
2.0 Introduction to CSS3
Cascading Style Sheets (CSS) is a style sheet language used for describing the look and
formatting of a document written in a markup language.CSS3 is a latest standard of css earlier
versions (CSS2).The main difference between css2 and css3 is follows

 Media Queries
 Namespaces
 Selectors Level 3
 Color
2.1 CSS3 modules
CSS3 is collaboration of CSS2 specifications and new specifications, we can called this
collaboration is module. Some of the modules are shown below

 Selectors
 Box Model
 Backgrounds
 Image Values and Replaced Content
 Text Effects
 2D Transformations
 3D Transformations
 Animations
 Multiple Column Layout
 User Interface

CSS3 Rounded corners are used to add special colored corner to body or text by using the
border-radius property.A simple syntax of rounded corners is as follows –

#rcorners7 {

border-radius: 60px/15px;

background: #FF0000;

padding: 20px;

width: 200px;

height: 150px;

11
Copyright © 2018. BluePrint Technologies. All rights reserved.
The following table shows the possible values for Rounded corners as follows
Table 2CSS options for rounded corner

Values Description

border-radius Use this element for setting four boarder radius


property

border-top-left-radius Use this element for setting the boarder of top left
corner

border-top-right-radius Use this element for setting the boarder of top right
corner

border-bottom-right- Use this element for setting the boarder of bottom


radius right corner

border-bottom-left- Use this element for setting the boarder of bottom


radius left corner

Let’s consider the following example of how we can use css in html
<html>
<head>

<style>
#rcorners1 {
border-radius: 25px;
background: #8AC007;

padding: 20px;
width: 200px;
height: 150px;
}

#rcorners2 {
border-radius: 25px;
border: 2px solid #8AC007;
padding: 20px;

width: 200px;
height: 150px;
}

12
Copyright © 2018. BluePrint Technologies. All rights reserved.
</style>
</head>
<body>

<p id="rcorners1">Rounded corners!</p>


<p id="rcorners2">Rounded corners!</p>
</body>
</html>

The above snippet gives an output as follows

Figure 4 Output of the css program 1

2.2 CSS Boders


CSS Border image property is used to add image boarder to some elements. You do not need
to use any HTML code to call boarder image. A sample syntax of boarder image is as follows

#borderimg {

border: 10px solid transparent; padding: 15px;}

13
Copyright © 2018. BluePrint Technologies. All rights reserved.
The most commonly used values are shown below −
Values Description
border-image-source Used to set the image path
border-image-slice Used to slice the boarder image
border-image-width Used to set the boarder image width
border-image-repeat Used to set the boarder image as rounded, repeated
and stretched

Example

<html>

<head>

<style>

#borderimg1 {

border: 10px solid transparent;

padding: 15px;

border-image-source: url(/css/images/border.png);

border-image-repeat: round;

border-image-slice: 30;

border-image-width: 10px;

</style>

</head>

<body>

<p id="borderimg1">This is image boarder example.</p>

<p id="borderimg2">This is image boarder example.</p>

14
Copyright © 2018. BluePrint Technologies. All rights reserved.
<p id="borderimg3">This is image boarder example.</p>

</body>

</html>

It will produce the following result

Figure 5 Output of CSS Program 2

2.3 Multi Background


CSS Multi background property is used to add one or more images at a time without HTML
code.
#multibackground {
background-image: url(/css/images/logo.png), url(/css/images/border.png);
background-position: left top, left top;
background-repeat: no-repeat, repeat;
padding: 75px;
}
The most commonly used values are shown below −

Values Description

background Used to setting all the background image properties in


one section

background-clip Used to declare the painting area of the background

background- Used to specify the background image


image

background- Used to specify position of the background images


origin

background-size Used to specify size of the background images

15
Copyright © 2018. BluePrint Technologies. All rights reserved.
Multi background Size
Multi background property is accepted to add different sizes for different images. A sample
syntax is as shown below −
#multibackground {
background: url(/css/imalges/logo.png) left top no-repeat, url(/css/images/boarder.png) right
bottom no-repeat, url(/css/images/css.gif) left top repeat;
background-size: 50px, 130px, auto;
}

As shown above an example, each image is having specific sizes as 50px, 130px and auto size.

2.4 CSS3 Colors


CSS3 has supported additional color properties as follows −

 RGBA color
 HSL color
 HSLA color
 Opacity

RGBA stands for Red Green Blue Alpha. It is an extension of CSS2,Alpha specifies the opacity of
a color and parameter number is a numerical between 0.0 to 1.0. A Sample syntax of RGBA as
shown below −

#d1 {background-color: rgba (255, 0, 0, 0.5) ;}

#d2 {background-color: rgba (0, 255, 0, 0.5) ;}

#d3 {background-color: rgba (0, 0, 255, 0.5) ;}

HSL stands for hue, saturation, lightness. Here Huge is a degree on the color wheel, saturation
and lightness are percentage values between 0 to 100%. A Sample syntax of HSL as shown below −

#g1 {background-color: hsl (120, 100%, 50%) ;}

#g2 {background-color: hsl (120, 100%, 75%) ;}

#g3 {background-color: hsl (120, 100%, 25%) ;}

HSLA stands for hue, saturation, lightness and alpha. Alpha value specifies the opacity as shown
RGBA. A Sample syntax of HSLA as shown below −

#g1 {background-color: hsla (120, 100%, 50%, 0.3) ;}

#g2 {background-color: hsla (120, 100%, 75%, 0.3) ;}

16
Copyright © 2018. BluePrint Technologies. All rights reserved.
#g3 {background-color: hsla (120, 100%, 25%, 0.3) ;}

Opacity is a thinner paints need black added to increase opacity. A sample syntax of opacity is as
shown below −

#g1 {background-color: rgb (255, 0, 0); opacity: 0.6 ;}

#g2 {background-color: rgb (0, 255, 0); opacity: 0.6 ;}

#g3 {background-color: rgb (0, 0,255); opacity: 0.6 ;}

2.5 CSS Gradients


Gradients displays the combination of two or more colors.But these gradients are dependent on the
browser we use
background: -webkit-linear-gradient(90deg, #780206 10%, #061161 90%); /* Chrome 10+, Saf5.1+*/
background:-moz-linear-gradient(90deg, #780206 10%, #061161 90%); /* FF3.6+ */
background:-ms-linear-gradient(90deg, #780206 10%, #061161 90%); /* IE10 */
background:-o-linear-gradient(90deg, #780206 10%, #061161 90%); /* Opera 11.10+ */
background:linear-gradient(90deg, #780206 10%, #061161 90%); /* W3C */

2.6 CSS - Validations


Validation is the process of checking something against a rule. A CSS validator checks your
Cascading Style Sheets to make sure that they comply with the CSS standards set by the W3
Consortium. There are a few validators, which will also tell you which CSS features are supported by
which browsers (since not all browsers are equal in their CSS implementation).
You can use the following tools to check the validity of your CSS.

W3C CSS Validator (World Wide Web Consortium).


This validator checks your css by either file upload, direct input, or using URI - one page at
a time. This validator helps you to locate all the errors in your CSS. - http://jigsaw.w3.org/css-validator/

WDG CSS check validator


The WDG CSS check validator, lets you validate your css by direct input, file upload, and
using URI. Line and column numbers will list errors if you have any. Errors usually come with links to
explain the reason of error. http://www.htmlhelp.com/tools/csscheck/

Reasons to validate
There are a number of reasons why you should validate your code. However, major ones are as
follows

 It Helps Cross-Browser, Cross-Platform, and Future Compatibility.


 A good quality website increases search engine visibility.
 Professionalism: As a web developer, your code should not raise errors while seen by
the visitors.

Reference1 : https://www.w3schools.com/css/

Reference 2: https://www.quackit.com/css/

17
Copyright © 2018. BluePrint Technologies. All rights reserved.
3.0 Introduction to JavaScript
JavaScript is an object-based scripting language that is lightweight and cross-platform.
JavaScript is not compiled but translated. The JavaScript Translator (embedded in browser) is
responsible to translate the JavaScript code.

3.1 Where JavaScript is used

JavaScript can be used to create interactive websites. It is mainly used for,

 Client-side validation
 Dynamic drop-down menus
 Displaying data and time
 Displaying popup windows and dialog boxes (like alert dialog box, confirm dialog box and prompt
dialog box)
 Displaying clocks etc.

3.2 JavaScript history


Netscape released a scripting language called Live Script in its early beta release of Navigator
2.0 in 1995. Netscape decided to rename the language as JavaScript to make it sounded like the hot
Java programming language. Below table 3 shows a simple comparison of java and JavaScript

Table 3Comparison of JavaScript and Java

JavaScript Java
Easy to learn and use Complicated to learn and use
Useful for simple tasks Useful for complex tasks
No developer's kit required Requires Java Developer Kit to create applets
JavaScript code is written directly in HTML Java programs are saved in separate files and
and it does not require compiling must be compiled before they can be run
After Netscape introduced JavaScript in 1995, Microsoft introduced its own form of JavaScript
called JScript for its browser: Internet Explorer. As time progressed, major browser vendors included
support for different brands of JavaScript. Table 4 lists different versions of JavaScript and how
Netscape and Internet Explorer support them.

Table 4 Javascript Versions

JavaScript Version Description


JavaScript 1.0 This is the first version of JavaScript and Netscape 2.0 and Internet
Explorer 3.0 support it.
JavaScript 1.1 This version was introduced in Netscape 3.0 but only some parts were
implemented in Internet Explorer 3.0.
JavaScript 1.2 Supported by both Netscape 4.0 and Internet Explorer 4.0.
JavaScript 1.3 Introduced in Netscape 4.06 and is supported by Internet Explorer 4.0
and above.

18
Copyright © 2018. BluePrint Technologies. All rights reserved.
3.3 Basics of JavaScript
If you already are not aware, with HTML you can only create static web pages. A static web
page simply is a page whose content or layout will not change. A dynamic page, on the other hand, is
interactive and whose content changes according to the scripting instructions specified. To create a
dynamic web page, you simply write a small program using a web programming language like Active
Server Pages, JavaScript, Perl, PHP, etc.

3.3.1 Server-side and client-side Scripting


The programs or scripting instruction that run on the server is referred to as server-side
scripting. Active Server Pages is an example of a server-side technology, which runs on a Windows
server. The main advantage of using a server-side language is that the scripting code remains and
runs on the server. One of the main disadvantages of using a server-side technology is that server
slows down as many users access resources from the server. To combat that problem and other
server-side scripting problems, use of client-side scripting is preferred. JavaScript is a popular client-
side scripting language. Client-side scripts run on the client's computer thus are more responsive to
user's actions than a server-side script, as the data does not have to be sent over the internet.

JavaScript code is placed between the <script> and </script> tags. In addition, the JavaScript
code inside the <script> tag can be placed directly in an HTML document. You may also link external
JavaScript files to an HTML document. By doing that, you can share your JavaScript across multiple
web pages.

3.3.2 Whitespace in JavaScript


A whitespace character is an empty space (without any visual representation) on screen.
Examples of whitespace characters include space characters, tabs, and line break characters. In
JavaScript, use of excessive whitespace is ignored. For instance, the following JavaScript code,
a = b * d - c;
Is equivalent to
a = b * d - c;

Thus, both statements would be interpreted the same way. You might be asking be yourself
why is whitespace important? Because whitespace is ignored in JavaScript, you can use it to benefit
yourself by writing code that is more readable and understandable. The importance of whitespace
though may not be realized in a smaller program. Suppose you had the following JavaScript code:

If (a > b) {document.write ("a is greater than b.") ;} else {document.write ("a is not greater than b"); }
As a programmer, the above code may be harder for you to follow but for the computer (specifically
the interpreter) it is more beneficial as much of the unnecessary space characters are eliminated. In

19
Copyright © 2018. BluePrint Technologies. All rights reserved.
the following code, however, we use reasonable amount of space for readability and understand
ability:
If (a > b)
{
document.write ("a is greater than b.");
}
else
{
document.write ("a is not greater than b");
}
From our above discussion, do not assume JavaScript ignores all excessive whitespace. The
exception is to our rule is use of whitespace in strings. In strings, whitespace is preserved, as in:
var AString = "Thisis a string";

3.3.3 Statements in JavaScript


A statement is an instruction that instructs a computer (JavaScript interpreter) to carry a
specific action. For example,
document.write ("This is a JavaScript statement.");
Instructs the computer to print, "This is a JavaScript statement." In JavaScript, statements are
terminated with a semicolon or return statement. Because statements in JavaScript are ended with a
semicolon, multiple statements can be grouped on one line, for example:
var x; x = 60; document.write (x);

In JavaScript, statements can also be terminated with a line break character, for example,
var x
x = 60
document.write (x)
The above three lines are treated as three separate statements as:

var x;
x = 60;
document.write (x);
To avoid ambiguity and any unintended results, use a semicolon to mark end of a statement instead
of relying on an implicit semicolon insertion (or a linebreak character).

3.3.4 Case sensitivity in JavaScript


JavaScript is a case-sensitive scripting language. What that means is that the language
considers capital letters as different from their lowercase counterparts. For example, if you declare a
variable called totalCost in JavaScript, you have to use totalCost to refer to that variable not TotalCost,
TOTALCOST, or some other combination.

In JavaScript the case sensitivity does not just apply to variable names but also to JavaScript
keywords, event handlers, and object properties or methods. Keywords in JavaScript are all
lowercase, for example, while, for, if, else, and so on. On the other hand, methods (properties) use

20
Copyright © 2018. BluePrint Technologies. All rights reserved.
"camel-back" naming convention (first word is in lowercase and each successive first letter of each
word is capitalized), for example, toArray(), lastModified(), and so on.

3.3.5 Code blocks in JavaScript


A code block simply consists of grouped statements with curly braces ({ }). For example,
statements grouped in a loop is referred to as a code block:
Consider the following snippet as follows

counter=0;
while(counter<10)
{
documents.write(“counter=”+ counter + “<br>”);

counter++
}
A code block can also be created with statements grouped in a condition:
if(counter == 15)

{
break
}
Finally statements grouped in a function also create a code block:

function Count(counter)
{
counter=counter+1;
return counter;

3.3.6 Running JavaScript


The browser is responsible for running JavaScript. Thus, the output from JavaScript is going
to be more responsive as the data does not need to travel to or from server. A web browser runs
JavaScript when a web page is downloaded or in response to an event.
JavaScript code can be placed in either an HTML file or an external file. So how do you decide
where do you place your code? If your JavaScript code is small and cannot be used in any other web
page, then, you should consider placing your code directly in the HTML document that uses it. If, on
the other hand, your JavaScript is long and/or used very by many HTML documents, then, you should
create a separate JavaScript file.

Because you can insert JavaScript code inside an HTML file, it needs to be distinguished from
the rest of the text or code on the page. To separate your JavaScript commands from HTML

21
Copyright © 2018. BluePrint Technologies. All rights reserved.
commands or regular text on the page, insert your JavaScript code inside the opening <script> and
closing </script> tag. For example,
<script language="JavaScript">JavaScript commands</script>
Because there are different client-side languages, we need to indicate to the browser which
language we are using in our scripts. To indicate the scripting language, we added the language
attribute to the <script> tag. Since we are using JavaScript, we set the language tag to JavaScript. If
you omit the language tag from your <script> tag, the browser will assume that your code is written in
JavaScript.

If you place your scripting code outside of the HTML page, you still use the <script> tag but
then just add the src attribute. The value of src attribute tells the browser where your JavaScript code
is located. For instance,
<script language="JavaScript" src="JavaScript/displayDate.js"></script>

Indicates that we are using JavaScript language and the JavaScript commands are located in a folder
called JavaScript and a file called displayDate.js. A ".js" file extension indicates a JavaScript file.

3.4 Data types


Every variable has a data type. Data type indicates what kind of data the variable holds. In
JavaScript, the type of data variable hold has been grouped into two categories:

 primitive types

 composite types

3.4.1 Primitive types in JavaScript


JavaScript supports five primitive data types:

 numbers
 strings
 Booleans
 undefined and null

Numbers
As the name implies, a number type refers to numerical values. Numbers can be divided into two
groups:
 floating-point — are fractional numbers such as 2.45, -3.58, and .97

 Integers — are whole numbers such as 245, -480, and 3.

Strings
A string type refers to one or more characters of text. In JavaScript, a string is enclosed inside
single or double quotes. The following, for example, represents an invalid string:
"This is not a valid string.'
“This is a valid string”

Boolean

22
Copyright © 2018. BluePrint Technologies. All rights reserved.
In JavaScript, Boolean logic allows your program to make decisions. A Boolean logic
statement consists of a condition that evaluates to either true or false. You can think of the condition as
a question that has one of two possible answers:

 yes or no,
 ON or OFF, or
 positive or negative
 true or false

Figure 6an example of Boolean logic

Undefined and null types


Undefined type
The undefined type refers to those variables or object properties that are either undefined or
do not exist. When a variable, for example, is declared without assigning a value to it, it is of
undefined type. So
var iAge;

declares a variable called iAge. Its type is undefined; it can be confirmed by simply outputting its
type using the typeof operator:

alert ("iAge is of type: " + typeof(iAge));


So our output will show that iAge is of type undefined:

So as long as no value is assigned to a variable, its type is undefined. Once a value is assigned, it
will no longer be of type undefined but rather one of other types supported in JavaScript: numbers,
strings, Boolean, or Null.

23
Copyright © 2018. BluePrint Technologies. All rights reserved.
Null type
The null type indicates an empty value. When a variable is assigned the value null, its type
becomes null. A null type variable is a placeholder that represents nothing. The following shows an
example of a variable of type null:

var iAge = null;


Since null is an empty object, its type is object. We can confirm this by using the typeof operator:
alert ("iAge is of type: " + typeof(iAge));
That will output:

From these basic data types, more complex data type (also known as composite types) is
derived. Although JavaScript supports five primitive data types, we actually use only numbers, strings,
and Booleans to store data. The undefined and null types arise under certain circumstances in
programming.

3.4.2 Composite types in JavaScript


From primitive types mentioned above, we can derive composite types. A composite type can
consist of numbers, strings, Booleans, undefined and null values. The three types of composite types
available in JavaScript are objects, arrays, and functions.

3.5 Working with variables


A variable is a named element used to store and retrieve information. With variables, we can
store information in one part of the program, and access information from that variable in another
part of the program.
Like many other programming languages, JavaScript has variables. You can think of variables as
empty containers. You can place data into those containers and then use (or refer to) those contains
by their name.

3.5.1 Declaring variables in JavaScript


Before you use a variable, you should declare (create) it. The process of creating a variable is
also known as declaring a variable. When you declare a variable, you tell the computer to reserve
some memory for your program to store some data. To declare a variable in JavaScript, use the var
command. For instance, the following command creates a variable
var age;

called age. With the above command, computer will reserve some memory and allow you to store to
or retrieve from that memory with the name you chose, age. Remember at this point our variable aegis
null or has a garbage value–whatever computer's memory slot happens to hold.

24
Copyright © 2018. BluePrint Technologies. All rights reserved.
You can declare more than one variable by separating each with a comma and still use one var
command, as:
var state, city, zip, country;
When you declare a variable, keep the following JavaScript restrictions in mind to a variable name:

 A variable name cannot be one of the reserved words in JavaScript. Examples of reserved words
in JavaScript include var, or document.write. Reserved words have a specific purpose in
JavaScript; they cannot be used as a variable name.

 The first letter of a variable name must be a letter or an underscore (_). Age, year, _month are all
valid variable names. However, 11month, 9_ are not valid variable names.

 A variable name cannot contain any space characters. If your variable consists of more than one
word, separate each word with a underscore (i.e., first_name, last_name) or make the first letter
of each word a capital letter (i.e., FirstName, LastName).

3.6.2 Declaring variable without var command


As noted above, to explicitly declare (create) a variable in JavaScript we use the var command.
In JavaScript, however, you can also declare variables implicitly by using the assignment operator to
assign a value to the new variable. For example,
age = 50;
Declares a variable called age and signs he integer value 50 to this variable.
The following shows some more examples of variables being created when a value is assigned to a
variable:
<script language="javascript">

sum = x = y = 0; // declares three variables and each is set to 0.


</script>
Alternatively, you may declare and assign the values using the var command:
<script language="javascript">

var sum, x, y; // declares multiple variable with the var command.


sum = x = y = 0; // sets each variable to 0
</script>
Therefore, after reviewing the examples above you might be wondering what approach you should
take to create variables.

3.5.2 Assigning values to variables


After you declare a variable, you can assign a value to a variable. Assigning a value to a
variable means storing a value to a variable. To assign a value, use the equal sign:

var age;
age = 55;

25
Copyright © 2018. BluePrint Technologies. All rights reserved.
The first line declares a variable called age. The second line stores the number 55 to our variable age.
If you want, you could also combine those two lines, as:
age = 55;
In this one line above, we declare a variable called age when we assign the value 55. In this case, the
value is declared implicitly; to explicitly declare a variable, use the command var before a variable
name.
Consider the following example:

<script language="javascript">
var fName, age;
fName = "John";
age = 23;
document.write (fName);
document.write ("is");
document.write (age);
</script>
The following shows the output of the above code.
Johnis23

To print "Johnis23" as "John is 23", simply add a space character around the word "is", as
<script language="javascript">
var fName, age;
fName = "John";
age = 23;
document.write (fName);
document.write (" is ");
document.write (age);
</script>
That will print:
John is 23

We could simplify our code to these fewer lines:


<script language="javascript">
fName = "John";
age = 23;
document.write (fName + " is " + age);
</script>
Lines 2 and 3 each declare and assign a value. On line 4, we combine the output with the plus symbol.
The output is the same as shown before:
John is 23

26
Copyright © 2018. BluePrint Technologies. All rights reserved.
3.6 Operators in JavaScript
An operator is a method implemented to replace, modify or combine values represented by
variables. With operators, we can evaluate expressions–JavaScript commands that assign values to
variables. In the following expression,
totalAmountDue = totalBeforeTax + (totalBeforeTax * .05);
=, +, * are operators. An expression, as shown above, always has an assignment operator (= sign).
An expression can also contain other operators (like +, *, -, /, etc.).
We have five types of operators and they are as follows,

 Arithmetic operators

 Assignment operators

 Conditional statements

o Comparison operators (also called relational operators)

o Logical operators

3.6.1 Arithmetic Operators


We have two types of arithmetic operators and they are,
 Binary – those operators that work on elements in an expression.

 Unary – those operators that work on only one element or variable.


Table 5Binary arithmetic operators in JavaScript

Operator Name Description Example


+ Addition Adds two var webPages = 100;
operator values together. var images = 25;
In JavaScript, var TotalFiles = webPages + images;
this operator is var message = "Hello " + "Sam";
also used to
combine two
elements.
- Subtraction Subtracts one var totalAmount = 100;
operator value from var discount = 3.50;
another. var totalAmountDue = totalAmount - discount;
/ Division Divides one var totalCost = 300;
operator value by var numOfItems = 7;
another var averagePricePerItem = totalCost /
numOfItems
* Multiplication Multiples two var pricePerItem = 5.50;
operator values together var quantityPurchased = 40;
var totalPurchaseCost = pricePerItem *
quantityPurchased;
% Modulus Determines the var result = 5 % 2;
operator remainder after
dividing one
value by
another

27
Copyright © 2018. BluePrint Technologies. All rights reserved.
Table 6Unary Arithmetic operators in JavaScript

Operator Operator Name Description Example


++ Increment operator Increases a value by 1 a = 10;
b = a++;
-- Decrement operator Decreases a value by 1 a = 10;
b = a--;
- Negation operator Changes the sign of a value a = -10;
b = -a;

3.6.2 Assignment Operators


Expressions use assignment operator (= sign) to assign values. JavaScript supports other
assignment operators that we can use to assign values to a variable. Those other assignment
operators can assign a value in single operation instead of two. If you have worked in a programming
language like C++, they should be familiar to you. The following, for instance,
var x = 5;
var y = 15;
x += y;
Table 7 Summary of assignment operators

Operator Description Example Equivalent to


= Assigns the value of a variable on the right hand side a = b; a = b;
(of the =) to the variable on the left of = operator.
+= Adds two variables and assigns the result to a variable a += b; a = a + b;
on the left (of +=).
-= Subtracts two variables and assigns the result to a a -= b; a = a - b;
variable on the left (of -=).
/= Divides the variable on the left (of /=) by the variable a /= b; a = a / b;
on the right (of /=) and assigns the result to the variable
on the left.
*= Multiples the variable on the left (of *=) by the variable a *= b; a = a * b;
on the right (of *=) and assigns the result to the variable
on the left.
%= Divides the variable on the left (of %=) by the variable a %= b; a = a % b;
on the right (of %=) and assigns the remainder to the
variable on the left.

3.6.3 Conditional Statements

Very often, when you write code, you want to perform different actions for different decisions.

You can use conditional statements in your code to do this.

28
Copyright © 2018. BluePrint Technologies. All rights reserved.
In JavaScript, we have the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition is true


 Use else to specify a block of code to be executed, if the same condition is false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed

IF Statement
Use the if statement to specify a block of JavaScript code to be executed if a condition is true.

Syntax
if (condition) {
block of code to be executed if the condition is true
}

Else Statement
Use the else statement to specify a block of code to be executed if the condition is false.

if (condition) {
block of code to be executed if the condition is true
} else {
block of code to be executed if the condition is false
}

Else if Statement
Use the else if statement to specify a new condition if the first condition is false.

if (condition1) {
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is false and condition2 is true
} else {
block of code to be executed if the condition1 is false and condition2 is false
}

Switch Statement

Use the switch statement to select one of many blocks of code to be executed.

Syntax
switch (expression) {
case n:
code block

29
Copyright © 2018. BluePrint Technologies. All rights reserved.
break;
case n:
code block
break;
default:
code block
}

This is how it works:

 The switch expression is evaluated once.


 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.

Break
When JavaScript reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

Default
The default keyword specifies the code to run if there is no case match:

3.6.4 Logical operators


The logical operators are used to connect two or more Boolean expressions. Examples of
logical operators include the AND operator (&&), OR operator (||), and the NOT operator (!). A condition
joined with the AND operator is true only when all of the Boolean expressions are true. For example,
in the following

(4 > 2) && (10 < 15)

In table 8, we list the logical operators available in JavaScript.


Table 8Available Logical operators in JavaScript

Operator Description

&& Returns true only when all expressions are true.

|| Returns true only when at least one expression is true.

! Returns true if an expression is false and false if an expression is true.

30
Copyright © 2018. BluePrint Technologies. All rights reserved.
3.6.5 Comparison operators
Comparison operators are also called relational operators. These operators are used to
construct and test conditions. To use the operator, we need left-hand-side and right-hand-side. The
sides represent the values we want to compare and the comparison operator is placed between the
values. See the following as an example:

Figure 7Comparison operator in JavaScript

Table 9Various Comparison operator in Java Script

Operator Description
== Returns true if both sides are equal. Note the mathematical equal sign (=) is
interpreted as an assignment operator in JavaScript. So, in JavaScript, use two
equal symbols (==) when you want to find out if one variable is equal to another.
!= Returns true if variables are not equal
> Returns true if the variable on the left is greater than the variable on the right
< Returns true if the variable on the left is less than the variable on the right
>= Returns true if the variable on the left is greater than or equal to the value of
the variable on the right
<= Returns true if the variable on the left is less than or equal to the value of the
variable on the right

3.7 Working with loops


Looping or iteration control is used to execute some set of instructions repeatedly. Without
loops, we would have to write the instructions, as many times we want them to execute. Let us print
numbers 1 through 5 without using a loop:

<script language="javascript">
document.write (1 + "<br>");

31
Copyright © 2018. BluePrint Technologies. All rights reserved.
document.write (2 + "<br>");
document.write (3 + "<br>");
document.write (4 + "<br>");
document.write (5 + "<br>");
</script>

The following shows the output of the above code:


1
2
3
4
5

Before we do this same example with a loop control structure, let us first point out that there
are four types of loops

 for - loops through a block of code a number of times


 for/in - loops through the properties of an object
 while - loops through a block of code while a specified condition is true
 do/while - also loops through a block of code while a specified condition is true

For Loop
The for loop is often the tool you will use when you want to create a loop.

The for loop has the following syntax:

for (statement 1; statement 2; statement 3) {


code block to be executed
}

Statement 1 is executed before the loop (the code block) starts.

Statement 2 defines the condition for running the loop (the code block).

Statement 3 is executed each time after the loop (the code block) has been executed.

For/in Loop
The JavaScript for/in statement loops through the properties of an object:

<script>

var txt = "";

var person = {fname:"John", lname:"Doe", age:25};

32
Copyright © 2018. BluePrint Technologies. All rights reserved.
var x;

for (x in person) {

txt += person[x] + " ";

document.getElementById("demo").innerHTML = txt;

</script>

The output of this is as follows

JavaScript Loops

The for/in statement loops through the properties of an object.

John Doe 25

The while loop


The while loop is different from a for loop in the respect that it is known ahead of time how
many times a while loop will execute.

The general syntax for creating a while loop is:

while (condition) {
JavaScript statements that you want to execute repeatedly
}

where
condition = a Boolean expression that can be true or false. While the Boolean expression is true, the
JavaScript code inside the while loop is executed.

The following shows an example of a while loop:

<script language="javascript">
var i = 1;
while (i <= 5) {
document.write (i + " ");
i++;
}
</script>

Note that for a while loop we initialize our counter variable, i, before the loop starts. Note also the
counter variable is updated inside the while loop. This while loop prints:

12345

33
Copyright © 2018. BluePrint Technologies. All rights reserved.
Table 10JavaScript While Loop Sample code

JavaScript while loop code Output


<script language="javascript"> 1
var i = 1; 3
// this while loop prints odd numbers between 1 and 10. 5
while (i <= 10) { 7
document.write (i + "<br>"); 9
i += 2;}</script>
<script language="javascript"> 2
var i = 2; 4
// this while loop squares i as long as i is less than or equal 8
to 1024.while (i <= 1024) { 16
document.write (i + "<br>"); 32
i *= 2; 64
} 128
</script> 256
512
1024

3.8 Creating JavaScript functions


If you have to write a large program, you may consider using functions. Functions allows you
to easily reuse your code. A function is a series of commands that either calculates a value or
performs an action. A function consists of function name, which identifies it, parameters, the values
passed to the function, and the set of commands that run when the function is called. To use a function,
you call the function. When you call the function, you pass (send) the values used by the function.
Note that not all functions require you to pass values; thus parameters are optional. Functions can
also return a value, the result of the calculation or the output of the function sent back from the
function.

The general syntax of a JavaScript function is:

function functionName (parameters) {


JavaScript commands
}

where

functionName = name of the function

parameters = values sent to the functions

JavaScript commands = commands that run when the function is called or used

A function starts with the keyword function. All the commands that belong to a function must
be placed inside the curly braces { }. The set of commands placed inside the curly braces is referred
to as a commands block. The commands block combined with the function name is referred to as
a function definition. In other words, a function definition tells you what the function is and what it
does.

34
Copyright © 2018. BluePrint Technologies. All rights reserved.
Before you start creating your own JavaScript functions, keep in mind that JavaScript function
name must begin with a letter or underscore (_). The function name cannot contain any spaces. In
addition, like variables, function names are case-sensitive. Thus, calculateSalary and CalculateSalary
are considered different function names. For the function parameters, there is no limit in the number
of function parameters a function contains. The function parameters must be placed inside the
parentheses, following the function name, and a comma must separate each parameter.

3.8.1 Performing an action with a function


To create a function, first decide what exactly you want the function to do. For now, we will
start with a simple JavaScript function that will print a message to the screen. Remember the idea
behind using functions is to reuse and organize your code. That should start to make sense as follow
examples shown on this page.
Suppose we have the following function definition:
function DisplayMessage () {
document.write ("Learn JavaScript from the Scripting Master!");
}
The name of this function is DisplayMessage. Anytime we want to use this function, we will use the
function name we listed between the keyword function and parentheses. When we say we want to use
or call a function, we are saying we want the function to run the code inside function. Recall the code
inside the curly braces is called command block. In the DisplayMessage function, our command block
only consists of a statement that will print a message using the document.write method.
Note that our function takes no parameters. Recall parameters are listed inside the parenthesis. To
call the DisplayMessage function, we will simply write
DisplayMessage ()
Now, let's use this example to show you how to use a function in JavaScript:

<script language="javascript">
function DisplayMessage () {
document.write ("Learn JavaScript from the Scripting Master!");
}
document.write ("Calling the function....<br>");
DisplayMessage ();
document.write ("<br>..Done!");
</script>
The execution of this script will begin on line five and that prints the "Calling the function...”
Remember that a function is executed only when you call the function. We call the function on line 6.
When the function is called, the code inside the function will be executed. So after line 6, line 2 will be
executed that states the name of the function and indicates that it takes no parameters because of the
empty parentheses. Next, line 3 will be executed to print the "Learn JavaScript from the Scripting
Master!" Line 4 ends our function. Finally, line 7 will be executed to print ".Done!" The following shows
the output of the above JavaScript code:
Calling the function....
Learn JavaScript from the Scripting Master!
..Done!

35
Copyright © 2018. BluePrint Technologies. All rights reserved.
As you may have noticed, when we use functions we are changing the order in which the statements
in our scripts are executed. In other words, your statements may not run in the order they are listed in
your program. This type of control structure is referred to as non-linear (non-sequential) execution. In
our JavaScript code above, lines 2, 3, and 4 were executed after line 6.
With this one example, do not feel that functions make you write extra code. Remember the idea
behind using functions is to reuse code. For instance, let us say we wanted to print a long welcome
message in five different places of our program. For that example, we would define a function that
contains our welcome message. Anytime we need to print that message we just simply call the
function. You do not have to write five different document.write () methods for the welcome message
at five different locations in your program!

3.8.2 Passing parameters to functions


In the previous section, you saw how to define a function and use a function. In this section, you will
learn how to pass parameters (or values) to a function. Let us continue with the example we used in
the previous section. We will change our function definition and the other JavaScript code as follows:
<script language="javascript">
function DisplayMessage (message) {
document.write (message + "<br>");
}
DisplayMessage ("Hello,");
DisplayMessage ("Learn JavaScript, HTML, ASP!");
</script>
This function takes in one parameter called message, see line 2. Remember parameters are
listed inside the parentheses. On line 3, we print the value of message. On line 5 and 6, we call the
function DisplayMessage () and pass different values each time. The following shows the output of the
above code:
Hello,
Learn JavaScript, HTML, ASP!
As another example, let us write a function that will calculate a person's salary; we will ignore
taxes or any other deductions. For this function, we will pass three parameters: employeeName,
hoursWorked, and payRatePerHour. The following shows the JavaScript code:
<script language="javascript">
calculateSalary (employeeName, hoursWorked, payRatePerHour) {
var totalSalary;
totalSalary = hoursWorked * payRatePerHour;
document.write (employeeName + ", your salary for this week is: $" + totalSalary + "<br>");
}
calculateSalary ("Steve", 25, 30);
calculateSalary ("John", 40, 40);
</script>
Note in our function definition (line 2) and when we call the function (lines 7 and 8), that, each
parameter is separated with a comma. In addition, when you pass values to a function, make sure you
send the values in the order the function expects the values. For this function, the first parameter
expects a string, the second parameter expects the number of hours a particular person has worked,

36
Copyright © 2018. BluePrint Technologies. All rights reserved.
and the third parameter expects the pay rate for an individual. The following shows the output of this
example:
Steve, your salary for this week is: $750
John, your salary for this week is: $1600

3.8.3 Returning a value from a function


To return a value from a function, use the return command along with a variable or value at
the end of the function's command block. Consider the following function definition:
function isEven (num) {
if (num % 2 == 0) {
return num;
}
}
This function determines if a number is even. This function takes one parameter, num. On
line 4, we return the value of num. Note line 4 is only executed if the Boolean expression on line 3 is
true. Note that our Boolean expression uses the modulus operator. Let us find even numbers
between 1 and 20 by using the function definition we show above.
In the following code,
<script language="javascript">
function isEven (num) {
if (num % 2 == 0) {
return num;
}
}
function printMessage (num) {
if (num > 1) {
document.write (num + " ");
}
}
var evenNum;
document.write ("Even numbers: ");
for (i = 1; i <= 20; i++)
{
evenNum = isEven (i);
printMessage (evenNum);
}
</script>
We are using two functions. We call the isEven () function on line 16 inside a for loop.
Our for loop is on lines 14 through 18. The for loop executes 20 times and calls the isEven () function
and the printMessage () function 20 times. The first time the isEven function is called with the
parameter value 1. The function returns nothing because 1 % 2 does not equal zero, so the
printMessage () function will print nothing. However, when the second time the for loop is run, the
value 2 is passed to the isEven () function. This is a even number because 2 % 2 is 0 so the function
will return 2. In this case, the printMessage () function will print the number 2. The following shows the
output of the JavaScript code:

37
Copyright © 2018. BluePrint Technologies. All rights reserved.
Even numbers: 2 4 6 8 10 12 14 16 18 20
Reference 1 : https://www.w3schools.com/js/
Reference 2: https://www.codeschool.com/learn/javascript

38
Copyright © 2018. BluePrint Technologies. All rights reserved.
4.0 Introduction to SAPUI5
SAP UI5 apps has rich user interfaces for modern Web business applications, responsive
across browsers and devices, based on HTML5.

SAPUI5 offers powerful development concepts:

 One consistent user experience for your apps


 Responsive across browsers and devices - smartphones, tablets, desktops
 Built-in extensibility concepts at code and application level
 Data binding types and Model-View-Controller (MVC)
 Feature-rich UI controls for handling complex UI patterns and predefined layouts for typical use
cases.
 UI controls automatically adapt themselves to the capabilities of each device.
 Full translation support
 Keyboard interaction support and accessibility features

Reference:https://sapui5.hana.ondemand.com/1.46.10/#docs/guide/95d113be50ae40d5b0b
562b84d715227.html

4.1 Versioning
SAPUI5 uses a 3-digit version identifier, for example 1.48.8. The digits have the following meaning:

 The first digit (1) specifies the release number (major version).

 The second digit (44) specifies the version number (minor version).

 The third digit (7) specifies the patch number.

Reference:https://sapui5.hana.ondemand.com/#/topic/91f021426f4d1014b6dd926db0e9107
0

39
Copyright © 2018. BluePrint Technologies. All rights reserved.
4.2 SAPUI5 Architecture Overview
In SAP UI5 architecture, you have three layers −

 At the top, is the presentation layer, where devices like mobile, tablets, and laptops consume UI5
components.

 At the middle layer, is the application clients that includes SAP UI5 libraries for theming and
controls. UI5 control libraries include

o Sap. Viz

o Sap.ui. commons (Controls like text fields and buttons)

o Sap.ui. table (Input controls for table)

o Sap.ui.ux3

o Sap.m (Includes input control for mobile devices)

 At the bottom, Application Server component. This includes SAP NetWeaver Application Server
for ABAP/Java, SAP backend, HANA XS engine for development or database.

Figure 8SAPUI5 Architecture

Reference: https://www.tutorialspoint.com/sap_ui5/sap_ui5_architecture.htm

40
Copyright © 2018. BluePrint Technologies. All rights reserved.
4.3 Model View Controller
Model, view, and controller are assigned the following roles:

 The view is responsible for defining and rendering the UI.

 The model manages the application data.

 The controller reacts to view events and user interaction by modifying the view and model.

Figure 9MVC Representation

The purpose of data binding in the UI is to separate the definition of the user interface (view), the data
visualized by the application (model), and the code for the business logic for processing the data
(controller). The separation has the following advantages: It provides better readability, maintainability,
and extensibility and it allows you to change the view without touching the underlying business logic
and to define several views of the same data.

Views and controllers often form a 1:1 relationship, but it is also possible to have controllers without a
UI, these controllers are called application controllers. It is also possible to create views without
controllers. From a technical position, a view is a SAPUI5 control and can have or inherit
a SAPUI5 model. View and controller represent reusable units, and distributed development is highly
supported.

Reference:https://sapui5.hana.ondemand.com/#/topic/91f233476f4d1014b6dd926db0e9
1070

41
Copyright © 2018. BluePrint Technologies. All rights reserved.
4.4 Controls and Libraries
4.4.1 Controls
Controls can be used to define appearance and behavior of parts of the screen. Controls
consist of:

Control name

 The control name is a string that consists of the library name and the control name, separated by
a dot.

 The library name should be omitted if there is no need to assign the control to a library. It is
possible, for example, to use Square as control name.

 For controls that are reused by others, we recommend to use a unique library name, for
example sap.byd.Square.

Control metadata

 The metadata defines the properties, events, aggregations and associations of a control.

Elements

 Elements are parts of controls or rather configuration packages for parts of controls.
Elements cannot be used standalone and do not have their own renderer.

 Instead, the control that uses the element does the rendering: The List Box control, for example,
renders the List Item elements.

Methods

 By convention, methods are public, unless their name starts with an underscore or if it is one of
the special method types.
 When developing control libraries. The public methods has to be annotated with @public in the
JSDoc, and private methods with @private.
 The generated getter/setter methods for properties are also public methods.
 We can add methods to a new control by simply providing the implementation. Iis not necessary
to add the method to the metadata
 Other controls and the application must only call public methods and the control ensures that they
remain compatible.
 There are no technical rules that prevent the call of private methods, but as a good practice it is
not allowed

Reference:https://sapui5.hana.ondemand.com/#/topic/ddbceecd7d3d42eea9cf78a820a2
38fb

42
Copyright © 2018. BluePrint Technologies. All rights reserved.
4.42 Libraries
SAPUI5 provides a set of JavaScript and CSS libraries, which can be combined in an
application using the combinations that are supported.

Figure 10SAP Libraries

Deprecated Libraries

 sap.ui.commons
o Deprecated as of version 1.38.
 sap.ui.ux3
o Deprecated as of version 1.38.
 sap.ca
o Deprecated as of version 1.22.
 sap.me
o Deprecated as of version 1.34.
 sap.makit
o Deprecated as of version 1.38.

Reference:https://sapui5.hana.ondemand.com/#/topic/363cd16eba1f45babe3f661f321a7820

43
Copyright © 2018. BluePrint Technologies. All rights reserved.
4.5 Types of Views, Model, Bindings Commented [RA1]: 1.Add Navigation and Routing after
this topic
4.5.1 Views 2. Fragments
The view in the Model View Controller concept is responsible for defining and rendering the 3. Formatters
UI. SAPUI5 supports predefined view types.

 XML view. The user interface is defined in an XML file or string. The XMLView type supports a
mix of XML and plain HTML.
 JSON view. The user interface is defined in a file or string in JSON format.
 JS view. The user interface is constructed in a traditional manner that is in JS format.
 HTML view. The user interface is defined in an HTML file or string.

Reference:https://help.sap.com/saphelp_nw74/helpdata/en/91/f0df546f4d1014b6dd926d
b0e91070/frameset.htm

4.5.2 Model
A model in the Model View Controller concept holds the data and provides methods to retrieve
the data from the database and to set and update data.SAPUI5 provides the following predefined
models.
The JSON model can be used to bind controls to JavaScript object data, which is usually
serialized in the JSON format. The JSON model is a client-side model and, therefore, intended for
small datasets, which are completely available on the client. The JSON model supports two-way
binding.
The XML model is a client-side model intended for small datasets, which are completely
available on the client. The XMLModel does not contain mechanisms for server-based paging or
loading of deltas
The Resource model is designed to handle data in resource bundles, mainly to provide texts
in different languages.
The OData model enables binding of controls to data from OData services. The OData model
is a server-side model: the dataset is only available on the server and the client only knows the
currently visible rows and fields. This also means that sorting and filtering on the client is not possible.
For this, the client has to send a request to the server.
Reference:https://help.sap.com/saphelp_nw74/helpdata/en/91/f0df546f4d1014b6dd926db0e
91070/frameset.htm

4.5.3 Bindings and its Types


SAPUI5 uses data binding to bind two data sources or information sources together to keep
them coordinated: All changes in one data source will be reflected in the other data source.
For data binding, you need a model and a data-binding instance: The model instance holds
the data and provides methods to set the data or to retrieve the data from a server. It also provides a
method for creating bindings to the data. When this method is called, a data-binding instance is
created, which contains the binding information and provides an event, which is fired whenever the
bound data is changed. An element can listen to this event and update its visualization according to
the new data.

44
Copyright © 2018. BluePrint Technologies. All rights reserved.
Binding Types

 One Way: One-way binding means a binding from the model to the view; value changes in
the model update all corresponding bindings and the view
 Two Way: Two-way binding means a binding from the model to the view and from the view to
the model; value changes in the model and in the view update all corresponding bindings and
the view and model, respectively
 One Time: One-time binding means from model to view once.

Table 11Model Types

Model One Way Two Way One Time


Resource Model -- -- X
JSON Model X X X
XML Model X X X
OData Model X X X
Reference:https://help.sap.com/saphelp_nw74/helpdata/en/91/f0df546f4d1014b6dd926db0e
91070/frameset.htm

45
Copyright © 2018. BluePrint Technologies. All rights reserved.
5.0 Introduction to SAPUI5 Controls and API
5.1 Controls in SAP UI5:
By opening this URL https://sapui5.hana.ondemand.com/#/controls we will get a page similar
to the one shown in figure 11.

Figure 11Available controls in sapui5

As shown in the figure 11 we can do search for a control, one can be able to see the control
sample, and how it can be used.

Figure 12Control Samples

46
Copyright © 2018. BluePrint Technologies. All rights reserved.
Next we need to click on the control name shown on the right side of the page , which shows
how the controls looks when implemented in SAP UI5 application. The figure 13 depicts the same.

Figure 13 Control demo

Click on this icon available on the top right of the page to reveal the code as shown in figure 13

Figure 14Application Code

We can also download the code and import it to our webide for our own study.

47
Copyright © 2018. BluePrint Technologies. All rights reserved.
5.2 API Reference:
SAP provides a huge collection of API that can be consumed in to our application. To open
API reference please click on this link https://sapui5.hana.ondemand.com/#/api

Figure 15API Reference

Figure 16API Options

As shown in figure 16 we can search for an API and the right side of the page gives us the
Overview, constructor properties events and Methods of the selected API.

48
Copyright © 2018. BluePrint Technologies. All rights reserved.
6.0 Exercises
6.1 SAP HCP URL

Register: https://accounts.sap.com/saml2/idp/sso/accounts.sap.com

Figure 17SAP HCP Registration screen

Login:https://accounts.sap.com/saml2/idp/sso?sp=sp.accounts.sap.com&RelayState
=https://accounts.sap.com/ui/protected/profilemanagement

Figure 18SAP HCP Login Screen

Reference: https://www.sap.com/developer/tutorials/hcp-create-trial-account.html

49
Copyright © 2018. BluePrint Technologies. All rights reserved.
6.2 WEB IDE Configuration
Open your SAP Cloud Platform account (if you have a free developer account, click HERE to
open the console.)

Figure 19Webide Login Page

After signing in using the SAP HCP credentials .You should now be in the SAP Cloud Platform
Cockpit, as shown below. Click on the Services menu item on the left

Figure 20HCP Cockpit Services

50
Copyright © 2018. BluePrint Technologies. All rights reserved.
Next, click on the SAP Web IDE box as shown in figure 20. You may need to scroll down to
find this box.

Figure 21SAP Webide Service Selection

In the SAP Web IDE screen, you will see a paragraph called Service Description. At the
bottom of the paragraph, there is a link called Open SAP Web IDE as in figure 21. Click this link

Figure 22SAP Webide- Opening link

51
Copyright © 2018. BluePrint Technologies. All rights reserved.
A new tab (or window) will open, and the Web IDE will load as shown in figure 22

Bookmark this page! If you create a bookmark to this page, it is easy to get back to the
Web IDE later.

Figure 23SAP Webide Welcome Page

Reference:https://www.sap.com/india/developer/tutorials/sapui5-webide-open-webide.html

52
Copyright © 2018. BluePrint Technologies. All rights reserved.
6.3 Configuring ODATA Services in Web IDE
Log into SAP Cloud Platform

Figure 24Cockpit Login

Go to https://account.hanatrial.ondemand.com and log in to your SAP Cloud Platform cockpit.

Next step, Select the Destinations tab on the left side, and then click on New
Destination to open a new destination configuration form.

Figure 25Destination Menu

53
Copyright © 2018. BluePrint Technologies. All rights reserved.
Confirm data
Enter/confirm all fields in the Destination configuration section with the information below.

Field Name Value

Name Northwind

Type HTTP

Description Northwind OData Service

URL http://services.odata.org

Proxy Type Internet

Authentication No Authentication

Do not use the entire path for the URL. The URL should only be http://services.odata.org

Add properties
Add three Additional Properties fields by clicking on the New Property button once for
each property.

Field Name Value

WebIDEEnabled true

WebIDESystem Northwind_Data

WebIDEUsage odata_gen

54
Copyright © 2018. BluePrint Technologies. All rights reserved.
Figure 26Add Properties to destination

Click Save and then click on test connection.


Referencehttps://www.sap.com/developer/tutorials/hcp-create-destination.html

55
Copyright © 2018. BluePrint Technologies. All rights reserved.
6.4 Creating a sample project in Web IDE

Go to your SAP Web IDE.

Select File –> New –> Project from Template…

Select the box called SAPUI5 Application, then click next.

(Leave the Available Versions box on SAPUI5 Innovation).

56
Copyright © 2018. BluePrint Technologies. All rights reserved.
Fill in the form as follows:

Project Name Navigation_in_SAP

Name Space (leave this field blank)


Enable native mobile device functionality (unselected)

57
Copyright © 2018. BluePrint Technologies. All rights reserved.
Then click on next

Now an empty project will be created.


Open sap course link for ui5: https://open.sap.com/courses/ui51
Open sap course link for HCP : https://open.sap.com/courses/hanacloud2-2

Reference:https://www.sap.com/india/developer/tutorials/sapui5-webide-create-project.html
Sample Program Link: https://bpterp.sharepoint.com/:u:/s/UXSmart/EZnhCe7lortPl-
F0WLebMoYBk0xDVfSdFwhUlRrFC-9tmA?e=n3gsMZ

58
Copyright © 2018. BluePrint Technologies. All rights reserved.
Sample Output

Figure 27App Homepage

This application shows how we can do navigation in SAPUI5


Display Not Found

Figure 28Page Not Found

Show Employee List (Mandatory Parameter Routing)

59
Copyright © 2018. BluePrint Technologies. All rights reserved.
Figure 29Mandatory Parameter Routing

Show Employee Overview (Multiple Parameter Routing)

Figure 30Multiple Parameter Routing Commented [RA2]: Add Hybrid apps


Offline apps
Configuring apps on SCP Launchpad

60
Copyright © 2018. BluePrint Technologies. All rights reserved.
7.0 Do’s and Don’ts Commented [RA3]: Cover Fiori Implementation before
Do’s and Don’ts
7.1 JavaScript Code Issues Fiori apps library
Fiori apps extension
 Don't use methods or properties that are not public Launchpad configuration
 Don't use references to global names
 Don't use deprecated APIs
 Don't override or add control methods
 Don't manipulate the DOM structure within controls
 Don't attach DOM event handlers
 Don't create global IDs (when running with other views or apps)
 Don't forget about control lifecycle management
 Don't hard code or concatenate strings that need to be translatable
 Don't forget about proper "this" handling
 Don't use console.log()
 Don't use timeouts
 Don't build apps without reasonable automated tests
Referencehttps://sapui5.hana.ondemand.com/#/topic/030fcd14963048218488048f407f8f34.html

7.2 CSS Styling Issues


This section lists some of the most important rules relating to CSS styling in SAPUI5.
 Don't override control class styling directly
 Don't style DOM element names directly
 Don't use generated IDs in CSS selectors
 Don't create selectors that are not name spaced
 Don't use hard-coded colors, font sizes and images if the app should be themable
 Don't use theming parameters for attributes they were not intended for
Reference https://sapui5.hana.ondemand.com/#/topic/9d87f925dfbb4e99b9e2963693aa00ef

7.3 Performance Issues


 Do not use visibility for lazy instantiation
Reference
1https://sapui5.hana.ondemand.com/#/topic/966d67c8cc5046419d1b35556cd9e447
Reference 2https://www.w3schools.com/js/js_best_practices.asp

61
Copyright © 2018. BluePrint Technologies. All rights reserved.

Das könnte Ihnen auch gefallen