Você está na página 1de 246

SAPX04

<Course Number and Course Title ABC123 Overiew>


HTML5 Foundations for SAP
SAPUI5 Development

SAP SAPGUI5
Training System: Windows 2008 R2 with latest SAPUI5 component)
Collection 95

2014 SAP AG. All rights reserved.

2014 SAP AG. All rights reserved.

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.

2014 SAP AG. Alle Rechte vorbehalten.

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.

Die von SAP AG oder deren Vertriebsfirmen angebotenen Softwareprodukte knnen


Softwarekomponenten auch anderer Softwarehersteller enthalten.

INTERMEC ist eine eingetragene Marke der Intermec Technologies Corporation.

Microsoft, Windows, Excel, Outlook, PowerPoint, Silverlight und Visual Studio sind
eingetragene Marken der Microsoft Corporation.

Bluetooth ist eine eingetragene Marke von Bluetooth SIG Inc.

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.

2014 SAP AG. All rights reserved.

Wi-Fi ist eine eingetragene Marke der Wi-Fi Alliance.


Motorola ist eine eingetragene Marke von Motorola Trademark Holdings, LLC.
Computop ist eine eingetragene Marke der Computop Wirtschaftsinformatik GmbH.
SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP BusinessObjects Explorer,
StreamWork, SAP HANA und weitere im Text erwhnte SAP-Produkte und -Dienstleistungen sowie die entsprechenden Logos sind Marken oder eingetragene Marken der
SAP AG in Deutschland und anderen Lndern.
Business Objects und das Business-Objects-Logo, BusinessObjects, Crystal Reports,
Crystal Decisions, Web Intelligence, Xcelsius und andere im Text erwhnte BusinessObjects-Produkte und Dienstleistungen sowie die entsprechenden Logos sind Marken
oder eingetragene Marken der Business Objects Software Ltd. Business Objects ist ein
Unternehmen der SAP AG.
Sybase und Adaptive Server, iAnywhere, Sybase 365, SQL Anywhere und weitere im Text
erwhnte Sybase-Produkte und -Dienstleistungen sowie die entsprechenden Logos sind
Marken oder eingetragene Marken der Sybase Inc. Sybase ist ein Unternehmen der
SAP AG.
Crossgate, m@gic EDDY, B2B 360, B2B 360 Services sind eingetragene Marken
der Crossgate AG in Deutschland und anderen Lndern. Crossgate ist ein Unternehmen
der SAP AG.
Alle anderen Namen von Produkten und Dienstleistungen sind Marken der jeweiligen
Firmen. Die Angaben im Text sind unverbindlich und dienen lediglich zu Informationszwecken. Produkte knnen lnderspezifische Unterschiede aufweisen.
Die in dieser Publikation enthaltene Information ist Eigentum der SAP. Weitergabe und
Vervielfltigung dieser Publikation oder von Teilen daraus sind, zu welchem Zweck und
in welcher Form auch immer, nur mit ausdrcklicher schriftlicher Genehmigung durch
SAP AG gestattet.

Course Topics

This course covers:

HTML5 for SAPUI5 Essentials


Creation of HTML and CSS styles
JavaScript Development
jQuery Development

2014 SAP AG. All rights reserved.

Course Description

This course is designed to give participants the opportunity to gain an


understanding of HTML5 by introducing the basics of web programming
techniques using HTML5, CSS3, JavaScript, and jQuery.

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.

2014 SAP AG. All rights reserved.

Course Goals

This course will prepare you to:


Understand and practice the basics of web programming technique:
HTML5, CSS3, JavaScript, and jQuery
Describe and understand the basics of security in web programming
languages

2014 SAP AG. All rights reserved.

Course Objectives

After completing this course, you will be able to:


Create web pages using basic HTML5 and CSS3
Make web pages more lively through JavaScript programming
Further improve web pages by using parts of jQuery and jQueryUI

2014 SAP AG. All rights reserved.

Course Prerequisites
Required Knowledge (Essential)

Basic web skills and experiences such as working with a browser


Experience with files and folders, editing source code, using an
integrated development environment
Basic knowledge on what programming is about and willingness to
write code

Recommended

None

2014 SAP AG. All rights reserved.

Target Audience & Course Duration

This course is intended for the following audiences:

Developers
Technology Consultants
Product owners and consultants looking for an in-depth overview of
web development

Duration: 2 days

2014 SAP AG. All rights reserved.

Course Content
Content:
Unit 1 Foundations of HTML5 & CSS
Unit 2 Foundations of JavaScript
Unit 3 Foundations of JQuery
Unit 4 Security

2014 SAP AG. All rights reserved.

10

Course Outline and Schedule


Preface
Day 1:
Welcome & Introductions
UNIT 1 Foundations of HTML5 & CSS

Lesson 1: HTML5 and CSS3 Essentials

UNIT 2 Foundations of JavaScript

Lesson 2: Essentials of the JavaScript Language

2014 SAP AG. All rights reserved.

11

Course Outline and Schedule


Preface

Day 2:
Unit 3 Foundations of JQuery

Lesson 3: JQuery Foundations

UNIT 4 Security

Lesson 4 - Foundations of HTML, CSS, JavaScript, jQuery Security

2014 SAP AG. All rights reserved.

12

UNIT 1
Foundations of HTML5
& CSS

Unit 1 Foundations of HTML5 & CSS:


Unit Objectives

After completing this unit, you will be able to:

Describe and write HTML5 and CSS code

2014 SAP AG. All rights reserved.

14

Unit 1 Foundations of HTML5 & CSS:


Unit Lessons
Foundations of HTML5 & CSS
Lesson 1: HTML5 and CSS3 Essentials

2014 SAP AG. All rights reserved.


SAP 2014 /

15

Lesson Objectives

After completing this lesson, you will be able to:

Describe and write HTML5 and CSS code

2014 SAP AG. All rights reserved.

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

Font Style, Size, and Color


Layout of the Sematic Blocks
Transitions, Animations

JavaScript

Programming Language
Page Dynamics
Behavior of the Page

Popup Windows
Event Handlers for Buttons
DOM Manipulation
AJAX and related Techniques

jQuery
jQueryUI

Streamlining of Common Tasks


JavaScript Libraries
Reusable UI Blocks
Best Practice Solutions
Domain Specific Language Browser Independency

2014 SAP AG. All rights reserved.

18

What is HTML5?

Next generation of HTML superseding HTML 4.01, XHTML 1.0, XHTML 1.1

Standardizes features of the web platform

Designed to be cross-platform like its predecessors

Defines new tags and markup

Describes new JavaScript APIs

Deprecates or redefines some so far common elements

Supported to a wide extent by the latest versions of Opera, Chrome,


Firefox, and, to a lesser extent, by IE9

2014 SAP AG. All rights reserved.

19

What does HTML5 contain?


Class

Examples

Semantics

Giving meaning to structure, data driven web

Offline & Storage

Local Storage, Indexed DB, File API

Device Access

Geo Location, Audio/Video Input Access

Connectivity

Web Sockets, Pushing Data from the Client

Multimedia

Audio and video are first class citizens in the HTML5

3D, Graphics & Effects

SVG, Canvas, WebGL, and CSS3 3D

Performance & Integration

Web Workers, XMLHttpRequest2

CSS3

Wide range of stylization and effects, enhancing the


web app without sacrificing your semantic structure
or performance

2014 SAP AG. All rights reserved.

