SAPX04: HTML5 Foundations For SAP SAPUI5 Development
SAPX04: HTML5 Foundations For SAP SAPUI5 Development
SAP SAPGUI5
Training System: Windows 2008 R2 with latest SAPUI5 component)
Collection 95
No part of this publication may be reproduced or transmitted in any form or for any purpose
without the express permission of SAP AG. The information contained herein may be
changed without prior notice.
Some software products marketed by SAP AG and its distributors contain proprietary
software components of other software vendors.
Microsoft, Windows, Excel, Outlook, PowerPoint, Silverlight, and Visual Studio are
registered trademarks of Microsoft Corporation.
Apache Maven, Maven, Apache, the Apache feather logo, and the Apache Maven project
logos are trademarks of The Apache Software Foundation. This course is not designed to
teach candidates MAVEN technology. Existing knowledge of MAVEN is a pre-requisite.
IBM, DB2, DB2 Universal Database, System i, System i5, System p, System p5, System x,
System z, System z10, z10, z/VM, z/OS, OS/390, zEnterprise, PowerVM, Power
Architecture, Power Systems, POWER7, POWER6+, POWER6, POWER, PowerHA,
pureScale, PowerPC, BladeCenter, System Storage, Storwize, XIV, GPFS, HACMP,
RETAIN, DB2 Connect, RACF, Redbooks, OS/2, AIX, Intelligent Miner, WebSphere, Tivoli,
Informix, and Smarter Planet are trademarks or registered trademarks of IBM Corporation.
Linux is the registered trademark of Linus Torvalds in the United States and other countries.
Adobe, the Adobe logo, Acrobat, PostScript, and Reader are trademarks or registered
trademarks of Adobe Systems Incorporated in the United States and other countries.
Oracle and Java are registered trademarks of Oracle and its affiliates.
UNIX, X/Open, OSF/1, and Motif are registered trademarks of the Open Group.
Citrix, ICA, Program Neighborhood, MetaFrame, WinFrame, VideoFrame, and MultiWin
are trademarks or registered trademarks of Citrix Systems Inc.
HTML, XML, XHTML, and W3C are trademarks or registered trademarks of W3C,
World Wide Web Consortium, Massachusetts Institute of Technology.
Apple, App Store, iBooks, iPad, iPhone, iPhoto, iPod, iTunes, Multi-Touch, Objective-C,
Retina, Safari, Siri, and Xcode are trademarks or registered trademarks of Apple Inc.
IOS is a registered trademark of Cisco Systems Inc.
Google App Engine, Google Apps, Google Checkout, Google Data API, Google Maps,
Google Mobile Ads, Google Mobile Updater, Google Mobile, Google Store, Google Sync,
Google Updater, Google Voice, Google Mail, Gmail, YouTube, Dalvik and Android are
trademarks or registered trademarks of Google Inc.
INTERMEC is a registered trademark of Intermec Technologies Corporation.
Wi-Fi is a registered trademark of Wi-Fi Alliance.
Bluetooth is a registered trademark of Bluetooth SIG Inc.
Motorola is a registered trademark of Motorola Trademark Holdings LLC.
Computop is a registered trademark of Computop Wirtschaftsinformatik GmbH.
SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP BusinessObjects Explorer,
StreamWork, SAP HANA, and other SAP products and services mentioned herein as well
as their respective logos are trademarks or registered trademarks of SAP AG in Germany
and other countries.
Business Objects and the Business Objects logo, BusinessObjects, Crystal Reports, Crystal
Decisions, Web Intelligence, Xcelsius, and other Business Objects products and services
mentioned herein as well as their respective logos are trademarks or registered trademarks
of Business Objects Software Ltd. Business Objects is an SAP company.
Sybase and Adaptive Server, iAnywhere, Sybase 365, SQL Anywhere, and other Sybase
products and services mentioned herein as well as their respective logos are trademarks or
registered trademarks of Sybase Inc. Sybase is an SAP company.
Crossgate, m@gic EDDY, B2B 360, and B2B 360 Services are registered trademarks
of Crossgate AG in Germany and other countries. Crossgate is an SAP company.
All other product and service names mentioned are the trademarks of their respective
companies. Data contained in this document serves informational purposes only. National
product specifications may vary.
The information in this document is proprietary to SAP. No part of this document may be
reproduced, copied, or transmitted in any form or for any purpose without the express prior
written permission of SAP AG.
RIM, BlackBerry, BBM, BlackBerry Curve, BlackBerry Bold, BlackBerry Pearl, BlackBerry
Torch, BlackBerry Storm, BlackBerry Storm2, BlackBerry PlayBook, and BlackBerry App
World are trademarks or registered trademarks of Research in Motion Limited.
2014 SAP AG. All rights reserved.
Weitergabe und Vervielfltigung dieser Publikation oder von Teilen daraus sind, zu
welchem Zweck und in welcher Form auch immer, ohne die ausdrckliche schriftliche
Genehmigung durch SAP AG nicht gestattet. In dieser Publikation enthaltene Informationen
knnen ohne vorherige Ankndigung gendert werden.
Google App Engine, Google Apps, Google Checkout, Google Data API, Google Maps,
Google Mobile Ads, Google Mobile Updater, Google Mobile, Google Store, Google Sync,
Google Updater, Google Voice, Google Mail, Gmail, YouTube, Dalvik und Android sind
Marken oder eingetragene Marken von Google Inc.
Microsoft, Windows, Excel, Outlook, PowerPoint, Silverlight und Visual Studio sind
eingetragene Marken der Microsoft Corporation.
Apache Maven, Maven, Apache, the Apache feather logo, and the Apache Maven project
logos sind eingetragene Marken der Apache Software Foundation.
IBM, DB2, DB2 Universal Database, System i, System i5, System p, System p5, System x,
System z, System z10, z10, z/VM, z/OS, OS/390, zEnterprise, PowerVM, Power
Architecture, Power Systems, POWER7, POWER6+, POWER6, POWER, PowerHA,
pureScale, PowerPC, BladeCenter, System Storage, Storwize, XIV, GPFS, HACMP,
RETAIN, DB2 Connect, RACF, Redbooks, OS/2, AIX, Intelligent Miner, WebSphere, Tivoli,
Informix und Smarter Planet sind Marken oder eingetragene Marken der IBM Corporation.
Linux ist eine eingetragene Marke von Linus Torvalds in den USA und anderen Lndern.
Adobe, das Adobe-Logo, Acrobat, PostScript und Reader sind Marken oder eingetragene
Marken von Adobe Systems Incorporated in den USA und/oder anderen Lndern.
Oracle und Java sind eingetragene Marken von Oracle und/oder ihrer
Tochtergesellschaften.
UNIX, X/Open, OSF/1 und Motif sind eingetragene Marken der Open Group.
Citrix, ICA, Program Neighborhood, MetaFrame, WinFrame, VideoFrame und MultiWin
sind Marken oder eingetragene Marken von Citrix Systems, Inc.
HTML, XML, XHTML und W3C sind Marken oder eingetragene Marken des W3C,
World Wide Web Consortium, Massachusetts Institute of Technology.
Apple, App Store, iBooks, iPad, iPhone, iPhoto, iPod, iTunes, Multi-Touch, Objective-C,
Retina, Safari, Siri und Xcode sind Marken oder eingetragene Marken der Apple Inc.
IOS ist eine eingetragene Marke von Cisco Systems Inc.
RIM, BlackBerry, BBM, BlackBerry Curve, BlackBerry Bold, BlackBerry Pearl, BlackBerry
Torch, BlackBerry Storm, BlackBerry Storm2, BlackBerry PlayBook und BlackBerry App
World sind Marken oder eingetragene Marken von Research in Motion Limited.
Course Topics
Course Description
This course is a pre-requisite course for all courses on SAP SAPUI5, especially if
a developer is new to the field of web development.
There will be hands-on exercises performed during the course to gain experience
with HTML5 so as to prepare the participant for follow up SAP SAPUI5 classes.
Course Goals
Course Objectives
Course Prerequisites
Required Knowledge (Essential)
Recommended
None
Developers
Technology Consultants
Product owners and consultants looking for an in-depth overview of
web development
Duration: 2 days
Course Content
Content:
Unit 1 Foundations of HTML5 & CSS
Unit 2 Foundations of JavaScript
Unit 3 Foundations of JQuery
Unit 4 Security
10
11
Day 2:
Unit 3 Foundations of JQuery
UNIT 4 Security
12
UNIT 1
Foundations of HTML5
& CSS
14
15
Lesson Objectives
16
HTML5 Essentials
Web Technologies
Technology
Role
Examples
HTML
(HTML5)
Markup Language
Page Content
Semantics of the Page
Headings, Paragraphs
Sections, Headers, Footers, Articles
Hyperlinks, Buttons
CSS (CSS3)
Annotation Language
Page Style
Appearance of the Page
JavaScript
Programming Language
Page Dynamics
Behavior of the Page
Popup Windows
Event Handlers for Buttons
DOM Manipulation
AJAX and related Techniques
jQuery
jQueryUI
18
What is HTML5?
Next generation of HTML superseding HTML 4.01, XHTML 1.0, XHTML 1.1
19
Examples
Semantics
Device Access
Connectivity
Multimedia
CSS3
(Source: http://www.w3.org/html/logo/)
20
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Basic HTML 5 Page Template</title>
</head>
<body>
<!-- Body Content -->
</body>
</html>
21
about:
about:about
about:blank
view-source:
file:
22
Useful Tools
23
Additional Information
24
http://vesapui5.dhcp.wdf.sap.corp:1080/trac/sapui5/wiki/Documentation/Tools/download
Recommended is the 64bit version; only if NGAP/BSP repositories are to be used (not
relevant for the training) the 32bit version should be installed
MAC users in addition follow the steps from the Installation Guide for ABAP in Eclipse
https://wiki.wdf.sap.corp/wiki/display/aie/ABAP+In+Eclipse+on+Mac
25
26
Go to File Import.
27
Click OK.
2014 SAP AG. All rights reserved.
28
29
Total View
Expand the
Modul_1_HTML_
Practice folder to
view all directories
& files and confirm
30
31
Upon installation, note the new tab and the change in status:
32
33
15 minutes
2014 SAP AG. All rights reserved.
34
CSS3 Essentials
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>My Page</title>
<link href="css/style.css" rel="stylesheet" />
</head>
<body>
<! Body Content -->
</body>
</html>
36
Basic Selectors
Universal Selector
The universal selector is an asterisk. It is like a wildcard and matches all element
types in the document
*{}
Type Selector
body, footer, p {}
The ID Selector
The ID selector works on the value of ID attributes
#mainHeader {}
37
Basic Selectors
Class Selector
The class selector matches on the value of class attributes
<p class="topNavigation">paragraph</p>
.topNavigation {}
38
Property Survey
/* property: value; */
font-family: Georgia, Arial;
font-size: 10px;
text-transform: uppercase;
text-decoration: none;
font-weight: bold;
background-color: #FF4400;
color: #949494;
border: 2px solid green;
border-radius: 5px;
margin-top: 20px;
padding-bottom: 5px;
width: 200px;
height: 100px;
2014 SAP AG. All rights reserved.
39
CSS Reset
http://meyerweb.com/eric/tools/css/reset/
The goal of a reset style sheet is to reduce browser inconsistencies in things like default
line heights, margins and font sizes of headings, and so on
Reset styles quite often appear in CSS frameworks, and the original "meyerweb reset"
found its way into Blueprint, (http://www.blueprintcss.org/) among others
* {
margin: 0;
padding: 0;
}
40
Each box has a content area (e.g., text, an image, etc.) and optional surrounding
padding, border, and margin areas
The final width (height) of an element is the sum of the margin, padding, border
and the given width (height)
http://imagecss.com/
41
42
Goal
Practice the use of basic CSS selectors and properties
Method
Return to Exclipse
Use the code from P03_CSS_Essentials_Exercise_1 in your exercises folder
Task
Create the HTML document including the <style> section
Replace _universal, _type, by appropriate markup
Test the webpage
Duration
15 minutes
43
Linear Gradients
Linear Gradient
background: -moz-linear-gradient(left, blue, white);
background: -webkit-linear-gradient(left, blue, white);
45
Box Shadows
Color and Blur
box-shadow: 8px 8px lightgrey;
box-shadow: 8px 8px 4px lightgrey;
46
Rounded Corners
Circular Arcs
border-radius: 16px;
border-radius: 20%;
Elliptic Arcs
border-radius: 16px/32px;
Two Corners
border-radius: 16px 32px;
Individual Corners
border-top-left-radius: 8px;
border-top-right-radius: 16px;
border-bottom-right-radius: 24px;
border-bottom-left-radius: 32px;
47
Goal
Use gradients, shadows, corners
Method
Use P03A_CSS_Features_Exercise_1
Design a form according to
the picture on the right
Task
Add gradient effects
Add shadow effects
Add rounded corners
Test form in browser
Duration
30 minutes
2014 SAP AG. All rights reserved.
48
<section>
Defines a logical region of a page or a grouping of content
<article>
Defines an article of complete piece of content
<header>
Defines a header region of a page or section
<footer>
Defines a footer region of a page or section
<nav>
Defines a navigation region of a page or section
<aside>
Defines secondary or related content
<div> (block layout) and <span> (inline layout)
Represents a container with no special meaning used for layout purposes
50
51
52
<fieldset>
Groups related elements in a form
<input type="range">
Displays a slider control
<input type="number">
Displays a form field for numbers, often as a spin box
<input type="date">
Displays a form field for dates
<input type="email">
Displays a form field for email addresses
54
<input type="url">
Displays a form field for URLs
<input type="color">
Displays a form field for specifying colors
55
Placeholder text provides users with instructions on how they should fill in the
fields.
<input id="last_name" type="text" name="last_name"
placeholder="Smith">
HTML5 introduces an autocomplete attribute that tells web browsers that they
should not attempt to automatically fill in data for the field.
<input id="password" type="password" name="password"
value="" autocomplete="off" placeholder="8-10
characters" />
56
Goal
Use the new HTML5 input features to design a registration form
Method
Use the code from P06_HTML_Forms_Exercise_1
Task
Create an input form with labels and input fields
Add first name, last name (both text)
Add age (number), email (email), homepage (url)
Add Password (password), submit (submit)
Use placeholder text and check input validation
Validate the entire page using http://validator.w3.org/
Test the page in a browser
Duration
15 minutes
2014 SAP AG. All rights reserved.
57
58
Any attribute that starts with "data-" will be treated as a storage area for private
data (private in the sense that the end user can't see it - it doesn't affect layout or
presentation)
This allows you to write valid HTML markup (passing an HTML 5 validator) while,
simultaneously, embedding data within your page
<li class="user" data-name="John Resig" data-city="Boston"
data-lang="js" data-food="Bacon">
<b>John says:</b> <span>Hello, how are you?</span>
</li>
60
JavaScript API
The .dataset property behaves very similarly to the the .attributes property (but
it only works as a map of key-value pairs)
var user = document.getElementsByTagName("li")[0];
var pos = 0, span = user.getElementsByTagName("span")[0];
var phrases
{name:
{name:
{name:
];
= [
"city", prefix: "I am from "},
"food", prefix: "I like to eat "},
"lang", prefix: "I like to program in "}
61
Goal
Use custom data attributes to dynamically change a document.
Method
Use code from P07_HTML_Attributes_Exercise_1
Task
Create a document, add a paragraph with custom attributes
Add button and a div tag
Add a button event handler
On button click, the custom data shall be written into the div tag
Test the page in a browser
Duration
15 minutes
62
Pseudoclasses
:nth-child(n)
The :nth-child(n) selector matches every element that is the nth child, regardless
of type, of its parent
64
Goal
Use pseudoclasses as CSS selectors to style a table
Method
Use code from P08_HTML_Styling_Tables_Exercise_1
Task
Create an HTML document with a table
Define table header, body, and footer
Style the table header
Add a zebra pattern to the table body
Style the footer and the last table column
Test the page in a browser
Duration
15 minutes
2014 SAP AG. All rights reserved.
65
66
Goal
Modify the table to make it more interactive
Method
Use code from P08_HTML_Styling_Tables_Exercise_2
If a user moves the mouse over a table row its text should
become more readable and its color should change
Task
Use the :hover selector to modify the text color
Use the :hover selector to modify the text decoration
Use the :hover selector to modify the background color
Test the page in a browser by hovering the mouse over the rows
Duration
15 minutes
2014 SAP AG. All rights reserved.
67
Goal
Using events, enable row deletion
Method
Use code from P08_HTML_Styling_Tables_Exercise_3
If a user clicks on a row it should be removed from the screen
Task
Add event handlers to the table row elements
Test the page in a browser by selecting a row (s) to delete
Duration
15 minutes
68
Example of deletions:
69
CSS Floats
The Definition
Reference
http://www.alistapart.com/articles/css-floats-101/
Tutorial
http://www.maxdesign.com.au/articles/css-layouts/
2014 SAP AG. All rights reserved.
71
CSS Floats
Elements are floated horizontally, this means that an element can only be
floated left or right, not up or down.
A floated element will move as far to the left or right as it can. Usually this
means all the way to the left or right of the containing element.
The elements after the floating element will flow around it.
If an image is floated to the right, a following text flows around it, to the left.
Elements after the floating element will flow around it. To avoid this, use the
clear property.
72
Reference: http://www.maxdesign.com.au/articles/process/
2014 SAP AG. All rights reserved.
73
74
Goal
Get comfortable with CSS float layouts by writing a page with header,
footer, left (floated) column, and right (floated) column
Method
Use the code from P10_HTML_CSS_Floats_Exercise_1
Use screen shot in the following slide to design and build your page
Task
Create the page, refer to the screen shot on the next page
Add styles for header, footer, content, and navigation column
Test your page in a browser
Duration
15 minutes
75
76
Goal
Design a thumbnail gallery
Method
Use the code from P10_HTML_CSS_Floats_Exercise_2
Use gallery screen shot from the following slide
Create a oat layout and style it appropriately
Task
Create a container for the gallery
Create a thumbnail CSS class for the images
Add hover effects
Test your page in a browser by hovering over the images
Duration
15 minutes
2014 SAP AG. All rights reserved.
77
78
Unit Summary
79
UNIT 2
Foundations of
JavaScript
81
82
Lesson Objectives
83
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>JavaScript Language Basics</title>
</head>
<body>
<!-- Page Content -->
<script src="js/P21_JS_Language_Basics.js"></script>
</body>
</html>
// Message popup
alert("Hello, world!");
/* Write to console */
console.log("Hello, world!");
85
Script Placement
Short scripts
Place them in the header after the title element and after the CSS includes.
All other scripts should be placed at the end of the body region.
86
Syntax Issues
Identifier
JavaScript is case sensitive
The first character of an identifier can be a dollar sign or an underscore and any other
letter, but no number
Keywords cannot be used as identifiers
Comments
// single line comment
/* multiline comment
multiline comment */
YUI Doc
http://developer.yahoo.com/yui/yuidoc
87
Variables
Statements
o One statement per line
o All statements should end with a semicolon
o Keep your code clean and readable
88
Developer
Remarks
CoffeeScript
Open Source
http://coffeescript.org/
Dart
http://code.google.com/p/dart/
TypeScript
Microsoft
http://www.typescriptlang.org/
Node
Open Source
http://nodejs.org/
89
Resources
Documentation of ECMA-262
http://www.ecmascript.org/docs.php
SELFHTML
http://de.selfhtml.org/
JavaScript Tutorials
http://www.w3schools.com/js/default.asp
Interactive Environment
http://eloquentjavascript.net/paper.html
90
Goal
Learn how to process JavaScript within an HTML page
Method
Use as starter code P21_JS_Language_Basics_Exercise_1
Task
Create an HTML document
Insert the <script> tag at the end of the body
Send an alert popup and write some text to the console
Display the document in a browser and open the console (F12)
Open the script debugger and set a breakpoint
Load the page again and see the script stopping
Test the page in a browser
Duration
10 minutes
2014 SAP AG. All rights reserved.
91
// this is a comment
/* this is a
block comment */
// variable declaration
var iMyVariable = 12;
// multi variable declaration
var iVar1 = 0, sVar2 = "Hello";
93
// string
var sVar = "Hello World";
var sVarAlt = 'Hello World';
// number (integer && float)
var iVar = 1234;
var fVar = 12.34;
// boolean
var bVar = true;
// null && undefined
var vNull = null;
var vUndefined = undefined;
94
// string
var sVar = "Hello World";
var sVarAlt = 'Hello World';
// string escaping
var sEsc = "Hello \"World\"";
// Hello "World"
// string with a newline
var sNL = "Hello\nWorld";
// Hello
// World
\n
\r
\t
\uXXXX
newline
carriage return
tab
unicode character
95
// string operations
var sText = "test string";
alert(sText.length);
alert(sText.substring(5,7));
alert(sText.charAt(5));
alert(sText.indexOf("s"));
//
//
//
//
11
"st"
"s"
2
// string separation
var sNames = "Peter,Tim,Frank,Andreas";
var aNames = sNames.split(",");
// "Peter", "Tim", "Frank", "Andreas"
// string transformation
alert("JavaScript".toUpperCase());
charAt
charCodeAt
concat
fromCharCode
indexOf
lastIndexOf
match
replace
search
slice
split
substr
substring
toLowerCase
toUpperCase
valueOf
// JAVASCRIPT
96
Goal
Implement Caesar's cipher (the shift cipher)
Method
Use as starter code P22_JS_Primitive_Data_Types_Exercise_1
Task
In Caesar's cipher, each character is shifted by a certain offset
Consider charCodeAt(), fromCharCode(), and %
Use a for loop, e.g. for (var i = 0; i < n; i++) { }
Test the cipher for the alphabet with different offsets
Duration
15 minutes
98
JavaScript Objects
RegExp Regular Expression Object: Pattern Matching and Search & Replace
100
Objects
// object literal
var oObjLiteral = {};
// object
var oObject = new Object();
// dot notation
oObject.property;
oObject.method([parameter]);
// square bracket notation
oObject["property"];
oObject["method"]([parameter]);
// adding a property to an object
oObject.newProperty = "Property Value";
// adding a new method to an object
oObject.newMethod = function() { /* impl */ };
// deleting properties or methods
delete oObject.newMethod;
101
Objects (Map)
// value1
alert(oMap["key3"]);
// value3
102
Arrays
// array literal
var aArrLiteral = [];
var aArrLiteral1 = [1, 2, 3, 4];
// array
var aArray = new Array();
var aArray1 = new Array(1, 2, 3, 4);
// adding values
aArray.push(5, 6, 7, 8);
// accessing values
alert(aArray[0]); // 5
// joining values
alert(aArray.join(" - ")); // "5 - 6 - 7 - 8"
// size of an array
alert(aArray.length); // 4
103
Functions
104
Math
// min
Math.min(1, 2);
// 1
// max
Math.max(1, 2);
// 2
// PI
Math.PI
// 3.14
// round
Math.round(Math.PI);
// 3
// random
Math.random();
// 0..1
105
Date
// today
var d = new Date();
// day of the month (from 1-31)
d.getDate();
106
Goal
Get familiar with array operations
Method
Use the start up code from P23_JS_Reference_Types_Exercise_1
Task
Write the function insertAfter
It takes an array, an element, and a list of new elements
The new elements are inserted after the given element
If the given element does not occur, the array does not change
Consider the use of the array indexOf and splice functions
Duration
15 minutes
107
JavaScript Operators
Operators
// assignment operator
=
// logic operators
&&, ||, !
// bit operators
>>, <<, &, |, ^, ~
// comparison operators
==, !=, >, <, >=, <=, ===, !==
// calculation operators
+, -, *, /, %, ++, --
// void operator
void
// delete operator
delete
109
alert("1" == 1);
alert("1" === 1);
alert(1 === 1);
// true
// false
// true
// weirdness
alert("1" == true);
alert("0" == true);
// true
// false
// even weirder
alert("" == 0);
// true
110
// number calculation
4 + 5; // 9
// string concatenation
"hello" + " world"; // "hello world
// when "+" is
// numbers the
4 + 5 + "five"
4 + 5 + "five"
111
typeof Operator
// string
var sVar = "Hello World";
alert(typeof sVar);
// string
// number (integer && float)
var iVar = 1234;
alert(typeof iVar);
// number
var fVar = 12.34;
alert(typeof fVar);
// number
// boolean
var bVar = true;
alert(typeof bVar);
// boolean
// function
var fnAdd = function(a, b) { return a + b; };
alert(typeof fnAdd);
// function
112
// string
var oString = new String("Hello World);
alert(typeof oString );
// object
alert(oString.constructor === String); // true
// number (integer && float)
var oInt = new Number(1234);
alert(typeof oInt );
alert(oInt.constructor === Number);
var oFloat = new Number(12.34);
alert(typeof oFloat);
alert(oFloat.constructor === Number);
// boolean
var oBool = new Boolean(true);
alert(typeof oBool);
alert(oBool.constructor === Boolean);
// object
// true
// object
// true
// object
// true
113
JavaScript Statements
if else condition
// default
if (condition) {
// impl when true;
} else {
// impl when false;
}
// checking defined objects
if (object) {
// do something
}
115
switch command
switch (var) {
case value1:
// impl;
break;
case value2:
// impl;
break;
default:
// impl;
}
116
while loop
while (condition) {
// loop impl
}
117
do while loop
do {
// loop impl
} while (condition);
118
for loop
119
for in loop
var oObject = {
key1: "value1",
key2: "value2"
};
for (var sKey in oObject) {
var oProp = oObject[sKey];
}
var aArray = [
"value1", "value2"
];
for (var iIndex in aArray) {
var oValue = aArray[iIndex];
}
Be aware:
var oObject = {
key1: "value1",
key2: "value2"
};
for (var sKey in oObject) {
if (oObject.hasOwnProperty(sKey)) {
var oProp = oObject[sKey];
}
}
var aArray = [
"value1", "value2"
];
for (var i = 0, l = aArray.length; i < l; i++) {
var oValue = aArray[iIndex];
}
121
Conditional Assignment ( ? : )
var nCount = 0;
var sText = "test";
if (sText=="test") {
nCount += 1;
} else {
nCount -= 1;
}
alert(nCount);
// 1
condition ?
value_if_true :
value_if_false
Do not nest
conditional
assignments since
this makes the code
not readable anymore.
122
Exercise: Statements
Goal
Use a for in loop to copy the properties of an object
Method
Use the start up code from P25_JS_Statements_Exercise_1
Task
Create an object literal
Add some properties (remember concept object as a map)
Use a for in loop to copy the properties into an array
Output the array
Duration
15 minutes
123
Characteristics
125
Goal
Get familiar with the concept of a closure
Method
Use the starter code from P26_JS_Variables_Scope_Exercise_1
Task
Write a (outer) function that returns a (inner) function
The outer function takes one argument, say n
The returned inner function also takes one argument, say x
The inner function returns x+n
Define several of those adders and test them
Duration
15 minutes
126
Since JavaScript native errors are quite unspecific, consider the use of user
defined error objects
128
Throw an error by using the throw operator and providing an object to throw
Any type of object can be thrown; an Error object is the most typical to use
129
130
131
132
Best Practice
133
The use of internal or private functions is known and thus they should be tested during
development
Functions making up the public interface or API should implement arguments checking
and signal wrong use to the caller
Avoid throwing errors from deep below the call stack, since this forces your user to
understand the details of your implementation
Consider to catch those errors in the public interface and eventually throw them again
more digestible to the caller
134
Description
Error
Base type for all errors; never actually thrown by the engine
EvalError
RangeError
ReferenceError
SyntaxError
Thrown when the code passed into eval() has a syntax error
TypeError
URIError
135
Error Handling
try {
someFunction();
} catch (error){
if (error instanceof TypeError){
// Handle type error
} else if (error instanceof ReferenceError){
// Handle reference error
} else {
// Handle all other errors
}
}
136
Do not leave catch clauses empty, since this does not handle errors but just
masks them
On the contrary, do not expose each and every technical exception to the user
Target design:
137
138
Browser attaches extra information to the error objects when they are thrown
2014 SAP AG. All rights reserved.
139
Debugging Techniques
console.log("Error");
140
Goal
Get familiar with common error situations
Method
Use the starter code from P27_JS_Error_Handling_Exercise_1
Task
Replace '___' by proper code to handle the errors situations
Replace 'e.name' by more descriptive member of the error object
Write equivalent code using instanceof
Duration
15 minutes
141
Selecting Elements
By ID
getElementById("col1");
By name
getElementsByName
By tag name
getElementsByTagName
HTML5 method
var selected = document.querySelector(".selected");
143
Tree Nodes
Create an Attribut
Create an Element
var el = document.createElement("h1");
var txt = document.createTextNode("Content");
el.appendChild(txt);
var content_section = document.getElementById("col1");
content_section.appendChild(el);
144
JavaScript Events
Handler Types
146
var EventManager = {
addHandler: function(element, type, handler){
if (element.addEventListener){
element.addEventListener(type, handler, false);
} else if (element.attachEvent){
element.attachEvent("on" + type, handler);
} else {
element["on" + type] = handler;)};
EventManager.addHandler(el,"click",handler);
147
The concept of event bubbling was introduced to deal with situations where a
single event, such as a mouse click, may be handled by two or more event
handlers defined at different levels of the Document Object Model (DOM)
hierarchy
If this is the case, the event bubbling process starts by executing the event
handler defined for individual elements at the lowest level (e.g. individual
hyperlinks, buttons, table cells etc.)
From there, the event bubbles up to the containing elements (e.g. a table or a
form with its own event handler), then up to even higher-level elements (e.g. the
BODY element of the page)
Finally, the event ends up being handled at the highest level in the DOM
hierarchy, the document element itself (provided that your document has its own
event handler)
148
If you want to suppress it, set the event property cancelBubble to true
149
However, strictly speaking, event propagation is a wider term: it includes not only
event bubbling but also event capturing
Event capturing is the opposite of bubbling (events are handled at higher levels
first, then sink down to individual elements at lower levels)
Event capturing is supported in fewer browsers and rarely used; notably, Internet
Explorer prior to version 9.0 does not support event capturing
150
Goal
Get familiar with adding event handlers to push buttons
Method
Use code from P29_JS_Events_Exercise_1.html
Task
Add an HTML event handler to the first button
Add a DOM Level 0 event handler to the second button
Add two DOM Level 2 event listeners to the third button
Easy reaction is to send an alert popup or to change innerHTML
Test
Duration
15 minutes
151
Constructor Functions
153
Object Properties
function Employee() {
this.property = "propValue";
this.method = function () {};
}
var myEmployee1 = new Employee();
var myEmployee2 = new Employee();
myEmployee1.myAttr = "test";
myEmployee2.myFunc = function() {};
alert(myEmployee1.property);// "propValue"
alert(myEmployee2.property);// "propValue"
alert(myEmployee1.myAttr);
alert(myEmployee2.myAttr);
// "test"
// "undefined"
alert(myEmployee1.myFunc);
alert(myEmployee2.myFunc);
// "undefined"
// "function"
154
Objects can be created on demand and properties and methods will be added
as required.
New objects are not empty. It contains some properties and methods but they
are not own properties or methods.
With prototype chains you can define an inheritance chain for JavaScript
objects.
155
// "test"
// "test"
myEmployee1.myFunction();
myEmployee2.myFunction();
// "yo!"
// "yo!"
156
157
158
Inheritance (1)
159
Inheritance (2)
160
Inheritance (3)
161
Exercise: Inheritance
Goal
Build an inheritance hierarchy for shapes, circles, and squares
Method
Use code from P30_JS_OOP_Exercise_1
Task
Create constructor functions for shapes, circles, and squares
Every shape has center coordinates
In addition, a circle has a radius, and a square has a side length
Chain the prototypes
Add a function to output information about each shape
Add further functions to output the area for circles and squares
Duration
30 minutes
2014 SAP AG. All rights reserved.
162
Exercise: Inheritance
163
Synchronous Request
165
Asynchronous Request
166
167
168
Goal
Dynamically modify the page content by issuing an HTTP request
Method
Use starter code from P31_JS_HTTP_Requests_AJAX_Exercise_1
Task
Create an HTML page with a button and span tag
Create a data file with one text line to be read by the request
On button press, issue an asynchronous HTTP request
Replace the content of the span tag with the response
Test
Duration
30 minutes
Expected
outcome of
exercise
169
Traditionally API docs come from the Java word (the javadoc utility)
The special syntax consists of a dozen or so tags, which look like this
/**
* @tag value
*/
171
172
Description
@namespace
@class
@method
@param
@return
@constructor
173
Unit Summary
174
UNIT 3
Foundations of
JQuery
176
177
Lesson Objectives
178
JQuery Introduction
jQuery Essentials
180
JavaScript Frameworks
Dojo 1.7
Download: http://dojotoolkit.org/
Documentation: http://dojotoolkit.org/documentation/
YUI
Download: http://yuilibrary.com/
Documentation: http://yuilibrary.com/yui/docs/guides/
Ext JS 4
Download: http://dev.sencha.com/deploy/ext-4.0.0/
Documentation: http://docs.sencha.com/ext-js/4-0/
Comparison Table
http://en.wikipedia.org/wiki/Comparison_of_JavaScript_frameworks
181
Documentation
http://docs.jquery.com/Main_Page
182
Books
Jonathan Chaffer: Learning jQuery, Third Edition; 2011, Packt Publishing
Dan Wellman: jQueryUI; 2011, Packt Publishing
Internet
http://jquery.com/
http://jqueryui.com/
http://docs.jquery.com/Tutorials
Videos about jQuery
http://www.youtube.com/playlist?list=PL0EFA1232C66601D7
http://www.video2brain.com/de/videotraining/jquery
183
184
Goal
Using jQuery, let a push button a box fade in and out
Method
Use starter code from P41_jQuery_Introduction_Exercise_1
Task
Add the jQuery call when the page (i.e. the document) is ready
Add a Boolean variable which tracks the visibility of the box
Add a click handler for the push button
If the box is visible, let it fade out and set the visibility to false
If the box is hidden, let it fade in and set the visibility to true
Test
Duration
15 minutes
2014 SAP AG. All rights reserved.
185
Selector Types
Selector
Type
CSS
jQuery
What it does
Tag Name
p { }
$('p')
ID
#some-id { }
$('#some-id')
Class
.some-class { }
$('.some-class')
187
Resources
CSS Selectors
You can use most of the CSS-Selectors
http://api.jquery.com/category/selectors/basic-css-selectors/
Attribute Selectors
http://api.jquery.com/category/selectors/basic-css-selectors/
jQuery Selectors
http://api.jquery.com/category/selectors/jquery-selector-extensions/
188
Goal
Style a document using jQuery tag name, ID, and class selectors
Method
Use starter code from P42_jQuery_Selecting_Elements_Exercise_1
Task
All pre tags shall get klass1 attached
All elements of class subsequent shall also belong to klass2
The element with ID stanza3 shall get klass3 attached
Test
Duration
15 minutes
189
JQuery Events
$(document).ready(function(){});
Shorthand notation
$(function(){});
http://api.jquery.com/ready/
http://api.jquery.com/category/events/document-loading/
191
Mouse Events
You can bind an event handler to elements with .bind()
$('#foo').bind('click', function() {});
http://api.jquery.com/bind/
Shorthand-Notations
$("#target").click(handler);
http://api.jquery.com/category/events/mouse-events/
Keyboard Events
http://api.jquery.com/category/events/keyboard-events/
192
Mouse Events
Goal
Implement the click handler for a push button
Method
Use code from P43_jQuery_Events_Exercise_1
Task
Implement the event handler for the push button
When the button is clicked, some text in the
paragraph shall appear
Test
Duration
15 minutes
Expected
outcome of
exercise
193
Styling
Basic Styling
Defining CSS-Properties
$(this).css( "width", "200px" );
$(this).css({"width": "200px, height: 300px} );
http://api.jquery.com/css/#css2
195
Animation
http://api.jquery.com/category/effects/basics/
Fading in and out
http://api.jquery.com/category/effects/fading/
Custom animations
$('#book').animate({
width: '200',
left: '+=50'
}, 5000, function() {
// Animation complete.
});
http://api.jquery.com/animate/
196
Goal
Implement a font size switch
Method
Use code from
P44_jQuery_Styling_Animation_Exercise_1
Task
Complete the event handlers
The button Smaller decreases the font size by
1px
The button Larger increases the font size by
1px
Test
Duration
15 minutes
Expected
outcome of
exercise
197
Goal
Animate a box
Method
Use code from P44_jQuery_Styling_Animation_Exercise_2
Task
Implement a toggle handler for the push button
In the first toggle callback, first increase the width, then the height
In the second callback, decrease height and width to original values
Use chained animate calls for this purpose
Test
Duration
15 minutes
Expected
outcome of
exercise
198
DOM Manipulation
Changing attributes
$(img).attr('title', 'Dolphin');
http://api.jquery.com/category/manipulation/general-attributes/
http://api.jquery.com/category/manipulation/dom-insertion-outside/
http://api.jquery.com/category/manipulation/dom-insertion-inside/
200
DOM Manipulation
Wrapping elements
Wrap outside
.wrap() Wraps each element
.wrapAll() Wraps whole group
http://api.jquery.com/category/manipulation/dom-insertion-around/
Changing content
http://api.jquery.com/category/manipulation/dom-replacement/
http://api.jquery.com/category/manipulation/dom-removal/
201
Goal
Get familiar with the principle of jQuery DOM Manipulation
Method
Use the starter code from
P45_jQuery_DOM_Manipulation_Exercise_1
Task
Add an event handler which adds text before the paragraph
Add an event handler which brings the paragraph again in front
Test
Duration
15 minutes
202
Goal
Append to the DOM after reading additional data
Method
Use starter code from P45_jQuery_DOM_Manipulation_Exercise_2
Task
Look at the console output
Loop over all vegetables
For each vegetable, append name and color to the list
Test
Duration
15 minutes
203
JQuery AJAX
<body>
<pre id="req1"></pre>
<script>
$(document).ready(function() {
$.get("files/data.txt", function(data) {
console.log(data);
});
$("#req1").load("files/data.txt");
});
</script>
</body>
2014 SAP AG. All rights reserved.
205
206
Goal
In reaction to button clicks, load different HTML snippets and fill them
into a container to display them (Asynchronous HTTP and HTML)
Method
Use starter code from P46_jQuery_AJAX_Exercise_1
Task
Create an HTML document with snippets or use poems.html
Create another HTML document
Add buttons to load and a container to display the snippets
Write the click handlers using the jQuery load function
Test
Duration
15 minutes
2014 SAP AG. All rights reserved.
Expected
outcome of
exercise
207
JQuery UI
jQuery UI
Download:
Documentation:
http://jqueryui.com/download
http://jqueryui.com/demos/
209
jQuery UI
Widgets
o Accordion
o Autocomplete
o Button
o Date Picker
o Progress Bar
o Slider
o Tabs
210
Data Tables
http://www.datatables.net/
Step 1:
Step 2:
$(document).ready(function(){
$('#example').dataTable();
});
#example references the ID of the table
212
Deferred Object
Deferred Object
Definition
jQuery.Deferred()
chainable utility object
can register multiple callbacks into callback queues
can invoke callback queues
can relay the success or failure state of any synchronous or asynchronous function
Concept
http://en.wikipedia.org/wiki/Futures_and_promises (English)
http://de.wikipedia.org/wiki/Future_%28Programmierung%29 (German)
214
Basic Pattern
(function( $ ) {
$.fn.myPlugin = function() {
// Do your awesome plugin stuff here
};
})( jQuery );
http://docs.jquery.com/Plugins/Authoring
216
Simple Example
(function( $ ){
$.fn.maxHeight = function() {
var max = 0;
this.each(function() {
max = Math.max( max, $(this).height() );
});
return max;
};
})( jQuery );
217
Tooltip Example
http://net.tutsplus.com/tutorials/javascript-ajax/build-a-better-tooltip-with-jqueryawesomeness/
218
Unit Summary
219
UNIT 4
Security
221
Unit 4 Security
Security
Lesson 4: Foundations of HTML, CSS, JavaScript, jQuery Security
222
Lesson Objectives
223
225
226
Web applications accept user input which is used to create executable content in HTML pages
Weakness
Missing output filtering or encoding when writing user input back to HTML pages
Attacker injects client side JavaScript into web pages viewed by himself or others
Potential Consequences
3 Types of XSS
Non persistent or reflected (the most common type): The server receives input data and uses
it to build a result HTML page for the same user, without properly sanitizing the input
Persistent: Input data from a given user is persisted by the server and is included later on in
HTML pages returned to other users, again without proper data sanitization
DOM based: JavaScript DOM manipulation is used to echo input directly in the client, also
without proper data sanitization
227
Reflected XSS
Problem
Web applications accept user input, which is displayed on subsequent HTML pages (either
immediately or some time after)
If user input is not parsed, malicious JavaScript can be injected into HTML pages (which
are a mix of data and code)
Example
228
Stored XSS
The following is an example for all kinds of applications that accept, store and echo user
input, a feature being part of thousands of web pages (e.g., SDN, news pages, bookstores,
etc.)
Attacker
Web Server
Post Forum Message:
.....
GET Money for FREE !!!
Body:
.....
I found a solution!
.....
Can anybody help?
Get /forum.jsp?fid=122&mid=2241
.....
Error message on startup
.....
Client
!!! attack code
!!!
229
General idea
Prevent the injection of executable code in the web page, address the problem that
HTML pages are a mixture of code and data
Validate external input: Ensure that provided input matches to what the
application expects
Encode output: Prevent input from being executable in the HTML page
Avoid to render HTML yourself but use frameworks which employ encoding
230
CSS Injection
Security Warning
Many CSS styles can be used to smuggle a script into your page
Countermeasures
When accepting input for changing style at run time, strictly validate before
inserting untrusted data into an HTML style attribute
Use escaping when untrusted data is inserted inside your CSS styles
231
Security Warning
User friendly web forms leave the impression that only certain value types (e.g.
URLs, email addresses, date or color values) will be sent to the server
However, the attacker can use proper means, such as proxies, to send
arbitrary values
Countermeasure
Perform validation of input received through those type specific form elements
on the server
232
233
Examples
These are from same origin:
http://site.com
http://site.com/my/page.html
2012
2014SAP
SAPAG.
AG.AllAllrights
rightsreserved.
reserved.
234
JavaScript Sandbox
A given JavaScript is only allowed access to pages that share the scripts origin
235
Security Warning
Attacker directly accesses object properties he is not intended to deal with
Attacker changes query string or enhances JSON data
Example
{
"firstName":
Brendan
// exposed to input
"lastName":
Eich
// exposed to input
"accessType": restricted
}
Counter Measures
Filter and validate input before changing object properties
236
Security warning
eval()
innerHTML
document.write()
document.URL: http://www.app.com#<script></script>
document.referrer
237
http://www.example.com/welcome.html?name=Joe
http://www.example.com/welcome.html?name=<script>alert(docum
ent.cookie)</script>
238
Security Warning
Improper use of the innerHTML property can enable script injection attacks
Example
239
Countermeasure
When accepting text from an untrusted source (such as the query string of a
URL), use createTextNode to convert the HTML to text, and append the
element to the document using appendChild
When only dealing with text it is recommended to not use innerHTML, but
rather textContent which will not interpret the passed string as HTML, but
as plain text
240
Security Warning
The use of eval() for JSON parsing could lead to XSS via JSON injection
Example
If the attacker is able to inject, for example, a quote sign, he can break out of
the JavaScript string surrounding the value and exploit the XSS through the
eval function
"name":"Foo "+alert(/XSS/.source)+"Bar"
Security Recommendations
For older browsers that do not natively provide the JSON functions use the
open source JavaScript library json.js (http://www.json.org/js.html)
241
Security Warning
New browsers support the XMLHttpRequest object
With the introduction of HTML5, Cross Origin Resource Sharing (CORS) enables
to share content in between different domains/origins
Example
Imagine the site alice.com has some data that the site bob.com wants to
access
This type of request traditionally would not be allowed under the Same Origin
Policy (SOP). However, by supporting CORS requests, alice.com can add a
few special response headers that allows bob.com to access the data
Security Recommendations
URLs passed to XMLHttpRequest.open shall be validated for code injection
242
Security Warning
CDN is not under control of SAP
It is not known if the delivered JavaScript code is safe
243
Security Warning
Insecure writes happen when user input is written to the DOM without first being sanitized
Insecure writes means we are either outputting the data directly in the DOM using
.innerHTML or through potentially unsafe jQuery functions
$.after()
$.append()
$.appendTo()
$.before()
$.html()
$.insertAfter()
$.insertBefore()
$.prepend()
2014 SAP AG. All rights reserved.
$.prependTo()
$.replaceAll()
$.replaceWith()
$.unwrap()
$.wrap()
$.wrapAll()
$.wrapInner()
$.prepend()
244
https://wiki.wdf.sap.corp/wiki/display/PSSEC/Home
https://wiki.wdf.sap.corp/wiki/display/NWCUIAMSIM/Home
https://wiki.wdf.sap.corp/wiki/display/NWCUIAMSIM/XSS+Secure+Programming+Guide
https://www.owasp.org/index.php/Main_Page
http://cwe.mitre.org/
HTML5 Security
http://html5security.org
245
Unit Summary
246