web mastery with javascript - neugc - … mastery with javascript 17 features of javascript...

52
Web Mastery with JavaScript 1 WEB MASTERY WITH JAVASCRIPT John Valance Division 1 Systems [email protected] All materials copyright © 2014 - 2017 <div1>

Upload: lyphuc

Post on 16-Apr-2018

225 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

1

WEB MASTERY

WITH JAVASCRIPT

John Valance

Division 1 [email protected]

All materials copyright © 2014 - 2017 <div1>

Page 2: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

2 <div1>

About John Valance

• Independent Consultant

• Founder and CTO of Division 1 Systems

• Specialty is helping IBM shops develop web applications and related skills

• Training, mentoring, project management, consultation and coding

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

• 12+ years of web development experience

• Web scripting language of choice = PHP

• Frequent presenter on web development topics

• Trainer for Zend Technologies

• Teaches Intro to PHP for RPG programmers

• Zend Certified Engineer

Page 3: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

3 <div1>

What is JavaScript?

• 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.

Page 4: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

4 <div1>

Web Application Architecture

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

Page 5: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

5 <div1>

Dynamic Web Page Content

On the Server:

• PHP + SQL

• Retrieve database information

• Generate HTML document on the fly

• Deliver entire HTML document to browser

• Includes HTML, CSS, JavaScript

On the Client (i.e. Browser):

• JavaScript + CSS

• can modify any part of the document

• (HTML and/or CSS)

Page 6: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

6 <div1>

What Can JavaScript Do?

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

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

Page 7: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

7 <div1>

The <script> tag

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

Page 8: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

8 <div1>

JavaScript Example – input validation

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

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

Page 9: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

9 <div1>

User Interaction: alert / confirm / prompt

alert('Hello world!');

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

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

Page 10: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

10 <div1>

Where Is JavaScript Coded in the Document?

• 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

• Usually done in <head> section

Page 11: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

11 <div1>

JavaScript - Inline vs. Functions

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

Page 12: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

12 <div1>

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

function myFunction( parm1, parm2 ) {

// Function body statements…

}

• Can also be included as external file

• 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

Page 13: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

13 <div1>

JavaScript Example

<html>

<head>

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

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

<script>

function sayHello( ) {

alert(“Hello!!”);

}

</script>

</head>

<body>

<script>

sayHello();

</script>

</body>

</html>

Page 14: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

14 <div1>

JavaScript Event Handling

• JavaScript can react to events in the browser• mouse clicks,

• mouse movement,

• keystrokes,

• movement in and out of form fields, etc.

• Event handlers start with “on…”• onclick,

• onfocus,

• onblur,

• onmouseover,

• onmouseout

Page 15: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

15 <div1>

JavaScript Event Handling

• “Event handlers” coded as HTML tag attributes

• Specify JavaScript to execute

• Either individual statements or function calls

<body onload=“setInputDefaults();”>

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

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

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

Page 16: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

16 <div1>

Features of the JavaScript Language

• 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

Page 17: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

17 <div1>

Features of JavaScript (cont’d.)

• 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

Page 18: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

18 <div1>

Arrays in JavaScript

An array can be created in three ways:

• Separate statement to assign each element:var myCars = new Array();

myCars[0] = "Saab";

myCars[1] = "Volvo";

myCars[2] = "BMW";

• Pass elements to Array constructor:var myCars = new Array("Saab","Volvo","BMW");

• Use an Array Literal:var myCars = ["Saab","Volvo","BMW"];

Page 19: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

19 <div1>

Accessing Array Elements

• 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";

Page 20: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

20 <div1>

Other Features of Arrays

• 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

Page 21: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

21 <div1>

Objects in JavaScript

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

}

Page 22: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

22 <div1>

Object Syntax comparison

Dot Notation

Create empty object

var 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'];

Page 23: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

23 <div1>

JavaScript Object Notation (JSON)

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'

Page 24: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

24 <div1>

Nested Objects (multidimensional array)

var user = {

name: "Rose",

age: 25,

size: {

top: 90,

middle: 60,

bottom: 90

}

}

alert( user.name ) // "Rose"

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

Page 25: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

25 <div1>

PHP’s json_encode() function

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

// Assign above to var returnData

alert(returnData.custRec.CITY);

// displays “Burlington”

Page 26: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

26 <div1>

JavaScript Browser Programming

• Need to Understand:

• HTML

• CSS

• DOM

JavaScript is used often to access/manipulate these

• HTML = Hypertext Markup Language