(Source: http://www.w3.org/html/logo/)

20

Basic HTML 5 Page Template

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Basic HTML 5 Page Template</title>
</head>
<body>
<!-- Body Content -->
</body>
</html>

Regarding charset see e.g. http://webdesign.about.com/od/metatags/qt/meta-charset.htm

2014 SAP AG. All rights reserved.

21

Know Your Browser

Some special URIs (http://en.wikipedia.org/wiki/URI_scheme)

about:

Shows version information and copyright


information

about:about

Lists all the 'about:' URIs

about:blank

Shows a blank HTML document

view-source:

Shows a web page as code 'in the raw'

file:

Addressing files on local or network file


systems

2014 SAP AG. All rights reserved.

22

Useful Tools

Validate your HTML


http://validator.w3.org

Validate your CSS


http://jigsaw.w3.org/css-validator

Online version of a complete HTML and CSS Guide


http://webkompetenz.wikidot.com/docs:html-handbuch
http://www.selfhtml.org

Try all HTML elements and CSS properties


http://www.w3schools.com/html5/default.asp

2014 SAP AG. All rights reserved.

23

Additional Information

The W3C maintains an HTML5 landing page


http://www.w3.org/html/logo/

The W3C has released a Web Developer's Guide about HTML5


http://dev.w3.org/html5/html-author/
All about HTML5 can be read in the specification
http://www.w3.org/TR/html5/
On the website http://html5doctor.com you can find a brief discussion on the use
of any HTML5 element; if you are not sure whether an item was marked up
correctly, this is the place to look it up
Microsoft also offers a web site about HTML5
http://html5labs.interoperabilitybridges.com/

2014 SAP AG. All rights reserved.

24

Installation of the SAPUI5 Development Environment

Get familiar with the structure of the provided training material

Download link for the SAPUI5 Developer Studio (Eclipse based)

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

2014 SAP AG. All rights reserved.

25

Exercise: Lab Environment Setup 1

Launch Eclipse from Start All Programs


eclipse eclipse.

When the Workspace Launcher dialog window


appears, enter the workspace N/workspace
and tick the check box Use this as the default
and do not ask again.
If you change your default project location,
make a note of it.

2014 SAP AG. All rights reserved.

26

Lab Environment Setup 2

Close the Welcome tab.

Go to File Import.

In the Import window that


appears, select General
Existing Projects into Workspace
and then choose Next.

2014 SAP AG. All rights reserved.

27

Lab Environment Setup 3

On the current window, click Select root


directory and click Browse

On the next window, navigate to the


Application (N:) drive
SAPX04_95\Modul_1_HTML and select
as root directory.

Click OK.
2014 SAP AG. All rights reserved.

28

Lab Environment Setup 4

Make sure that all


projects appearing in the
Projects area are ticked,
and press Finish

Verify that your Eclipse


Project explorer looks
similar to the following:

2014 SAP AG. All rights reserved.

29

Total View

Expand the
Modul_1_HTML_
Practice folder to
view all directories
& files and confirm

Note that your start


up project files are
all in the exercises
folder
Also note that
there is a
solutions folder
containing all
the code
solutions

2014 SAP AG. All rights reserved.

30

Installing the Firebug Add-on in FireFox (1)

Launch FireFox and


make sure you are on
the Start Page

Click the Add-ons icon


at the bottom of the
browser:
This will launch the
Add-ons Manager.

Use the search field to


search for the Firebug
Add-on.

Install it by means of the


corresponding Install
button:
2014 SAP AG. All rights reserved.

31

Installing the Firebug Add-on in FireFox (2)

Upon installation, note the new tab and the change in status:

Close all tabs.

2014 SAP AG. All rights reserved.

32

Setup for Debugging with FireBug

Make sure that your Firebug Console is


activated/enabled by going to FireFox and click the
FireBug and set to On for All Web Pages:

Enable the Console and click All, as you see in the


screen shot example below:

2014 SAP AG. All rights reserved.

33

Exercise: Basic HTML Page


Goal
Write an HTML page showing a push button and an
alert popup
Method
Go to Eclipse
Expand the exercises folder in your project*
Use the code from
P02_HTML_Essentials_Exercise_1
Task
Copy or create the HTML page skeleton
Add a push button to the body section
Add an event handler for button onclick
Use an alert popup as the event handler
Test the webpage using FireFox (see next slide to
enable FireBug)
Duration

* Note that there is


also a solutions folder
containing completed
code in case you
need help

15 minutes
2014 SAP AG. All rights reserved.

34

CSS3 Essentials

Connecting Stylesheets to HTML

<!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>

2014 SAP AG. All rights reserved.

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 {}

2014 SAP AG. All rights reserved.

37

Basic Selectors

Class Selector
The class selector matches on the value of class attributes

<p class="topNavigation">paragraph</p>
.topNavigation {}

The Descendant Selector


A descendant selector of the form "A B" matches when an element B is an
arbitrary descendant of some ancestor element A
table td {}

2014 SAP AG. All rights reserved.

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

Original CSS Reset from meyerweb

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;
}

2014 SAP AG. All rights reserved.

40

CSS Box Model

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/

2014 SAP AG. All rights reserved.

41

Working with Browser Tools

Use function button F12 in browser

Firebug plugin for Firefox, no install for Chrome and IE

2014 SAP AG. All rights reserved.

42

Exercise: Basic CSS Selectors and Properties

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

2014 SAP AG. All rights reserved.

43

CSS3 Special Features Gradients,


Shadows and Corners

Linear Gradients
Linear Gradient
background: -moz-linear-gradient(left, blue, white);
background: -webkit-linear-gradient(left, blue, white);

Linear Gradient with Angle


background: -moz-linear-gradient(90deg, red, white);
background: -webkit-linear-gradient(90deg, red, white);

Linear Gradient with Color Stops


background: -moz-linear-gradient(top, blue, white 80%, orange);
background: -webkit-linear-gradient(top, blue, white 80%, orange);

Linear Gradient with Transparency


background: -moz-linear-gradient(left, rgba(255,255,255,0),
rgba(255,255,255,1)), url(img/bg_landscapeFooter.png);
background: -webkit-linear-gradient(left, rgba(255,255,255,0),
rgba(255,255,255,1)), url(img/bg_landscapeFooter.png);
2014 SAP AG. All rights reserved.

45

Box Shadows
Color and Blur
box-shadow: 8px 8px lightgrey;
box-shadow: 8px 8px 4px lightgrey;

Spread and Blur


box-shadow: 8px 8px 0px 4px lightgrey;
box-shadow: 8px 8px 4px 4px lightgrey;

No Offset and Inset


box-shadow: 0px 0px 4px cyan;
box-shadow: inset 0px 0px 4px cyan;
#box11:hover {
box-shadow: 0px 0px 4px cyan;
}

2014 SAP AG. All rights reserved.

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;

2014 SAP AG. All rights reserved.

47

Exercise: Design of a Form

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

Using HTML5 Semantic Markup

(New) Structural Semantic Tags

<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

2014 SAP AG. All rights reserved.

50

Exercise: Define a Blog Using Semantic Markup


Goal
Use the new structural tags und style the resulting page
Method
Use the code from P04_HTML_Semantic_Markup_Excerise_1
Task
Create an HTML page
Add a header, a footer, and two sections for posts and a sidebar
Add horizontal navigation areas to both, the header and the footer
Add an article with an aside to the posts section
Add a vertical sidebar menu
Style the page
Test the webpage
Duration
30 minutes

