66
Web Mastery with JavaScript John Valance Division 1 Systems [email protected] © 2014-2018 Division 1 Systems <div1> www.div1sys.com

Introduction to JavaScript€¦ ·  · 2018-03-1723 •Array elements are accessed by index number Arrays are not associative, like in PHP (i.e. no alpha indices) •Array indices

  • Upload
    lamdien

  • View
    216

  • Download
    2

Embed Size (px)

Citation preview

Web Mastery

with

JavaScript

John Valance

Division 1 Systems

[email protected]

© 2014-2018 Division 1 Systems

<div1>

www.div1sys.com

2

About John Valance

• 30+ years IBM midrange experience (S/38 thru IBM i)

• 17+ years of web development experience

• Independent consultant since Feb. 2000

• COMMON Board of Directors since May 2017

• Founder and CTO of Division 1 Systems – www.div1sys.com

Helping IBM shops modernize and web-enable applications and skills

• Frequent presenter on web development topics

• Relationship with Zend Technologies

Instructor, Zend Reseller, Zend Certified Engineer

What Is JavaScript?

4

•Not to be confused with Java!

but similar syntax, based on C

•Developed originally by Netscape in 1995

•Runs on the client-side (usually) i.e. in browser

•Scripting language for web browsers (usually)

•All browsers have built-in JavaScript interpreter – you don’t buy it or install it.

• Interpreted at run-time (as page loads)

•JavaScript code is downloaded from server with the HTML document, but only runs in the browser.

What is JavaScript?

5

Web Applications = Client / Server

Languages used:

•Server side (IBM i):

PHP

SQL (accessing DB2 tables)

Possibly RPG & CL

• Called via stored procedures or Zend Toolkit for IBMi

•Client side (web browser):

HTML

CSS

JavaScript

Web Application Architecture

6

Manipulate the HTML document after it has been sent to the browser in a myriad of ways

• Validate input data

• React to events

e.g.: mouse clicks or cursor movement into/out of fields

• Control Dynamic HTML

make things move around, appear and disappear

• Read and alter document elements, including HTML tags and CSS attributes

• Open & close windows, communicate between windows.

• Send Ajax requests to Server

Key technology in Web 2.0 applications

http://jvalance.com/jslab/complete/

What Can JavaScript Do?

http://localhost/jvalance.com/webdemos/DHTML_examples.html

7

•To insert a JavaScript into an HTML page, use the <script>

tag.

•The <script> and </script> tells where the JavaScript starts

and ends.

•The lines between the <script> and </script> contain the

JavaScript:

<script>

alert("My First JavaScript");

</script>

The <script> tag

8

<html>

<head>

<title>JavaScript Example</title>

<script>