• CSS = Cascading Style Sheets

• DOM = Document Object Model

Page 27: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

27 <div1>

What is CSS?

• CSS stands for Cascading Style Sheets

• Extension to HTML, allowing fine-grained control

over visual aspects of rendering document

• 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.

Page 28: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

28 <div1>

CSS Style Rule Syntaxselector {

property: value;

property: value;

...

}

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

coming…)

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

Page 29: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

29 <div1>

Examples of CSS Selectors

• 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 styling rule 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

Page 30: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

30 <div1>

Where can Styles be specified?

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

Page 31: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

31 <div1>

Demos of CSS Stylesheets

• Inline style sheet in head

• http://jvalance.com/webdemos/

• sitestyle.css, used in customer inquiry demo

• http://jvalance.com/web20/cust_inq_ctrl.php

• CSS Zend Garden

• http://www.csszengarden.com

Page 32: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

32 <div1>

Example: Change BG color on hover

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

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

Page 33: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

33 <div1>

Example: Hide/Show function

function toggleBox ( id ) {

var elem = document.getElementById(id);

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

elem.style.display = '';

} else {

elem.style.display = 'none';

}

}

toggleBox(‘orderList’);

• 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

Page 34: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

34 <div1>

Accessing Document Elements

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

Page 35: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

35 <div1>

Document Object Model

• 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

Page 36: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

36 <div1>

DOM Object Properties

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

Page 37: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

37 <div1>

HTML and DOM tree

HTML

<html>

<head>

<title>My Document</title>

</head>

<body>

<h1>Header</h1>

<p>Paragraph</p>

</body>

</html>

DOM

Page 38: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

38 <div1>

Navigating W3C DOM

• 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( )

Page 39: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

39 <div1>

Traversing the DOM example

• Can get at any element, but not easy.

• Starting at document root:

var theHtmlNode = document.childNodes[0];

var theBodyNode = theHtmlNode.childNodes[1];

var theParagraphNode = theBodyNode.childNodes[1];

alert( "theParagraphNode is a "

+ theParagraphNode.nodeName + " node!" );

Page 40: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

40 <div1>

Problems with Basic JavaScript

• 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

Page 41: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

41 <div1>

JavaScript Frameworks

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

Page 42: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

42 <div1>

Popular JavaScript Frameworks

• jQuery

• most widely used

• Prototype

• Mootools

• ExtJS

• Dojo

• YUI

• Midori

Page 43: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

43 <div1>

Example: Toggle Visibility

• Core JavaScript: function toggleBox () {

var elem = document.getElementById('box');

if (elem.style.visibility == "hidden") {

elem.style.visibility = "visible";

} else {

elem.style.visibility = "hidden;

}

}

• Using jQuery

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

<div id=“box”>

Page 44: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

44 <div1>

jQuery Syntax$("selector").method();

• $( )

• Dollar function - this calls jQuery

• Synonymous with calling jQuery( )

• This example could be coded jQuery("#box").toggle();

• $("#box")

• This selects the element with id=“box”

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

• This toggles the visibility (hidden/visible) of the box element

• Same as if statement in previous slide

• Other visibility methods besides toggle():show(), hide(), slideDown(), slideUp(),

slideToggle(), fadeIn(), fadeOut()

Page 45: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

45 <div1>

Selectors

• 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”

Page 46: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

46 <div1>

Methods

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

Page 47: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

47 <div1>

jQuery Demos

• w3Schools

• http://www.w3schools.com/jquery/jquery_examples.asp

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

• http://api.jquery.com/

• jQueryUI

• http://jqueryui.com/demos/

Page 48: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

48 <div1>

Ajax

• 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

Page 49: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

49 <div1>

Ajax (cont’d.)

• 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

Page 50: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

50 <div1>

Making an Ajax Call using jQuery

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

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

• Data returned by server script can be any format

• XML, HTML, JSON

function clickButton() {var url = 'getCustomer.php?custNum=1234';$.get(url, processResponse);

}

function processResponse( data ) {alert('data returned = ' + data);

}

Page 51: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

51 <div1>

References and Examples

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

Page 52: WEB MASTERY WITH JAVASCRIPT - NEUGC - … Mastery with JavaScript 17  Features of JavaScript (cont’d.) •Runs on client, in browser • Code is downloaded from server

Web Mastery with JavaScript

52 <div1>

Contact Information

John Valance

[email protected]

802-355-4024

Division 1 Systems

www.div1sys.com

Contact me with any questions