2014 SAP AG. All rights reserved.

51

Exercise: Define a Blog Using Semantic Markup

You tested page


should appears as
follows:

2014 SAP AG. All rights reserved.

52

User-Friendly Web Forms

Survey of Input Types

Best supported in Opera and Chrome

<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

2014 SAP AG. All rights reserved.

54

Survey of Input Types

<input type="url">
Displays a form field for URLs

<input type="color">
Displays a form field for specifying colors

<input type="text" name="name" autofocus id="name">


Jump to the first field with autofocus.

2014 SAP AG. All rights reserved.

55

Providing Hints with Placeholder Text

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" />

2014 SAP AG. All rights reserved.

56

Exercise: User-Friendly Web Forms

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

Exercise: User-Friendly Web Forms

You tested page should appears as follows:

2014 SAP AG. All rights reserved.

58

Working with HTML5 Custom


Attributes

Custom Attributes (data- Attributes)

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>

2014 SAP AG. All rights reserved.

60

JavaScript API

A simple JavaScript API is presented to access these attribute values

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 "}

user.addEventListener( "click", function(){


var phrase = phrases[ pos++ ];
// Use the .dataset property
span.innerHTML = phrase.prefix + user.dataset[ phrase.name ];
}, false);
2014 SAP AG. All rights reserved.

61

Exercise: Custom Data Attributes

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

2014 SAP AG. All rights reserved.

62

Styling Tables with HTML5


Pseudoclasses

Pseudoclasses

:nth-child(n)
The :nth-child(n) selector matches every element that is the nth child, regardless
of type, of its parent

n can be a number, a keyword, or a formula (e.g. 2, even, odd, or 2n+3)


:nth-of-type(n)
The :nth-of-type(n) selector matches every element that is the nth child, of a
particular type, of its parent
:last-child
The :last-child selector matches every element that is the last child of its parent
:nth-last-child(n)
The :nth-last-child(n) selector matches every element that is the nth child,
regardless of type, of its parent, counting from the last child

2014 SAP AG. All rights reserved.

64

Exercise 1: Styling Tables with Pseudoclasses

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

Exercise 1: Styling Tables with Pseudoclasses

You tested page should


appears as follows:

2014 SAP AG. All rights reserved.

66

Exercise 2: Reacting to Mouse Events

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

Exercise 3: Deletion of Table Rows

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

2014 SAP AG. All rights reserved.

68

Exercise 3: Deletion of Table Rows

Example of deletions:

2014 SAP AG. All rights reserved.

69

CSS Floats

The Definition

Definition of a float according to the W3C


A float is a box that is shifted to the left or right on the current line. The most
interesting characteristic of a float (or floated or floating box) is that content
may flow along its side (or be prohibited from doing so by the clear property).
Content flows down the right side of a left-floated box and down the left side of
a right-floated box.
http://www.w3.org/TR/CSS2/visuren.html#floats

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

How Elements Float

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.

The elements before the floating element will not be affected.

If an image is floated to the right, a following text flows around it, to the left.

Turning off Float Using Clear

Elements after the floating element will flow around it. To avoid this, use the
clear property.

The clear property specifies which sides of an element other floating


elements are not allowed.

2014 SAP AG. All rights reserved.

72

Building a Full CSS Layout

Reference: http://www.maxdesign.com.au/articles/process/
2014 SAP AG. All rights reserved.

73

Building a Full CSS Layout

Step 1 Make your layout idea explicit


It could be in the form of a digital mockup, a sketch on paper or an existing site or
template

Step 2 Look for the containers


To position elements on the page, the overall containers need to be established
Look at your design and work out the main containers on the page

Step 3 Name the containers


Identify container, header, footer, main navigation, menu, content,

Step 4 Create the HTML mark up


Use semantic markup and ID attributes whenever possible

Step 5 Position the overall containers with CSS rules


The positioning of the containers gives the skeleton of the CSS style sheet

Step 6 Style the elements in detail


Decide on the use of colors, fonts, decorations, images, link behavior, mouse effects,
Reference: http://www.maxdesign.com.au/articles/process/
2014 SAP AG. All rights reserved.

74

Exercise 1: CSS Floats Two Column Layout

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

2014 SAP AG. All rights reserved.

75

Screen Shot for Exercise 1

2014 SAP AG. All rights reserved.

76

Exercise: CSS Floats Thumbnail Gallery

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

Screen Shot for Exercise 2

2014 SAP AG. All rights reserved.

78

Unit Summary

After completing this unit, you should now be able to:

Describe and write HTML5 and CSS code

2014 SAP AG. All rights reserved.

79

UNIT 2
Foundations of
JavaScript

Unit 2 Foundations of JavaScript: Unit Objectives

After completing this unit, you will be able to:


Describe the JavaScript Language
Write JavaScript code

2014 SAP AG. All rights reserved.

81

Unit 2 Foundations of JavaScript: Unit Lessons


Foundations of JavaScript
Lesson 2: Essentials of the JavaScript Language

2014 SAP AG. All rights reserved.

82

Lesson Objectives

After completing this lesson, you will be able to:


Describe the JavaScript Language
Write JavaScript code

2014 SAP AG. All rights reserved.

83

JavaScript Language Basics

First Example: HTML and JavaScript

<!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!");

2014 SAP AG. All rights reserved.

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.

o The page loading will not be halted while JavaScript is processed


o HTML elements will be available

Do not use the defer Attribute. It only works in IE and Firefox.

2014 SAP AG. All rights reserved.

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 */

Use a documentation generator


JSDoc Toolkit
http://www.jsdoctookit.org

YUI Doc
http://developer.yahoo.com/yui/yuidoc

2014 SAP AG. All rights reserved.

87

Variables

Use the var keyword


o If you omit the var keyword, you automatically create a global variable
o JavaScript is loosely typed, change of type is always possible
o Multiple definitions are possible

Statements
o One statement per line
o All statements should end with a semicolon
o Keep your code clean and readable

2014 SAP AG. All rights reserved.

88

Alternatives and Further Developments


Language

Developer

Remarks

CoffeeScript

Open Source

http://coffeescript.org/

Dart

Google

http://code.google.com/p/dart/

TypeScript

Microsoft

http://www.typescriptlang.org/

Node

Open Source

http://nodejs.org/

2014 SAP AG. All rights reserved.

89

Resources

Documentation of ECMA-262
http://www.ecmascript.org/docs.php

SELFHTML
http://de.selfhtml.org/

Mozilla Developer Network


https://developer.mozilla.org/en/JavaScript

Using Style Guides


http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml

JavaScript Tutorials
http://www.w3schools.com/js/default.asp

Interactive Environment
http://eloquentjavascript.net/paper.html

2014 SAP AG. All rights reserved.

90

Exercise: Embed JavaScript into an HTML Page

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

JavaScript Primitive Data Types

Comments and Variables

// this is a comment

There are 2 types of JavaScript


comments a single line comment
and a block comment

By using the keyword var you begin


the declaration of a variable (no type
is required since JavaScript is
dynamic)

To specify more than one variable you


can separate them via comma.

A good practice is to use Hungarian


notation for naming variables. You can
find some hints in Wikipedia.

/* this is a
block comment */
// variable declaration
var iMyVariable = 12;
// multi variable declaration
var iVar1 = 0, sVar2 = "Hello";

2014 SAP AG. All rights reserved.

93

Basic Data Types

