© 2014 SAP AG. All rights reserved. 1
<Course Number and Course Title ABC123 Overiew>
SAPX04
HTML5 Foundations for SAP
SAPUI5 Development
SAP SAPGUI5
Training System: Windows 2008 R2 with latest SAPUI5 component)
© 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.
© 2014 SAP AG. All rights reserved. 3
© 2014 SAP AG. Alle Rechte vorbehalten.
Weitergabe und Vervielfältigung dieser Publikation oder von Teilen daraus sind, zu welchem Zweck und in welcher Form auch immer, ohne die ausdrückliche schriftliche Genehmigung durch SAP AG nicht gestattet. In dieser Publikation enthaltene Informationen können ohne vorherige Ankündigung geändert werden.
Die von SAP AG oder deren Vertriebsfirmen angebotenen Softwareprodukte können Softwarekomponenten auch anderer Softwarehersteller enthalten.
Microsoft, Windows, Excel, Outlook, PowerPoint, Silverlight und Visual Studio sind eingetragene Marken der Microsoft Corporation.
Apache Maven, Maven, Apache, the Apache feather logo, and the Apache Maven project logos sind eingetragene Marken der Apache Software Foundation.
IBM, DB2, DB2 Universal Database, System i, System i5, System p, System p5, System x, System z, System z10, z10, z/VM, z/OS, OS/390, zEnterprise, PowerVM, Power
Architecture, Power Systems, POWER7, POWER6+, POWER6, POWER, PowerHA, pureScale, PowerPC, BladeCenter, System Storage, Storwize, XIV, GPFS, HACMP, RETAIN, DB2 Connect, RACF, Redbooks, OS/2, AIX, Intelligent Miner, WebSphere, Tivoli, Informix und Smarter Planet sind Marken oder eingetragene Marken der IBM Corporation. Linux ist eine eingetragene Marke von Linus Torvalds in den USA und anderen Ländern. Adobe, das Adobe-Logo, Acrobat, PostScript und Reader sind Marken oder eingetragene Marken von Adobe Systems Incorporated in den USA und/oder anderen Ländern. 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.
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.
INTERMEC ist eine eingetragene Marke der Intermec Technologies Corporation. Wi-Fi ist eine eingetragene Marke der Wi-Fi Alliance.
Bluetooth ist eine eingetragene Marke von Bluetooth SIG Inc.
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 erwähnte SAP-Produkte und -Dienst-leistungen sowie die entsprechenden Logos sind Marken oder eingetragene Marken der SAP AG in Deutschland und anderen Ländern.
Business Objects und das Business-Objects-Logo, BusinessObjects, Crystal Reports, Crystal Decisions, Web Intelligence, Xcelsius und andere im Text erwähnte Business-Objects-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 erwähnte 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 Ländern. 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 Informations-zwecken. Produkte können länderspezifische Unterschiede aufweisen.
Die in dieser Publikation enthaltene Information ist Eigentum der SAP. Weitergabe und Vervielfältigung dieser Publikation oder von Teilen daraus sind, zu welchem Zweck und in welcher Form auch immer, nur mit ausdrücklicher schriftlicher Genehmigung durch SAP AG gestattet.
Course Topics
This course covers:
• HTML5 for SAPUI5 Essentials
• Creation of HTML and CSS styles
• JavaScript Development
© 2014 SAP AG. All rights reserved. 5
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
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. 7
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
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
© 2014 SAP AG. All rights reserved. 9
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
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. 11 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
Preface
Preface
Course Outline and Schedule
Day 2:
Unit 3 – Foundations of JQuery
• Lesson 3: JQuery FoundationsUNIT 4 – Security
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. 15
© SAP 2014 /
Unit 1 – Foundations of HTML5 & CSS:
Unit Lessons
Foundations of HTML5 & CSS
Lesson Objectives
After completing this lesson, you will be able to:
• Describe and write HTML5 and CSS codeWeb 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
JavaScript Libraries Best Practice Solutions Domain Specific Language
Streamlining of Common Tasks Reusable UI Blocks
© 2014 SAP AG. All rights reserved. 19
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,
What does HTML5 contain?
Class Examples (Source: http://www.w3.org/html/logo/)
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. 21
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>
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
© 2014 SAP AG. All rights reserved. 23
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
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. 25
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
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,
© 2014 SAP AG. All rights reserved. 27
Lab Environment Setup 2
• Close the Welcome tab. • Go to File Import.
• In the Import window that
appears, select General
Existing Projects into Workspace
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
© 2014 SAP AG. All rights reserved. 29
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:
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
© 2014 SAP AG. All rights reserved. 31
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:
Installing the Firebug Add-on in FireFox (2)
• Upon installation, note the new tab and the change in status:
© 2014 SAP AG. All rights reserved. 33
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
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
Exercise: Basic HTML Page
* Note that there is also a solutions folder containing completed code in case you
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>
© 2014 SAP AG. All rights reserved. 37
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 {}
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
© 2014 SAP AG. All rights reserved. 39
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;
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. 41
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)
Working with Browser Tools
• Use function button F12 in browser
© 2014 SAP AG. All rights reserved. 43
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
CSS3 Special Features – Gradients,
Shadows and Corners
© 2014 SAP AG. All rights reserved. 45
Linear Gradients
background: -moz-linear-gradient(left, blue, white); background: -webkit-linear-gradient(left, blue, white);
background: -moz-linear-gradient(90deg, red, white); background: -webkit-linear-gradient(90deg, red, white);
background: -moz-linear-gradient(top, blue, white 80%, orange); background: -webkit-linear-gradient(top, blue, white 80%, orange);
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);
Linear Gradient
Linear Gradient with Angle
Linear Gradient with Color Stops
Box Shadows
box-shadow: 8px 8px lightgrey; box-shadow: 8px 8px 4px lightgrey; box-shadow: 8px 8px 0px 4px lightgrey; box-shadow: 8px 8px 4px 4px lightgrey; box-shadow: 0px 0px 4px cyan;box-shadow: inset 0px 0px 4px cyan; #box11:hover {
box-shadow: 0px 0px 4px cyan; }
Color and Blur
Spread and Blur
© 2014 SAP AG. All rights reserved. 47
Rounded Corners
border-radius: 16px; border-radius: 20%; border-radius: 16px/32px; border-radius: 16px 32px; border-top-left-radius: 8px; border-top-right-radius: 16px; border-bottom-right-radius: 24px; border-bottom-left-radius: 32px; Circular Arcs Elliptic Arcs Two Corners Individual CornersGoal
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
(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)
© 2014 SAP AG. All rights reserved. 51
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
Exercise: Define a Blog Using Semantic Markup
• You tested page
should appears as follows:
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">
© 2014 SAP AG. All rights reserved. 55
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">
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
© 2014 SAP AG. All rights reserved. 57
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
Exercise: User-Friendly Web Forms
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. 61
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: "city", prefix: "I am from "},
{name: "food", prefix: "I like to eat "},
{name: "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);
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
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. 65 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
Exercise 1: Styling Tables with Pseudoclasses
• You tested page should
© 2014 SAP AG. All rights reserved. 67 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
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. 69
Exercise 3: Deletion of Table Rows
© 2014 SAP AG. All rights reserved. 71
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/
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. 73
Building a Full CSS Layout
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
© 2014 SAP AG. All rights reserved. 75 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. 77 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 float 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. 79
Unit Summary
After completing this unit, you should now be able to:
• Describe and write HTML5 and CSS codeFoundations of
JavaScript
© 2014 SAP AG. All rights reserved. 81
Unit 2 – Foundations of JavaScript: Unit Objectives
After completing this unit, you will be able to:
• Describe the JavaScript LanguageUnit 2 – Foundations of JavaScript: Unit Lessons
Foundations of JavaScript
© 2014 SAP AG. All rights reserved. 83
Lesson Objectives
After completing this lesson, you will be able to:
• Describe the JavaScript Language© 2014 SAP AG. All rights reserved. 85
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!");
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
© 2014 SAP AG. All rights reserved. 87
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
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
© 2014 SAP AG. All rights reserved. 89
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/
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
© 2014 SAP AG. All rights reserved. 91
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. 93
Comments and Variables
// this is a comment /* this is a
block comment */
// variable declaration var iMyVariable = 12;
// multi variable declaration var iVar1 = 0, sVar2 = "Hello";
• 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.
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;
• 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.
© 2014 SAP AG. All rights reserved. 95
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
• 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 newline
• \r carriage return
• \t tab
Basic Data Types – String (2)
// string operations
var sText = "test string";
alert(sText.length); // 11
alert(sText.substring(5,7)); // "st"
alert(sText.charAt(5)); // "s"
alert(sText.indexOf("s")); // 2
// string separation
var sNames = "Peter,Tim,Frank,Andreas"; var aNames = sNames.split(",");
// "Peter", "Tim", "Frank", "Andreas"
// string transformation
alert("JavaScript".toUpperCase()); // JAVASCRIPT
• The String object provides the
following functions: • charAt • charCodeAt • concat • fromCharCode • indexOf • lastIndexOf • match • replace • search • slice • split • substr • substring • toLowerCase • toUpperCase • valueOf
© 2014 SAP AG. All rights reserved. 97
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);
• For each of the 3 basic
types an object
representation exists
• By calling the constructor
you can create a String object
• You don’t 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!
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
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)
© 2014 SAP AG. All rights reserved. 101
Objects
// object literal var oObjLiteral = {}; // object
var oObject = new Object(); // dot notation
oObject.property;
oObject.method([parameter]); // square bracket notation oObject["property"];
oObject["method"]([parameter]); // adding a property to an object
oObject.newProperty = "Property Value"; // adding a new method to an object
oObject.newMethod = function() { /* impl */ }; // deleting properties or methods
delete oObject.newMethod;
• 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
Objects (Map)
// define the map var oMap = { key1: "value1", key2: "value2", key3: "value3" }; alert(oMap["key1"]); // value1 alert(oMap["key3"]); // value3
• 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
© 2014 SAP AG. All rights reserved. 103
Arrays
// array literal var aArrLiteral = []; var aArrLiteral1 = [1, 2, 3, 4]; // arrayvar aArray = new Array();
var aArray1 = new Array(1, 2, 3, 4); // adding values aArray.push(5, 6, 7, 8); // accessing values alert(aArray[0]); // 5 // joining values alert(aArray.join(" - ")); // "5 - 6 - 7 - 8" // size of an array alert(aArray.length); // 4
• 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
Functions
// function expression (anonymous function) var fnAdd = function(a, b) {
return a + b; };
// 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
• 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 don’t need
© 2014 SAP AG. All rights reserved. 105
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• 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.
Date
// today
var d = new Date();
// day of the month (from 1-31) d.getDate();
// day of the week (from 0-6) d.getDay();
// month (from 0-11) d.getMonth();
// year (four digits) d.getFullYear();
• The Date object is designed to work
for date and time.
• Date objects are created with new
© 2014 SAP AG. All rights reserved. 107 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. 109
Operators
// assignment operator = // comparison operators ==, !=, >, <, >=, <=, ===, !== // calculation operators +, -, *, /, %, ++, -- // logic operators &&, ||, ! // bit operators >>, <<, &, |, ^, ~ // void operator void // delete operator delete• Important operators are the
assignment, comparison, calculation and logic operators.
• Bit and void operators are mentioned
for completeness.
• By using the delete operator you can
delete unused objects and properties.
• 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.
Implicit Typecast (comparison)
alert("1" == 1); // true
alert("1" === 1); // false
alert(1 === 1); // true
// weirdness
alert("1" == true); // true
alert("0" == true); // false
// even weirder
alert("" == 0); // true
• 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 doesn‘t perform a typecast before comparing
• When using the equality operator (==)
there are sometimes amazing results….
© 2014 SAP AG. All rights reserved. 111
String Concatenation Operator
// number calculation 4 + 5; // 9
// string concatenation
"hello" + " world"; // "hello world“
// when "+" is used with strings and // numbers the result is a string 4 + 5 + "five" + 3 + 4; // "9five34“
4 + 5 + "five" + (3 + 4); // "9five7"
• When using + with numbers, the
numbers are added
• 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
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 // function
var fnAdd = function(a, b) { return a + b; }; alert(typeof fnAdd); // function
• 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
© 2014 SAP AG. All rights reserved. 113
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 ); // object
alert(oInt.constructor === Number); // true
var oFloat = new Number(12.34);
alert(typeof oFloat); // object
alert(oFloat.constructor === Number); // true
// boolean
var oBool = new Boolean(true);
alert(typeof oBool); // object
alert(oBool.constructor === Boolean); // 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.
© 2014 SAP AG. All rights reserved. 115
if … else … condition
// default
if (condition) {
// impl when true; } else {
// impl when false; }
// checking defined objects if (object) {
// do something }
• 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
switch… command
switch (var) { case value1: // impl; break; case value2: // impl; break; default: // impl; }• 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
© 2014 SAP AG. All rights reserved. 117
while… loop
while (condition) { // loop impl }
• The while loop executes its coding
until the condition is true. The
condition will be checked before the execution of the code.
do… while… loop
do {
// loop impl
} while (condition);
• The do while loop executes its coding
until the condition is true. The
condition will be checked after the execution of the code.
© 2014 SAP AG. All rights reserved. 119
for… loop
for (expr; cond; it) { // loop impl
}
• 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.
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:
• 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).
© 2014 SAP AG. All rights reserved. 121
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];
}
• 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.
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
• 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.
© 2014 SAP AG. All rights reserved. 123 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. 125
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 contextIf 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 hoistingGoal
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
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
© 2014 SAP AG. All rights reserved. 129
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
© 2014 SAP AG. All rights reserved. 131
© 2014 SAP AG. All rights reserved. 133
Best Practice
• Provide the text to be displayed to the Error constructor
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