Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Web Mastery with JavaScript

17 views

Published on

This session will introduce you to the concepts, capabilities and syntax of JavaScript, and help you understand how you might use JavaScript in your web applications. You will learn about using JavaScript to validate input forms and react to browser events such as page load, button clicks, mouse movement and keystrokes. You will also see how JavaScript can be used to change the content and appearance of web pages without reloading the entire page. It will also introduce some of the more advanced concepts of object oriented JavaScript and JSON (JavaScript Object Notation), Ajax (Asynchronous JavaScript and XML), and JavaScript frameworks, such as jQuery, which greatly simplify JavaScript programming tasks.

Published in: Software
  • Be the first to comment

  • Be the first to like this

Web Mastery with JavaScript

  1. 1. Web Mastery with JavaScript John Valance Division 1 Systems johnv@div1sys.com © 2014-2018 Division 1 Systems <div1> www.div1sys.com
  2. 2. 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
  3. 3. What Is JavaScript?
  4. 4. 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. 5. 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. 6. 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. 7. 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. 8. 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. 9. 9 alert('Hello world!'); var isOK = confirm('Are you sure?’); var favColor = prompt(‘Enter your favorite color:','blue'); User Interaction: alert / confirm / prompt
  10. 10. 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?
  11. 11. Coding JavaScript Functions
  12. 12. 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. 13. 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. 14. 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
  15. 15. Event Handling
  16. 16. 16 •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 JavaScript Event Handling
  17. 17. 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();”>
  18. 18. JavaScript Langage Features
  19. 19. 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. 20. 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.)
  21. 21. Arrays and Objects
  22. 22. 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. 23. 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. 24. 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. 25. 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. 26. 26 Web Mastery with JavaScript 26 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'];
  27. 27. JSON
  28. 28. 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. 29. 29 var user = { name: "Rose", age: 25, address: { street: ‘1254 State St.’, city: ‘Montpelier’, state: ‘VT’, zip: 05403 } } alert( user.name ) // "Rose" alert( user[‘address’][‘city’] ) // “Montpelier” Nested Objects (like multidimensional array)
  30. 30. 30 PHP’s json_encode() function var_dump($responseArray): json_encode($responseArray): // Assign above to var returnData alert(returnData.custRec.CITY); // displays “Burlington”
  31. 31. JavaScript and the Browser
  32. 32. 32 •Need to Understand:  HTML - Hypertext Markup Language  CSS - Cascading Style Sheets  DOM - Document Object Model JavaScript is used to access and manipulate these elements. JavaScript Browser Programming
  33. 33. CSS
  34. 34. 34 • 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?
  35. 35. 35 •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:
  36. 36. 36 • 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
  37. 37. 37 •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?
  38. 38. 38 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
  39. 39. 39 <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
  40. 40. 40 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
  41. 41. 41 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
  42. 42. The Document Object Model aka: The DOM
  43. 43. 43 • 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
  44. 44. 44 Web Mastery with JavaScript 44 HTML and DOM tree HTML <html> <head> <title>My Document</title> </head> <body> <h1>Header</h1> <p>Paragraph</p> </body> </html> DOM
  45. 45. 45 •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
  46. 46. 46 •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!" );
  47. 47. 47 •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
  48. 48. JavaScript Frameworks – jQuery
  49. 49. 49 Many JavaScript frameworks exist today, to simplify browser-based programming • 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 jQuery is most widely used JS framework JavaScript Frameworks
  50. 50. 50 • 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
  51. 51. 51 <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();
  52. 52. 52 • 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
  53. 53. 53 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/
  54. 54. 54 •w3Schools http://www.w3schools.com/jquery/jquery_examples.a sp •jQuery.com  http://jquery.com/  http://api.jquery.com/ •jQueryUI http://jqueryui.com/demos/ jQuery Demos
  55. 55. Ajax and JSON
  56. 56. 56 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
  57. 57. 57 •$.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 button function handleGetCustButtonClick() { var url = 'getCustomer.php?custNum=1234'; $.get(url, processGetCustResponse); } // Callback function for Ajax response function processGetCustResponse( data ) { alert('data returned = ' + data); }
  58. 58. 58 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
  59. 59. 59 PHP's json_encode() function var_dump($responseArray): json_encode($responseArray): // Callback function for Ajax response function processAjaxResponse( data ) { alert('Cust name is ' + data.custRec.NAME); }
  60. 60. 60 $.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
  61. 61. References
  62. 62. 62 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 References and Examples
  63. 63. Thanks for Attending! Please sign up for the Div1Sys newsletter
  64. 64. 64 Web Mastery with JavaScript 64 Bring Web Application to Life with jQuery Contact Information John Valance johnv@div1sys.com 802-355-4024 Division 1 Systems http://www.div1sys.com

×