// 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;

2014 SAP AG. All rights reserved.

A string value can be specified either


via double or single quotes. In each
case the surrounding quotes are the
leading one and the other quotes can
be used within the string value.

A number can be either an integer or


a float. By using the dot you can
define the variable to be a float value.

A boolean value is either true or false.

null and undefined are special values


whereas null is the null object and
undefined means explicitly that the
variable is not defined.

94

Basic Data Types String (1)

// 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

2014 SAP AG. All rights reserved.

Next to using the two different quotes


a string can be escaped via using
backslash to escape the following
character.

There are a couple of special


character representations:

\n
\r
\t
\uXXXX

newline
carriage return
tab
unicode character

95

Basic Data Types String (2)

// 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());

2014 SAP AG. All rights reserved.

The String object provides the


following functions:

charAt
charCodeAt
concat
fromCharCode
indexOf
lastIndexOf
match
replace

search
slice
split
substr
substring
toLowerCase
toUpperCase
valueOf

// JAVASCRIPT

96

Basic Data Types / Object Representation

// string + string object


var sString = "Hello World";
var oString = new String("Hello World");
var ooString = new Object("Hello World");
// number + number object
var iInt = 1234;
var oInt = new Number(1234);
var ooInt = new Object(1234);
var fFloat = 12.34;
var oFloat = new Number(12.34);
var ooFloat = new Object(12.34);
// boolean + boolean object
var bBool = true;
var oBool = new Boolean(true);
var ooBool = new Object(true);

2014 SAP AG. All rights reserved.

For each of the 3 basic


types an object
representation exists
By calling the constructor
you can create a String
object
You dont need to care
about dealing with objects or
primitives since JavaScript
automatically converts them.
As alternative the objects
can be created by using the
Object constructor.
The difference is that the
objects can be extended
whereas the primitives not!
97

Exercise: String Processing

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

2014 SAP AG. All rights reserved.

98

JavaScript Reference Types

JavaScript Objects

Array Array Object

Boolean Boolean Object (Wrapper)

Date Date Object: Working with Date and Time

Function Function Object (Wrapper)

Math Math Object: Perform Mathematical Tasks

Number Number Object (Wrapper)

String String Object (Wrapper)

RegExp Regular Expression Object: Pattern Matching and Search & Replace

2014 SAP AG. All rights reserved.

100

Objects

// object literal
var oObjLiteral = {};

Objects can be created via


object literal syntax or by
using the object constructor

Properties and/or methods


can be accessed via dot or
square bracket notation

Properties and/or methods


can be added and deleted
dynamically during runtime

// 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;

2014 SAP AG. All rights reserved.

101

Objects (Map)

// define the map


var oMap = {
key1: "value1",
key2: "value2",
key3: "value3"
};
alert(oMap["key1"]);

// value1

alert(oMap["key3"]);

// value3

2014 SAP AG. All rights reserved.

Objects are also often used


as Maps

Definition in the Object


literal syntax with key value
pairs.

Values can be accessed via


square bracket plus the
name of the value

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);

Arrays can be created via literal


syntax by using the square
brackets or by using the Array
constructor.

Values can be added by using


the push method

Values can be accessed via


square bracket plus the index of
the value

An array can be converted into


a string by using the join
method and specifying the
separator characters

The size can be determined via


the property length

// accessing values
alert(aArray[0]); // 5
// joining values
alert(aArray.join(" - ")); // "5 - 6 - 7 - 8"
// size of an array
alert(aArray.length); // 4

2014 SAP AG. All rights reserved.

103

Functions

// function expression (anonymous function)


var fnAdd = function(a, b) {
return a + b;
};

Functions are first-class objects


Can be created dynamically
Assignable to variables
Can be passed as arguments
to other functions
Can have properties and
methods

JavaScript does not have a local


scope (block scope). Furthermore
you only have a function scope.

Function expressions are


assigned to a variable and not
added to the global or function
scope as the function declaration.

Function declarations dont need


a trailing semicolon

// named function expression


var fnAdd = function add(a, b) {
return a + b;
};
// function declaration
function foo() {
// implement function here
}
// function object (only for demonstration)
var fnAdd = new Function('a, b', 'return a + b');
fnAdd(2, 3); // 5

2014 SAP AG. All rights reserved.

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

2014 SAP AG. All rights reserved.

The Math object allows you to perform


mathematical tasks.

Math is not a constructor. All


properties/methods of Math can be
called by using Math as an object,
without creating it.

105

Date

// today
var d = new Date();
// day of the month (from 1-31)
d.getDate();

The Date object is designed to work


for date and time.

Date objects are created with new


Date().

// day of the week (from 0-6)


d.getDay();
// month (from 0-11)
d.getMonth();
// year (four digits)
d.getFullYear();

2014 SAP AG. All rights reserved.

106

Exercise: Reference Types

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

2014 SAP AG. All rights reserved.

107

JavaScript Operators

Operators

// assignment operator
=

Important operators are the


assignment, comparison, calculation
and logic operators.

Bit and void operators are mentioned


for completeness.

// logic operators
&&, ||, !

By using the delete operator you can


delete unused objects and properties.

// bit operators
>>, <<, &, |, ^, ~

A specific feature of JavaScript for


comparison operators are the strict
equality operators: === and !==.
Compared to the equality operators
they will not do an implicit type cast
before checking the equality.

// comparison operators
==, !=, >, <, >=, <=, ===, !==
// calculation operators
+, -, *, /, %, ++, --

// void operator
void
// delete operator
delete

void see e.g. http://www.evocomp.de/beispiele/javascript/void.html


2014 SAP AG. All rights reserved.

109

Implicit Typecast (comparison)

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

2014 SAP AG. All rights reserved.

When comparing values using the


equality operators (== or !=)
JavaScript performs an implicit
typecast

If you want to avoid this behavior, you


should use the strict equality
operators (=== or !==) because this
doesnt perform a typecast before
comparing

When using the equality operator (==)


there are sometimes amazing
results.

110

String Concatenation Operator

// number calculation
4 + 5; // 9

When using + with numbers, the


numbers are added

// string concatenation
"hello" + " world"; // "hello world

// when "+" is
// numbers the
4 + 5 + "five"
4 + 5 + "five"

When using + with strings, the strings


are concatenated

When mixing numbers and strings


using +, the result is always a string.
Up to the first string the numbers are
still added, then a concatenation
takes place

Using brackets will first carry out the


code within the brackets

used with strings and


result is a string
+ 3 + 4; // "9five34
+ (3 + 4); // "9five7"

2014 SAP AG. All rights reserved.

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

// null && undefined


var vNull = null;
alert(typeof vNull);
// object
var vUndefined = undefined;
alert(typeof undefined); // undefined

The typeof-operator allows to check


the type of a variable.

In general you can differ between


string, number, boolean, object,
function and undefined

Strange behavior - be aware:

user-defined objects are typeof object


built-in type Array is typeof object
the null value is typeof object

// function
var fnAdd = function(a, b) { return a + b; };
alert(typeof fnAdd);
// function

2014 SAP AG. All rights reserved.

112

typeof Operator (does not work for objects!)

// 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);

2014 SAP AG. All rights reserved.

// object
// true
// object
// true

The type of objects can be


checked by utilizing the
constructor property.

The constructor property


contains the reference to
the constructor function
which can be used to
check the type of an
object.

// 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
}

2014 SAP AG. All rights reserved.

The condition can be either a boolean