function checkCustNo() {

if (document.myForm.custNo.value == '') {

alert(‘Customer number is required.');

} else {

alert(‘Customer No. entered was: ' + document.myForm.custNo.value);

}

}

</script>

</head>

JavaScript Example – input validation

http://172.25.0.1:10080/sandbox/connect_dots/cust_prompt_validate.html

9

alert('Hello world!');

var isOK = confirm('Are you sure?’);

var favColor = prompt(‘Enter your favorite color:','blue');

User Interaction: alert / confirm / prompt

10

• Can be inserted just about anywhere, but must be

enclosed in <script> </script> tag

• Scripts can be in <head> or <body> section.

• Can add as many scripts as you want throughout document

• Can also pull in externally defined JavaScript code

.js files

Usually done in <head> section

Where Is JavaScript Coded in the Document?

Coding JavaScript Functions

12

• Can include JavaScript code inline, or within function

definitions

• Inline script code is executed as the page loads

• JavaScript functions are only executed when:

called from some other JavaScript code

when certain events are fired (i.e. function coded as an event handler)

JavaScript - Inline vs. Functions

13

• Typically, functions are defined in <HEAD> section.

<head><script>

function myFunction( parm1, parm2 ) {

// Function body statements…

}

</script></head>

• Can also be included as external files

Function libraries, Frameworks

Linked to document in <HEAD> section

Use <script> tag, with “src” attribute, specifying file name

<script src=“fileName.js”></script>

Be sure to add closing </script> tag! (don’t use self closing tag)

• i.e. <script src=“fileName.js” /> // won’t work

JavaScript Functions

14

<html>

<head>

<script src="myScript.js"></script>

<script src="jQuery.js"></script>

<script>

function sayHello( ) {

alert(“Hello!!”);

}

</script>

</head>

<body>

<button onclick=“sayHello()” />

<script>

sayHello();

</script>

</body>

</html>

JavaScript Example

Event Handling

16

•JavaScript can react to events in the browsermouse clicks,

mouse movement,

keystrokes,

movement in and out of form fields, etc.

•Event handlers start with “on…”onclick,

onfocus,

onblur,

onmouseover,

onmouseout

JavaScript Event Handling

17

• Event handlers coded as HTML tag attributes

• Specify JavaScript code to be executed

Either individual statements or function calls

JavaScript Event Handling

<body onload=“setInputDefaults();”>

<input name=“company” onblur=“this.value=this.value.touppercase();”>

<tr onmouseover=“this.className=‘hilite’;”>

<a href=“javascript:openHelpWindow();”>

JavaScript Langage Features

19

• Syntax based on C language

• Interpreted, not compiled

• Loosely-Typed Language

Like PHP, unlike Java

Variable and function data types are not declared

• Data types dictated by content, not declaration

• Variables can change data type during script execution

• Core function set is relatively small

Many free libraries and frameworks available

• Allows both procedural and object-oriented coding styles

• All variables in JavaScript are objects of some type

Features of the JavaScript Language

20

• Runs on client, in browser

Code is downloaded from server to client, so user can see your code

• JavaScript can be turned off by user in browser options

Use noscript tag for this:

<noscript>You need JavaScript to use this website</noscript>

• Direct access to the Document Object Model (DOM)

APIs to access and manipulate the HTML document tree

• Does not directly access server databases or any other server resources.

• Only viable programming language for client-side scripting of web browsers

• Fairly universal syntax and capabilities across all browsers

Features of JavaScript (cont’d.)

Arrays and Objects

22

An array can be created in three ways:

1. Separate statement to assign each element:

var myCars = new Array();

myCars[0] = "Saab";

myCars[1] = "Volvo";

myCars[2] = "BMW";

2. Pass elements to Array constructor:

var myCars = new Array("Saab","Volvo","BMW");

3. Use an Array Literal:

var myCars = ["Saab","Volvo","BMW"];

Arrays in JavaScript

23

•Array elements are accessed by index number

Arrays are not associative, like in PHP (i.e. no alpha indices)

•Array indices are zero-based

1st element is element 0, 2nd element is index 1, etc.

•Use index in square brackets to access elements

Examples:

•Retrieve first element of myCars:

var name = myCars[0];

•Change first element of myCars:

myCars[0] = "Opel";

Accessing Array Elements

24

• Open-ended

Can add elements indefinitely at run-time

• Can contain any objects

All variables in JavaScript are objects of some type

Elements don’t have to be same data type

• Multidimensional

Elements can be arrays (see above)

Any number of dimensions

• Arrays are Objects

Several Properties and Methods:

• indexOf(), concat(), join(), push(), pop(), slice(), etc…

• Reference – http://www.w3schools.com/jsref/jsref_obj_array.asp

Other Features of Arrays

25

• Objects ~= Associative Arrays

• Can be defined dynamically (open-ended)

properties and methods can be added/removed at any time

very powerful feature

• Can be iterated over using for loop:

for (prop in obj) {

alert(obj[prop]);

}

Objects in JavaScript

26

Web Mastery with JavaScript

26

Object Syntax comparison

Dot Notation

Create empty objectvar obj = new Object();

Add property ‘name’ obj.name = 'John’;

Retrieve property ‘name'alert(obj.name);

Remove property ‘name’

delete obj.name;

Array Syntax

Create empty object

var obj = { };

Add property ‘name’

obj['name'] = 'John';

Retrieve property ‘name'

alert(obj['name']);

Remove property ‘name’

delete obj['name'];

JSON

28

Define object properties using bracketed list of name/value pairs:

{ key1: value1, key2: value2, ... }

var menuSetup = {

width: 300,

height: 200,

title: "Menu"

}

// same as:

var menuSetup = {}

menuSetup.width = 300

menuSetup.height = 200

menuSetup.title = 'Menu'

JavaScript Object Notation (JSON)

29

var user = {

name: "Rose",

age: 25,

size: {

top: 90,

middle: 60,

bottom: 90

}

}

alert( user.name ) // "Rose"

alert( user[‘size’][‘top’] ) // 90

Nested Objects (multidimensional array)

30

PHP’s json_encode() function

var_dump($responseArray): json_encode($responseArray):

// Assign above to var returnData

alert(returnData.custRec.CITY);

// displays “Burlington”

JavaScript

and the Browser

32

•Need to Understand:

HTML - Hypertext Markup Language

CSS - Cascading Style Sheets

DOM - Document Object Model

JavaScript is used often to access and manipulate these

elements.

JavaScript Browser Programming

33

• CSS stands for Cascading Style Sheets

• Styles define how to display HTML elements

help separate content from presentation.

• Styles are normally stored in Style Sheets

a list of styling rules

• External Style Sheets are stored in .css files

site-wide style changes can be made in one place

What is CSS?

34

•Selector: identifies a part of the document to be styled HTML tag name, Class name, or a Unique ID

•Property: A specific presentation attribute to be styled color, font-weight, border attributes, visibility

•Value: How the presentation attribute should be styled color: red; font-weight: bold; border: 2px solid blue;

CSS Style Rule Syntax

selector { property: value; property: value;...

}

body { font-size: 14pt; color: navy;...

}

Syntax: Example:

35

• HTML Tag Name:

BODY { font: arial; font-size: 12pt; color: navy }

Can use any HTML tag name Applies to all occurences of the tag throughout a document

• Class Name - precede with period (.) :

.error { color: red; font-weight: bold}

<p class=“error”>Invalid email address</p>

Can specify the same class on many different HTML tags

• Unique ID – precede with hash (#):

#shipto { visibility: hidden }

<div id=“shipto”> <table>... </div>

ID name should only occur once in HTML document

Examples of CSS Selectors

36

•Tag level: Inside a single HTML element (no selector)<table style=“border:none; color:blue”>

•Document level: Within <head> element of HTML page<head>

<style type=“text/css”>

table { border:none; color:blue }

</style>

</head>

•Site-wide level: External CSS file<head>

<link rel="stylesheet" type="text/css” href=“siteStyle.css" />

</head>

Where can Styles be specified?

37

Same web application, different style sheets

•No style sheet (i.e. browser default style sheet)

http://jvalance.com/webdemos/cust_list_table.php

•Style sheet 1:

http://jvalance.com/webdemos/cust_list_table_style.php

•Style sheet 2:

http://jvalance.com/webdemos/cust_list_table_style2.php

CSS Demo

38

<style>

tr.hilite td { background-color: lightblue }

</style>

<table id=“orderList”>

<tr onmouseover="this.className='hilite';" onmouseout="this.className='';" >

<td>Col-1</td><td>Col-2</td><td>Col-3</td>

</tr>

<tr onmouseover="this.className='hilite';" onmouseout="this.className='';" >

<td>Col-1</td><td>Col-2</td><td>Col-3</td>

</tr>

</table>

Example: Change BG color on hover

Demo: http://jvalance.com/jslab/complete/jslab03_comp.html

39

function toggleBox ( id ) {

var elem = document.getElementById(id);

if (elem.style.display == 'none') {

elem.style.display = '';

} else {

elem.style.display = 'none';

}

}

toggleBox(‘orderList’);

Example: Hide/Show function

• getElementById() retrieves a single unique element from document tree

• Assigned to local variable elem

• Attributes of this element can be accessed using dot notation

elem.style.visibility = “hidden”

<table id=“orderList” style=“visibilty: hidden”>Same

Demo: http://jvalance.com/jslab/complete/jslab02b_comp.html

40

Select unique element:

• node.getElementById("id");

var elem = document.getElementById(‘content-area’);

Select list of elements:

• node.getElementsByTagName("tag-name");

var input_tags = document.getElementsByTagName(“input”);

• node.getElementsByClassName(“class-name");

var list = document.getElementsByClassName("myButton");

for (var i = 0; i < list.length; i++) {

// list[i] is a node with the desired class name

}

Chained selectors:

document.getElementById("main").getElementsByTagName("p");

Accessing Document Elements

The Document Object Model

aka: The DOM

42

• DOM is how JavaScript accesses HTML elements

• HTML document = hierarchy of elements defined

by tags

• As browser loads document, elements are loaded

into Objects that JavaScript can easily access

• These objects form a model of the document

structure, and are tied directly to the display

If JavaScript modifies the DOM, the display is

immediately updated

Document Object Model

43

Web Mastery with JavaScript

43

HTML and DOM tree

HTML

<html>

<head>

<title>My

Document</title>

</head>

<body>

<h1>Header</h1>

<p>Paragraph</p>

</body>

</html>

DOM

44

•What is it?

API to access elements of HTML and XML documents

Heirarchical model of the HTML document tree

•DOM is how JavaScript accesses HTML elements

•HTML document = heirarchy of elements defined by tags

•As browser loads document, elements are loaded into

Objects that JavaScript can easily access

•These objects form a model of the document structure, and

are tied directly to the display

If JavaScript modifies the DOM, the display is immediately updated

Document Object Model

45

•Each DOM object can have properties:

Tag attributes

Tag contents

Nested HTML tags (= nested JS objects):

•JavaScript uses dot (.) notation to access objects and their properties:

document.searchForm.searchField.value = ‘javascript’;

•We can modify DOM properties using JavaScript

Makes document dynamic

•But - finding the right element in the DOM tree can be challenging!

DOM Object Properties

46

Web Mastery with JavaScript

46

HTML and DOM tree

HTML

<html>

<head>

<title>My Document</title>

</head>

<body>

<h1>Header</h1>

<p>Paragraph</p>

</body>

</html>

DOM

47

•W3C DOM is implemented as a tree of various types of Node objects

•Each Node object defines properties and methods for traversing and manipulating the tree.

Properties

• childNodes - a list of children of the node

• firstChild, lastChild, nextSibling, previousSibling, parentNode

Methods

• appendChild( ), removeChild( ), replaceChild( ), insertBefore( )

Navigating W3C DOM

48

•Can get at any element, but not easy.

•Starting at document root:

Traversing the DOM example

var theHtmlNode = document.childNodes[0];

var theBodyNode = theHtmlNode.childNodes[1];

var theParagraphNode = theBodyNode.childNodes[1];

alert( "theParagraphNode is a "

+ theParagraphNode.nodeName + " node!" );

49

•Very limited set of functions for accessing elements

•Awkwardness and Complexity of Code

Abstract DOM traversal and selection

• Arrays, Loops, Indexes

• Referencing Nodes and Elements

• Testing types and attributes of nodes

•Cross-browser compatability issues

•Performance

Problems with Basic JavaScript

50

Simplify coding of browser applications

• APIs eliminate cross-browser inconsistencies

• DOM access simplified

Traversal

Selection of elements

Modification, insertion, deletion of elements and attributes

• Greatly simplified selectors

• Event handling

• Animation

• Utility functions

• Ajax calls simplified/standardized

• High performance code base

JavaScript Frameworks

51

• jQuery

most widely used

•Prototype

•Mootools

•ExtJS

•Dojo

•YUI

•Midori

Popular JavaScript Frameworks

52

• Most widely used JavaScript

framework

• Greatly simplifies coding of

browser scripting

DOM selection and traversal

Cross browser API

Dynamic UI controls

Ajax calls

• Seamless integration with CSS

Easy to select elements via JavaScript

Easy to modify HTML attributes and

CSS properties

jQuery to the Rescue

• Intuitive syntax

well… mostly

• Open source and free

download from jQuery.com

• High performance and small file size

(~72K)

• No plug-ins required

Built on pure JavaScript

53

<div id=“box”>

•Using Core JavaScript:

•Using jQuery

Example: jQuery Toggle Visibility

function toggleBox () {var elem = document.getElementById('box');if (elem.style.display == "none") {

elem.style.display = "";} else {

elem.style.display = "none";}

}

$("#box").toggle();

54

• jQuery selectors = CSS selectors

HTML tag name

$(‘input’) – selects all <input> elements

$(‘p’) – selects all <p> elements

Class attribute

$(‘.inputLabel’) – selects any element with class=“inputLabel”

ID attribute

$(‘#mainContent’) – selects the element with id=“mainContent”

Selectors

55

Once elements are selected, we can call a variety of methods to alter the document

• hide(), show() and related methods

Saw these earlier

• addClass(), removeClass()

Add and remove a CSS class

• css()

Directly alter values of CSS properties

• attr(), removeAttr()

Change or remove HTML tag attributes

• text()

Change text contained between open/close tags

• insertBefore(), insertAfter, prepend() append(), remove(), replaceWith(), clone()

Allows insertion, deletion, moving, copying of HTML elements

Methods

jQuery API Documentation:

http://api.jquery.com/

56

•w3Schoolshttp://www.w3schools.com/jquery/jquery_examples.a

sp

•jQuery.com http://jquery.com/

http://api.jquery.com/

•jQueryUIhttp://jqueryui.com/demos/

jQuery Demos

Ajax and JSON

58

Asynchronous JavaScript and XML

• Allows calling a server script from within an HTML page via

JavaScript

Server script can be any language (PHP, Java, RPG)

Call is asynchronous (JavaScript doesn't wait for response)

Can specify a JavaScript function to be called when response is received

• No page reload

• Can retrieve and update data on server very quickly

Sub-second response is typical (like a local PC application)

Can modify page contents or styling based on what's returned by the

server script

• Ajax calls are simplified by using jQuery

Eliminates cross-browser syntactical differences

Ajax

59

•$.get(<url>, <callback-function>);

•$.post(<url>, <data>, <callback-function>);

•Data returned by server script can be any format

XML, HTML, JSON

Making an Ajax Call

// Event handler for click on get customer buttonfunction handleGetCustButtonClick() {

var url = 'getCustomer.php?custNum=1234';$.get(url, processGetCustResponse);

}

// Callback function for Ajax responsefunction processGetCustResponse( data ) {

alert('data returned = ' + data);}

60

JSON = JavaScript Object Notation

• Simpler, more compact format than XML

Basically a list of name:value pairs enclosed in braces

{"error":true, "message":"Invalid zip code"}

• Easy to use and parse

• PHP has json_encode() function

Transform variables into JSON as

• {<var-name>:<var-value>}

Can be used with associative/multi-dimensional arrays

• JavaScript can automatically parse JSON response into JavaScript

object

JSON

61

PHP's json_encode() function

var_dump($responseArray): json_encode($responseArray):

// Callback function for Ajax responsefunction processAjaxResponse( data ) {

alert('Cust name is ' + data.custRec.NAME);}

62

$.ajax( { …// json parameters … } );

https://tutorialzine.com/2009/09/simple-ajax-website-jquery

https://demo.tutorialzine.com/2009/09/simple-ajax-website-jquery/demo.html

Generic $.ajax() method – using JSON data

References

64

JavaScript

• w3schools: http://www.w3schools.com/js/

• javascript.info: http://javascript.info/

• Mozilla: https://developer.mozilla.org/en-US/docs/Web/JavaScript

• DevGuru: http://www.devguru.com/technologies/javascript/home

DOM

• Mozilla: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM

• w3schools: http://www.w3schools.com/jsref/dom_obj_document.asp

The Rhino Book:

• JavaScript – The Definitive Guide

by David Flanagan; O’ReillyMedia

http://shop.oreilly.com/product/9780596805531.do

Must-have reference

References and Examples

Thanks for Attending!

Please sign up for

the Div1Sys newsletter

66

Web Mastery with JavaScript

66

Bring Web Application to Life with jQuery

Contact Information

John Valance

[email protected]

802-355-4024

Division 1 Systems

http://www.div1sys.com