variable or you can also checking
objects for being defined and having a
correct value.

Not using the curly brackets is bad


style and is a common source for
issues. You should acquire the habit
to always make use of the curly
brackets.

115

switch command

switch (var) {
case value1:
// impl;
break;
case value2:
// impl;
break;
default:
// impl;
}

2014 SAP AG. All rights reserved.

Each case of the switch command


should end with a break statement.
Otherwise the following case will also
be executed.

The default case is executed when no


other case matches.

116

while loop

while (condition) {
// loop impl
}

2014 SAP AG. All rights reserved.

The while loop executes its coding


until the condition is true. The
condition will be checked before the
execution of the code.

117

do while loop

do {
// loop impl
} while (condition);

2014 SAP AG. All rights reserved.

The do while loop executes its coding


until the condition is true. The
condition will be checked after the
execution of the code.

118

for loop

for (expr; cond; it) {


// loop impl
}

2014 SAP AG. All rights reserved.

The for loop will be executed until the


condition (cond) is true. The start
expression (expr) will be defined
before the execution of the for loop
and the iteration expression (it) is
execution after each execution of the
coding.

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];
}

With the for in loop you can iterate


over each property of an object. In
each loop cycle the name (key) of the
property is assigned to the defined
variable.

You can also iterate over the entries


of an array. In each loop cycle the
index of the next value of the array is
assigned to the variable.

Be aware:

2014 SAP AG. All rights reserved.

The basic Object type can be extended


with additional properties. This will ad
unexpected values to the for in loop
(also Arrays are affected since they are
Objects).
No guarantee for the order of properties
120

looping doing it right!

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];
}

2014 SAP AG. All rights reserved.

Use for in loop to


iterate over the
properties of an
object. To prevent side
effects just add the
function hasOwnProperty
to make sure that the
property is defined on
the current object.

For Arrays just make


use of the standard for
loop to make sure to
get no side effects.

121

Conditional Assignment ( ? : )

var nCount = 0;
var sText = "test";
if (sText=="test") {
nCount += 1;
} else {
nCount -= 1;
}
alert(nCount);

// 1

// this is the same but shorter


nCount = (sText == "test") ? nCount + 1 : nCount - 1;
alert(nCount);
// 2

2014 SAP AG. All rights reserved.

The semantic behind


the conditional
assignment is:

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

2014 SAP AG. All rights reserved.

123

JavaScript Variables and Scope

Variables and Scope

Characteristics

Do not create a variable inside a function without the keyword var


Otherwise, it is a global variable

If you copy an object, you copy only the reference on it


You also cannot pass an object by value, only by reference

Keep an eye on the execution context


If a variable is created, it is also accessible in a function which has been
created in the same context (used especially when creating closures)

JavaScript does not have block-level scope


It only supports global and function scope
Be aware of variable hoisting

2014 SAP AG. All rights reserved.

125

Exercise: Variables and Scope Closure

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

2014 SAP AG. All rights reserved.

126

JavaScript Error Handling

Reasons for Throwing JavaScript Errors

If programs fail silently, it can take long time to notice an issue

Throwing errors leads to easier debugging and code maintenance

Since JavaScript native errors are quite unspecific, consider the use of user
defined error objects

Compared to other languages, tool support, e.g. debuggers, in JavaScript is still


evolving thus support for error detection in the code is even more important

2014 SAP AG. All rights reserved.

128

How to Throw Errors

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

Browsers display errors in their specific ways

Often some console window is used

throw new Error("Something bad happened.");

2014 SAP AG. All rights reserved.

129

Throwing an Error String

2014 SAP AG. All rights reserved.

130

Throwing an Error Object

2014 SAP AG. All rights reserved.

131

Throwing an Error Object and Custom Error Handling

2014 SAP AG. All rights reserved.

132

Best Practice

Provide the text to be displayed to the Error constructor

Include the function name and why the function failed

2014 SAP AG. All rights reserved.

133

When to Throw Errors

JavaScript does not have argument or type checking

Do not implement this for every function!

The key is proper organization of the code: Modularization and layering

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

This is especially important for library design


2014 SAP AG. All rights reserved.

134

ECMA-262 Error Object Types


Type

Description

Error

Base type for all errors; never actually thrown by the engine

EvalError

Thrown when an error occurs during execution of code via


eval()

RangeError

Thrown when a number is outside the bounds of its range; for


example, trying to create an array with -20 items (new
Array(-20)); these occur rarely during normal execution

ReferenceError

Thrown when an object is expected but not available, for


instance, trying to call a method on a null reference

SyntaxError

Thrown when the code passed into eval() has a syntax error

TypeError

Thrown when a variable is of an unexpected type; for example,


new 10 or "prop" in true

URIError

Thrown when an incorrectly formatted URI string is passed into


encodeURI, encodeURIComponent, decodeURI, or
decodeURIComponent

2014 SAP AG. All rights reserved.

135

Error Handling

The mechanism of error handling: The try catch statement

try {
someFunction();
} catch (error){
if (error instanceof TypeError){
// Handle type error
} else if (error instanceof ReferenceError){
// Handle reference error
} else {
// Handle all other errors
}
}

2014 SAP AG. All rights reserved.

136

Best Practice when Throwing and Catching Errors

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:

Lower, technical layers throw exceptions


Higher, application layers handle exceptions
In the application context you can often decide how to deal with the error
situation, e.g. whether to signal it to the user or to take different approach to
complete the task

2014 SAP AG. All rights reserved.

137

User Defined Error Type

2014 SAP AG. All rights reserved.

138

Advantages of User Defined Errors


function MyError(message) {
this.message = message;
}
MyError.prototype = new Error();
try {
throw new MyError("Hello, world!");
} catch (error) {
if ( error instanceof MyError) {
console.log(error.name + ' says "' + error.message + '".');
} else {
console.log("Something else happened.");
}
}

React to the difference between own errors and browser errors

Error message will be displayed in the browsers normal error handling


mechanism

Browser attaches extra information to the error objects when they are thrown
2014 SAP AG. All rights reserved.

139

Debugging Techniques

Use the console

console.log("Error");

Use a custom div container

var debugInfo = document.getElementById("debugInfo");


debugInfo.innerHTML = " ";

2014 SAP AG. All rights reserved.

140

Exercise: JavaScript Error Handling

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

2014 SAP AG. All rights reserved.

141

JavaScript DOM Manipulation

Selecting Elements

By ID
getElementById("col1");

By name
getElementsByName

By tag name
getElementsByTagName

HTML5 method
var selected = document.querySelector(".selected");

2014 SAP AG. All rights reserved.

143

Tree Nodes

Create an Attribut

var attr = document.createAttribute("align");


attr.nodeValue = "right";
var el = document.getElementsByTagName("h2")[0];
el.setAttributeNode(attr);

Create a Text Node

var txt = document.createTextNode(document.lastModified);


var old = document.createTextNode("Last update: ");
document.getElementById("date").appendChild(old);
document.getElementById("date").appendChild(txt);

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);

2014 SAP AG. All rights reserved.

144

JavaScript Events

Handler Types

HTML Event Handlers


onclick = alert('hello);

DOM Level 0 Event Handlers


el.onclick = function() { };

DOM Level 2 Event Handlers


el.addEventListener("click", <function>, false);

Multiple event handler can be added


Internet Explorer
el.attachEvent("onclick", function(){ });

2014 SAP AG. All rights reserved.

146

Cross Browser Solution

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);

2014 SAP AG. All rights reserved.

147

Event Bubbling Definition

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)

2014 SAP AG. All rights reserved.

148

Event Bubbling Example

Event bubbling is the default

If you want to suppress it, set the event property cancelBubble to true

var cnt3 = document.getElementById('container3');


cnt3.addEventListener('click', function(event) {
console.log("Event handler for container 3 (table row)");
event.cancelBubble = true;
});

2014 SAP AG. All rights reserved.

149

Event Propagation Definition

The term event propagation is often used as a synonym of event bubbling

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

2014 SAP AG. All rights reserved.

150

Exercise: JavaScript Event Handling

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

2014 SAP AG. All rights reserved.

Resulting page with


last button changed
after click event

151

Object Oriented Programming

Constructor Functions

// creation via functions


var myEmployee = new Employee();

// constructor function execution


function Employee() {
// create a new object via literal

// var this = {};

If a function is used to create objects


the function serves as a constructor
and is called constructor function. By
convention those functions start with
an upper case character.
If you call a constructor function via
new the following happens:

// add properties and methods to the


// object
this.property = "propValue";
this.method = function () {};

// implicitly return this instance


// return this;
}

2014 SAP AG. All rights reserved.

An empty object will be created which is


referenced via the variable this. The
prototype of the function is inherited.
Properties and Methods are assigned to
the object via this.
The newly created object will be
implicitly returned at the end of the
constructor function.

153

Object Properties

function Employee() {
this.property = "propValue";
this.method = function () {};
}
var myEmployee1 = new Employee();
var myEmployee2 = new Employee();

Properties and methods can be added


to an object at any time in the
program

Properties or methods which are


added to an object are only available
for the particular object not the other
objects of the same origin.

If properties or methods are added in


the constructor function they will be
available on each object created via
this function.

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"

2014 SAP AG. All rights reserved.

154

No Classes, but Prototypes

JavaScript has no classes which is strange for developers of other languages

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.

A prototype is an object from which other objects inherit properties.

Every object has a prototype by default. Since prototypes are themselves


objects, every prototype has a prototype too (There is only one exception, the
default object prototype at the top of every prototype chain).

With prototype chains you can define an inheritance chain for JavaScript
objects.

Further reading: Details of the object model


2014 SAP AG. All rights reserved.

155

Prototype Object (1)

function Employee() {};


var myEmployee1 = new Employee();
Employee.prototype.myAttr = "test";
Employee.prototype.myFunction = function() {
alert("yo!");
}

Each function has a prototype object

If one defines properties or methods


for this prototype object, all objects
created via the function will get
these properties and methods, even
if the creation of the object was
before the property or method
definition.

An advantage of using prototype as


opposed to defining methods in the
constructor functions is that using
prototype all objects use the same
function as opposed to copied one

var myEmployee2 = new Employee();


alert(myEmployee1.myAttr);
alert(myEmployee2.myAttr);

// "test"
// "test"

myEmployee1.myFunction();
myEmployee2.myFunction();

// "yo!"
// "yo!"

2014 SAP AG. All rights reserved.

156

Prototype Object (2)

// creation via functions


var myEmployee = new Employee();

One can think of the red, commented code


as something that the JS runtime does
implicitly

When a function is invoked via "new", a


new object called "this is being created.
This new object has a hidden link to the
functions prototype object.

This new object inherits methods and


properties from the prototype object. If a
method or a property is not found on the
new object the prototype will be checked.

The prototype object always has the


reference to the origin constructor function.

// constructor function execution


function Employee() {
// create a new object via literal
var this = {
__proto__ = Employee.prototype
};
// add properties and methods to the
// object
this.property = "propValue";
this.method = function () {};
// implicitly return this instance
return this;
}
Employee.prototype = {
constructor: Employee
};

2014 SAP AG. All rights reserved.

157

Comparison: Java & JavaScript

2014 SAP AG. All rights reserved.

158

Inheritance (1)

2014 SAP AG. All rights reserved.

159

Inheritance (2)

2014 SAP AG. All rights reserved.

160

Inheritance (3)

2014 SAP AG. All rights reserved.

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

Expected result in Console:

2014 SAP AG. All rights reserved.

163

HTTP Requests and AJAX

Synchronous Request

New browsers support the XMLHttpRequest object

Set the 3rd parameter of request.open to false for a synchronous call

var request = new XMLHttpRequest();


request.open("GET", "files/data.txt", false);
request.send(null);
console.log(request.getAllResponseHeaders());
console.log(request.responseText);

2014 SAP AG. All rights reserved.

165

Asynchronous Request

Set the 3rd parameter of request.open to true for an asynchronous call

Register a callback on event request.onreadystatechange

var request = new XMLHttpRequest();


request.onreadystatechange = function() {
if (request.readyState == 4) {
console.log("Request status " + request.status + " "
+ request.statusText);
console.log(request.getAllResponseHeaders());
console.log(request.responseText);
}
};
request.open("GET", "files/data.txt", true);
request.send(null);
2014 SAP AG. All rights reserved.

166

Synchronous XML Request

XML content is in request.responseXML

Use an XMLSerializer to render it into a String

var request = new XMLHttpRequest();


var serializer = new XMLSerializer();
request.open("GET", "files/fruit.xml", false);
request.send(null);
var sXML =
serializer.serializeToString(request.responseXML.documentElement);
console.log(sXML);

2014 SAP AG. All rights reserved.

167

Asynchronous JSON Request

JSON request proceeds in a standard way

Result shall be processed with JSON.parse()

var request = new XMLHttpRequest();


request.onreadystatechange = function() {
if (request.readyState == 4) {
console.log("Request status " + request.status + " "
+ request.statusText);
console.log(request.responseText);
var data = JSON.parse(request.responseText);
console.log(data["lemon"]);
}
};
request.open("GET", "files/fruit.json", true);
request.send(null);
2014 SAP AG. All rights reserved.

168

Exercise: Replace content of a span tag using a request

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

2014 SAP AG. All rights reserved.

Expected
outcome of
exercise
169

Writing API Docs

Auto-Generated API Documentation

API documentation can be auto-generated from comments in the code

Traditionally API docs come from the Java word (the javadoc utility)

For JavaScript there are two excellent tools


JSDoc Toolkit (http://code.google.com/p/jsdoc-toolkit/)
YUIDoc (http://yui.github.com/yuidoc/)

The special syntax consists of a dozen or so tags, which look like this
/**
* @tag value
*/

2014 SAP AG. All rights reserved.

171

YUIDoc Usage Example

2014 SAP AG. All rights reserved.

172

YUIDoc Sample Tags


Tag

Description

@namespace

The global reference that contains the object

@class

A misnomer (no classes in JavaScript) that is used to


mean either an object or a constructor function

@method

Defines a method in an object and specifies the


method name

@param

List the argument the function takes; the types of the


parameters are in curly braces, followed by the
parameter name and its description

@return

Like @param, only it describes the value retured by


the method and has no name

@constructor

Hints that this class is actually a constructor function

@property and @type

Describe properties of an object

2014 SAP AG. All rights reserved.

173

Unit Summary

After completing this unit, you should now be able to:


Describe the JavaScript Language
Write JavaScript code

2014 SAP AG. All rights reserved.

174

UNIT 3
Foundations of
JQuery

Unit 3 Foundations of JQuery: Unit Objectives

After completing this unit, you will be able to:


Describe JQuery
Write JQuery code

2014 SAP AG. All rights reserved.

176

Unit 3 Foundations of JQuery: Unit Lessons


Foundations of JQuery
Lesson 3: JQuery Foundations

2014 SAP AG. All rights reserved.

177

Lesson Objectives

After completing this lesson, you will be able to:


Describe JQuery
Write JQuery code

2014 SAP AG. All rights reserved.

178

JQuery Introduction

jQuery Essentials

Why do we need a JavaScript Framework?


Browser Dependencies
Different stages of HTML(5) and CSS(3) implementations
Different implementations of event handling
Known browser bugs
Browsers support different set of CSS selectors

Often Used Features


Frameworks provide an easy way to re-use code

Best Practice Solutions


Do not re-invent the wheel

2014 SAP AG. All rights reserved.

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

2014 SAP AG. All rights reserved.

181

How to get jQuery

Either Download jQuery


http://jquery.com

or use a CDN (Content Delivery / Distribution Network)


List with CDNs hosting jQuery
http://docs.jquery.com/Downloading_jQuery#CDN_Hosted_jQuery

Documentation
http://docs.jquery.com/Main_Page

2014 SAP AG. All rights reserved.

182

Other jQuery Resources

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

2014 SAP AG. All rights reserved.

183

jQuery First Example


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>jQuery First Example</title>
<script src="js/jquery-1.6.4.js"></script>
</head>
<body>
<h1 id="firstHead">jQuery First Example</h1>
<script>
$(document).ready(function() {
$("#firstHead").click(function() {
$("#firstHead").fadeOut();
});
});
</script>
</body>
</html>

2014 SAP AG. All rights reserved.

184

Exercise: Fading In and Fading Out (Warm Up Exercise)

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

Selecting JQuery Elements

Selector Types

Selector
Type

CSS

jQuery

What it does

Tag Name

p { }

$('p')

Selects all paragraphs in


the document

ID

#some-id { }

$('#some-id')

Selects the single element


in the document that has
an ID of some-id

Class

.some-class { }

$('.some-class')

Selects all elements in the


document that have a
class of some-class

2014 SAP AG. All rights reserved.

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/

Filter a result set


http://api.jquery.com/category/selectors/basic-filter-selectors/

2014 SAP AG. All rights reserved.

188

Exercise: Using Different Selector Types

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

2014 SAP AG. All rights reserved.

189

JQuery Events

Event DOM is Ready

Code execution when page is fully loaded

$(document).ready(function(){});

Shorthand notation

$(function(){});
http://api.jquery.com/ready/
http://api.jquery.com/category/events/document-loading/

2014 SAP AG. All rights reserved.

191

Mouse and Keyboard Events

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/

2014 SAP AG. All rights reserved.

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

2014 SAP AG. All rights reserved.

Expected
outcome of
exercise

193

JQuery Styling and Animation

Styling

Basic Styling

Adding and removing a CSS-Class


$(selector).addClass("classname");
$(selector).removeClass("classname");

Defining CSS-Properties
$(this).css( "width", "200px" );
$(this).css({"width": "200px, height: 300px} );

http://api.jquery.com/css/#css2

2014 SAP AG. All rights reserved.

195

Animation

Show and Hide elements


$(this).hide("slow");

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/

2014 SAP AG. All rights reserved.

196

Exercise 1: Styling Text

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

2014 SAP AG. All rights reserved.

Expected
outcome of
exercise
197

Exercise 2: Custom Animation

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

2014 SAP AG. All rights reserved.

Expected
outcome of
exercise
198

JQuery DOM Manipulation

DOM Manipulation

Changing attributes
$(img).attr('title', 'Dolphin');
http://api.jquery.com/category/manipulation/general-attributes/

Creating new elements


.after()
.before()
.insertAfter()
.insertBefore()

http://api.jquery.com/category/manipulation/dom-insertion-outside/
http://api.jquery.com/category/manipulation/dom-insertion-inside/

2014 SAP AG. All rights reserved.

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/

Deleting elements or content

http://api.jquery.com/category/manipulation/dom-removal/

2014 SAP AG. All rights reserved.

201

Exercise 1: jQuery DOM Manipulation

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

2014 SAP AG. All rights reserved.

202

Exercise 2: jQuery DOM Manipulation with AJAX

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

2014 SAP AG. All rights reserved.

203

JQuery AJAX

jQuery AJAX Calls

$.get(url) requests data and pipes them into a callback function

$(selector).load(url) inserts data into the selected element

<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

Further AJAX Options

AHAH, JSON, JavaScript, and XML

AHAH Asynchronous HTTP and HTML


.load("file.html");
http://api.jquery.com/load/
JSON JavaScript Object Notation
$.getJSON("data.json",request,callback)
http://api.jquery.com/jQuery.getJSON/
JavaScript files
$.getScript("file.js",callback);
http://api.jquery.com/jQuery.getScript/
XML
$.get("data.xml");
Walking through with .find("element").each();
2014 SAP AG. All rights reserved.

206

Exercise: Load and Display HTML Snippets (AHAH)

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/

jQuery UI enhances the possibilities of jQuery with


Animated colors
Class animations
Advanced easing (acceleration of effects)
http://jqueryui.com/demos/effect/#easing
More effects like shake, bounce,...
Interactions like resizable()
Widgets

2014 SAP AG. All rights reserved.

209

jQuery UI

Widgets
o Accordion
o Autocomplete
o Button
o Date Picker
o Progress Bar
o Slider
o Tabs

All functionality is added by extending jQuery


$(function() {
$( "#tabs" ).tabs();
});

2014 SAP AG. All rights reserved.

210

JQuery Data Tables

Data Tables

http://www.datatables.net/

Step 1:
Step 2:

Build a full featured HTML table


Add following code in your script block

$(document).ready(function(){
$('#example').dataTable();
});
#example references the ID of the table

2014 SAP AG. All rights reserved.

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)

2014 SAP AG. All rights reserved.

214

JQuery Plugin Development

Basic Pattern
(function( $ ) {
$.fn.myPlugin = function() {
// Do your awesome plugin stuff here
};
})( jQuery );

For an in-depth introduction, refer to the jQuery web site

http://docs.jquery.com/Plugins/Authoring

2014 SAP AG. All rights reserved.

216

Simple Example
(function( $ ){
$.fn.maxHeight = function() {
var max = 0;
this.each(function() {
max = Math.max( max, $(this).height() );
});
return max;
};
})( jQuery );

// Returns the height of the tallest div


var tallest = $('div').maxHeight();

2014 SAP AG. All rights reserved.

217

Tooltip Example

This example is a slide modification of a tutorial found in the web

http://net.tutsplus.com/tutorials/javascript-ajax/build-a-better-tooltip-with-jqueryawesomeness/

2014 SAP AG. All rights reserved.

218

Unit Summary

After completing this unit, you shold now be able to:


Describe JQuery
Write JQuery code

2014 SAP AG. All rights reserved.

219

UNIT 4
Security

Unit 4 Security: Unit Objectives

After completing this unit, you will be able to:

Describe the foundations of HTML, CSS, JavaScript, jQuery Security

2014 SAP AG. All rights reserved.

221

Unit 4 Security
Security
Lesson 4: Foundations of HTML, CSS, JavaScript, jQuery Security

2014 SAP AG. All rights reserved.

222

Lesson Objectives

After completing this lesson, you will be able to:

Describe the foundations of HTML, CSS, JavaScript,


jQuery Security

2014 SAP AG. All rights reserved.

223

Foundations of HTML, CSS,


JavaScript, jQuery Security

Server and Client Side Attacks

Server Side Attacks


The classical attack vector
Attacker uses its network connection to hack the server
Examples are SQL injection, remote code injection, and path transversal

Client Side Attacks


The modern or web attack vector
Attacker uses web client (browser) directly or indirectly (confused deputy)
Examples are cross site scripting and cross site request forgery

Never Trust the Client!


The client is under full control of the potential attacker
He can read and modify all aspects of the web user interface
He can put a proxy between the client and the server
Client side security measures are never sufficient the server must be secured
2014 SAP AG. All rights reserved.

225

Client Side Vulnerabilities

XSS Cross Site Scripting


Principle: Web applications accept user input, which can be used to create
executable content in HTML pages
1. Non persistent or reflected
2. Persistent
3. DOM based

XSRF Cross Site Request Forgery


Principle: Attacker uses session of a confused deputy

2014 SAP AG. All rights reserved.

226

XSS Cross Site Scripting


Security Warning

Web applications accept user input which is used to create executable content in HTML pages

Weakness

Insufficient input validation

Missing output filtering or encoding when writing user input back to HTML pages

Attack or Entry Point

Attacker injects client side JavaScript into web pages viewed by himself or others

Potential Consequences

Stealing access credentials, denial of service, web page modifications, execution of OS


commands

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

2014 SAP AG. All rights reserved.

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

The SAP Portal search page echoes the


search string on the result page

Corresponding HTML fragment

<span class="urTxtStd" ct="TV">


Business Suite
</span>

If input would not be validated, something like


follows would be possible

<span class="urTxtStd" ct="TV">


</span><script type="text/javascript">some code</script><span>
</span>
2014 SAP AG. All rights reserved.

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:

Did you know this?

Subject: GET Money for FREE


!!!

.....
GET Money for FREE !!!

<script> attack code </script>


Re: Error message on startup

Body:

.....
I found a solution!

<script> attack code </script>

.....
Can anybody help?
Get /forum.jsp?fid=122&mid=2241

.....
Error message on startup
.....

1. Attacker sends malicious code as part of message


2.

Server stores message

GET Money for FREE !!!


<script> attack code </script>

3. User requests message


4. Message is delivered by server

Client
!!! attack code
!!!

5. Browser executes script in message (as a mixture of data and code)


2014 SAP AG. All rights reserved.

229

General XSS Countermeasures

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

Find a harmless representation of user input, especially if it is output again


General countermeasures

Constrain input: Filter unwanted input

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

2014 SAP AG. All rights reserved.

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

Validate the URL and contents of external style sheets

Use escaping when untrusted data is inserted inside your CSS styles

2014 SAP AG. All rights reserved.

231

Web Forms: Never Trust the Client!

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

Never trust the client!

Countermeasure

Perform validation of input received through those type specific form elements
on the server

2014 SAP AG. All rights reserved.

232

JavaScript Excursion: Same Origin Policy (SOP)


Definition
The origin of a document is defined as the protocol, host, and port of
the URL from which the document was loaded
Documents loaded from different web servers have different origins
Documents loaded through different ports of the same host have different
origins.
A document loaded with the http: protocol has a different origin than one
loaded with the https: protocol, even if they come from the same web server
Windows or frames can work in contexts of each other only if they are from
same protocol://domain:port, or, shortly, from same origin
Note: The path part of the URL does not matter!

2014 SAP AG. All rights reserved.

233

Same Origin Policy: Examples

Examples
These are from same origin:

http://site.com

http://site.com/my/page.html

These come from another origin:

http://www.site.com (another domain)

http://site.org (another domain)

https://site.com (another protocol)

http://site.com:8080 (another port)

2012
2014SAP
SAPAG.
AG.AllAllrights
rightsreserved.
reserved.

234

JavaScript and Same Origin Policy


The only client side security measure

Defines basic access rights in HTTP

JavaScript Sandbox

A given JavaScript is only allowed access to pages that share the scripts origin

This effectively restricts the script to its own web application

2014 SAP AG. All rights reserved.

235

JavaScript: Direct Object Reference

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

// should not be exposed

}
Counter Measures
Filter and validate input before changing object properties

2014 SAP AG. All rights reserved.

236

DOM Manipulation: Security Issues

Security warning

DOM based attacks occur cause of insecure client side JavaScript

Client side creation of JavaScript

eval()

innerHTML

document.write()

Use of attacker controlled values

document.URL: http://www.app.com#<script></script>

document.referrer

2014 SAP AG. All rights reserved.

237

DOM Based XSS Example

DOM based XSS no server used


<HTML><TITLE>Welcome!</TITLE>
<SCRIPT>
var pos = document.URL.indexOf("name=") + 5;
document.write(document.URL.substring(pos,document.URL.length));
</SCRIPT>
</HTML>

Works fine with this URL:

http://www.example.com/welcome.html?name=Joe

But what about this one?

http://www.example.com/welcome.html?name=<script>alert(docum
ent.cookie)</script>

2014 SAP AG. All rights reserved.

238

DOM Manipulation: Avoid Use of Property innerHTML

Security Warning
Improper use of the innerHTML property can enable script injection attacks
Example

It is not uncommon to see innerHTML used to insert text in a web page


var name = "John";
// assuming el is an HTML DOM element
el.innerHTML = name;
// harmless
name = "<script>alert('I am an annoying alert!')</script>";
el.innerHTML = name;
// alerts the text which is annoying
// and not really what was expected

2014 SAP AG. All rights reserved.

239

Avoid Use of Property innerHTML: Alternatives

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

2014 SAP AG. All rights reserved.

240

AJAX Security: JSON Request eval() and XSS

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

Use JSON.parse() instead of eval()

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)

2014 SAP AG. All rights reserved.

241

XMLHttpRequest and Cross Origin Resource Sharing

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

Especially, it has to be ensured that in situation in which local URLs are


expected, no cross domain URLs get requested
2014 SAP AG. All rights reserved.

242

CDN for jQuery should not be used in production code

Security Warning
CDN is not under control of SAP
It is not known if the delivered JavaScript code is safe

2014 SAP AG. All rights reserved.

243

jQuery DOM Manipulation

Security Warning

JQuery has quite a set of potentially insecure DOM manipulation APIs

They all can lead to DOM based XSS

Insecure writes happen when user input is written to the DOM without first being sanitized

Data can come in through user input in the browser, or

Data can be loaded through JSON from the server

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

References and Further Information

SAP Product Standard Security

https://wiki.wdf.sap.corp/wiki/display/PSSEC/Home

SAP TIP Core CSI Security and Identity Management

https://wiki.wdf.sap.corp/wiki/display/NWCUIAMSIM/Home

SAP XSS Secure Programming Guide

https://wiki.wdf.sap.corp/wiki/display/NWCUIAMSIM/XSS+Secure+Programming+Guide

Open Web Application Security Project (OWASP)

https://www.owasp.org/index.php/Main_Page

Common Weakness Enumeration (CWE)

http://cwe.mitre.org/

HTML5 Security

http://html5security.org

2014 SAP AG. All rights reserved.

245

Unit Summary

After completing this unit, you should now be able to:

Describe the foundations of HTML, CSS, JavaScript, jQuery


Security

2014 SAP AG. All rights reserved.

246

Você também pode gostar