Presentation is loading. Please wait.

Presentation is loading. Please wait.

CMPE 280 Web UI Design and Development February 22 Class Meeting

Similar presentations


Presentation on theme: "CMPE 280 Web UI Design and Development February 22 Class Meeting"— Presentation transcript:

1 CMPE 280 Web UI Design and Development February 22 Class Meeting
Department of Computer Engineering San Jose State University Spring 2018 Instructor: Ron Mak

2 Assignment #2 Requirements
Assigned Thursday, Feb. 15 Due Monday, Feb. 26 At least one HTML form with input validation JavaScript and/or CSS Layout and formatting with CSS header and sidebar main body User interactivity with JavaScript It all happens in the browser only.

3 Assignment #2, cont’d This assignment is primarily about the client side. Make any necessary changes to your server-side code to make your client-side components work. Brief (2- or 3-page) report: Describes what input validation and interactivity features you added on the client side. Mention any improvements you may have made on the server side. Include any necessary instructions to run your code. port numbers, login usernames and passwords, etc.

4 More JavaScript Regular Expressions
JavaScript uses regular expressions for more than just pattern matching. You can use regular expressions also for string manipulation.

5 Example: Reversing Names
Suppose you had a list of names, such as You want to reverse the names, last name first, and insert a comma: Bill Clinton George Bush Barack Obama Donald Trump Clinton, Bill Bush, George Obama, Barack Trump, Donald Demo

6 Reversing Names, cont’d
re/reverse.html <body> <h1>Reverse names:</h1> <form action=""> Enter a list of names with first name first, one per line:<br> <textarea id="names" rows="10" cols="50"></textarea> <p> <input type="button" value="Reverse names" onclick=reverseNames() /> <input type="reset" /> </p> </form> </body>

7 Reversing Names, cont’d
function reverseNames() { var names = document.getElementById("names").value; var splitter = /\s*\n\s*/; var nameList = names.split(splitter); var newList = new Array; var reverser = /(\S+)\s(\S+)/; for (var i = 0; i < nameList.length; i++) { if (nameList[i].trim().length > 0) { newList[i] = nameList[i].replace(reverser, "$2, $1"); newNames += newList[i] + "\n"; } document.getElementById("names").value = newNames; re/reverse.js Use the pattern to split the string into an array of names. The pattern separates the names. \s is a whitespace character. We can improve this regular expression! \S = non-whitespace character Replace each name string according to the matching pattern.

8 Example: Formatting Names
Suppose you allow users to be sloppy: But you still want: BiLL CLinTON GeOrGe BuSh barack OBAMA dOnAlD truMP Clinton, Bill Bush, George Obama, Barack Trump, Donald Demo

9 Formatting Names, cont’d
Our regular expression for formatting names: Split the first and last names each into an initial letter followed by the rest of the letters. Call the regular expression’s exec() method on a string. Automatically sets JavaScript’s built-in RegExp object. Use RegExp.$1, RegExp.$2, etc. to access stored parts of the match. var formatter = /\s*(\S)(\S+)\s+(\S)(\S+)\s*/

10 Formatting Names, cont’d
re/format.js var newNames = ""; for (var i = 0; i < nameList.length; i++) { if (nameList[i].trim().length > 0) { formatter.exec(nameList[i]); newList[i] = RegExp.$3.toUpperCase() + RegExp.$4.toLowerCase() + ", " + RegExp.$1.toUpperCase() + RegExp.$2.toLowerCase(); newNames += newList[i] + "\n"; }

11 More Document Object Model (DOM)
Recall the DOM. Example: JavaScript, 9th ed. by Tom Negrino and Dori Smith Peachpit Press, 2015 ISBN

12 DOM, cont’d Also recall how we used innerHTML and JavaScript to modify the DOM: <body> <form action=""> <fieldset> ... </fieldset> </form> <div id="outputDiv"> <p>Output will appear here.</p> </div> </body> document.getElementById("outputDiv").innerHTML = "<p><strong>" + x + " + " + y + " = " + sum + "</strong></p>”;

13 DOM, cont’d Using innerHTML is error-prone.
document.getElementById("outputDiv").innerHTML = "<p><strong>" + x + " + " + y + " = " + sum + "</strong></p>"; Using innerHTML is error-prone. You can create elements with unclosed tags, or invalid tags. A safer way to modify the DOM is to use JavaScript’s DOM manipulation API. Demo

14 Example: DOM Modification
<head>     <title>Node Actions</title>     <script src="nodes.js"></script> </head> <body>     <h1>Node actions</h1>     <form id="theForm">         Enter some text and choose an action:         <p><textarea id="textArea" rows="5" cols="30"></textarea></p>         <p>             Node action:             <select id="chooser">                 <option value="Add">Add to end</option>                 <option value="Insert">Insert before</option>                 <option value="Replace">Replace</option>                 <option value="Delete">Delete</option>             </select>             Paragraph:              <select id="indexer"></select>             <input type=button value="Do it!" onclick=nodeAction() />         </p>     </form>     <hr />     <div id="workspace"> </div> </body> dom/nodes.html The node whose children we will manipulate using JavaScript’s DOM API.

15 DOM Modification, cont’d
dom/nodes.js window.onload = init; var textArea; var chooser; var indexer; var workspace; function init() { textArea = document.getElementById("textArea"); chooser = document.getElementById("chooser"); indexer = document.getElementById("indexer"); workspace = document.getElementById("workspace"); }

16 DOM Modification: Add a Child Node
dom/nodes.js function addNode() { var text = textArea.value; var textNode = document.createTextNode(text); var pNode = document.createElement("p"); pNode.appendChild(textNode); workspace.appendChild(pNode); textArea.value = ""; }

17 DOM Modification: Insert a Child Node
dom/nodes.js function insertNode() { var textNode = textArea.value; var index = indexer.selectedIndex; var textNode = document.createTextNode(textNode); var pNode = document.createElement("p"); pNode.appendChild(textNode); var pNodes = workspace.getElementsByTagName("p"); var chosenPNode = pNodes.item(index); workspace.insertBefore(pNode, chosenPNode); textArea.value = ""; }

18 DOM Modification: Replace a Child Node
dom/nodes.js function replaceNode() { var text = textArea.value; var index = indexer.selectedIndex; var textNode = document.createTextNode(text); var pNode = document.createElement("p"); pNode.appendChild(textNode); var pNodes = workspace.getElementsByTagName("p"); var chosenPNode = pNodes.item(index); workspace.replaceChild(pNode, chosenPNode); textArea.value = ""; }

19 DOM Modification: Delete a Child Node
dom/nodes.js function deleteNode() { var index = indexer.selectedIndex; var pNodes = workspace.getElementsByTagName("p"); var chosenPNode = pNodes.item(index); workspace.removeChild(chosenPNode); }

20 Custom JavaScript Objects
At run time, a JavaScript variable can have any value. Create a custom object simply by giving it properties and methods.

21 Example Custom JavaScript Object
objects/person.html var person = new Object(); person.name = "Mary"; person.age = 20; person.nextYear = function() { return this.age + 1; }; alert("Name = " + this.name + ", age = " + this.age + ", age next year = " + this.nextYear()); Demo

22 JavaScript Classes and Objects
A JavaScript class has a constructor function. Example: Convention: Capitalized constructor name. function Person(name, age) { this.name = name; this.age = age; this.nextYear = function() return this.age + 1; }; }

23 Example Object Instantiation
Use the constructor to create new instances: objects/people.html function createPeople() { mary = new Person("Mary", 20); john = new Person("John", 25); showPerson(mary); showPerson(john); } function showPerson(p) alert("Name = " + p.name + ", age = " + p.age + ", age next year = " + p.nextYear()); Demo

24 Prototype Objects A JavaScript class is a set of objects that inherit properties from the same prototype object. Person.prototype = { toString: function() { return "Person[name: '" + this.name + "', age: " + this.age + "]"; } function createPeople() mary = new Person("Mary", 20); john = new Person("John", 25); alert(mary); alert(john); objects/prototype.html Demo

25 Web Browser – Web Server Cycle
Each time you submit form data from the web browser to the web server, you must wait for: The data to upload to the web server. The web server to generate the next web page. The next web page to download to your browser. Your browser to render the next web page. You experience a noticeable page refresh.

26 Web Browser – Web Server Cycle, cont’d
Example: Click the submit button. JavaScript code on the server opens and reads a text file and generates a new web page containing the contents of the text file. The browser displays the new web page.

27 Web Browser – Web Server Cycle, cont’d
<body>     <form action="text-response"           method="get">         <fieldset>             <legend>User input</legend>             <p>                 <label>First name:</label>                 <input name="firstName" type="text" />             </p>                 <label>Last name:</label>                 <input name="lastName" type="text" />                              <input type="submit" value="Submit" />         </fieldset>     </form> </body> Client side

28 Web Browser – Web Server Cycle, cont’d
Server side // Process the form data and send a response. app.get('/text-response’,      function(req, res)     {         var firstName = req.param('firstName');         var lastName  = req.param('lastName');         var html = 'Hello, ' + firstName + ' ' + lastName + '!';                  res.send(html);     } );

29 AJAX Asynchronous JavaScript and XML
Tighter communication between the web browser and the web server. Shortens the browser-server cycle. The server generates and downloads part of a page. The web browser refreshes only the part of the page that needs to change. The browser and server work asynchronously. The browser does not have to wait for the download from the server.

30 AJAX Example We will compare AJAX to non-AJAX. Demo

31 AJAX Example, cont’d var express = require('express');
routes/index.js var express = require('express'); var router = express.Router(); var ctrlMain = require("../controllers/main"); router.get('/', ctrlMain.home); router.get('/non-ajax', ctrlMain.get_nonajax); router.post('/non-ajax', ctrlMain.post_nonajax); router.get('/ajax', ctrlMain.get_ajax); router.post('/ajax', ctrlMain.post_ajax); module.exports = router;

32 AJAX Example, cont’d var lineReader = require('line-reader');
function sendPage(fileName, result) {     var html = '';          lineReader.eachLine(fileName,         function(line, last)         {             html += line + '\n';             if (last)              {                  result.send(html);                 return false;              }             else             {                 return true;         }); } controllers/main.js

33 AJAX Example, cont’d controllers/main.js
module.exports.home = function(request, result)  {     sendPage('index.html', result); }; module.exports.get_nonajax = function(request, result)      sendPage('nonajax.html', result); module.exports.post_nonajax = function(request, result)      sendPage('nonajax2.html', result); module.exports.get_ajax = function(request, result)      sendPage('ajax.html', result); module.exports.post_ajax = function(request, result)      sendPage('lorem.txt', result); controllers/main.js

34 AJAX Example, cont’d nonajax.html <head> ...
    ...     <script type="text/javascript" src="common.js"></script> </head> <body onload = "init()">     <h1>Non-AJAX</h1>          <canvas id = "canvas"             height = "200"             width = "200">         <p>Canvas not supported!</p>     </canvas>     <form action="non-ajax" method="post">         <input type="submit" />     </form>     <hr />     <div id="output">         <p>             Watch this space!         </p>     </div> </body> nonajax.html

35 AJAX Example, cont’d <head> ...
    ...     <script type="text/javascript" src="common.js"></script> </head> <body onload = "init()">     <h1>Non-AJAX</h1>          <div id="output">         <p>             Lorem ipsum dolor sit amet, <br>             consectetur adipiscing elit, <br>             sed do eiusmod tempor incididunt <br>             ut labore et dolore magna aliqua.                 </p>     </div> </body> nonajax2.html

36 AJAX Example, cont’d const CANVAS_W = 200; const CANVAS_H = 200;
const IMAGE_W  = 20; const IMAGE_H  = 20; const RIGHT    = CANVAS_W - IMAGE_W; const BOTTOM   = CANVAS_H - IMAGE_H; var con; var image; var x  = 0; var y  = 0; var dx = 5; var dy = 3; function init() {     con = document.getElementById("canvas")           .getContext("2d");     con.strokeStyle = "black";               setInterval(draw, 50); } public/common.js

37 AJAX Example, cont’d public/common.js function draw() {
    con.fillStyle = "white";     con.fillRect(0, 0, CANVAS_W, CANVAS_H);     con.strokeRect(0, 0, CANVAS_W, CANVAS_H);          con.fillStyle = "green";     con.fillRect(x, y, IMAGE_W, IMAGE_H);     x += dx;     y += dy;     // Bounce off a wall     if ((x < 0) || (x > RIGHT))  dx = -dx;     if ((y < 0) || (y > BOTTOM)) dy = -dy; }

38 AJAX Example, cont’d ajax.html <head> ...
    ...     <script type = "text/javascript" src="common.js"></script> </head> <body onload = "init()">     <h1>AJAX</h1>          <canvas id = "canvas"             ...     </canvas>     <form action="">         <button type="button"                  onclick="doAJAX()">             Click for AJAX!         </button>     </form>     <hr />     <div id="output">         <p>Watch this space!</p>     </div> </body> ajax.html

39 AJAX Example, cont’d public/common.js var request; function doAJAX() {
    request = new XMLHttpRequest();     request.open("POST", "/ajax");     request.onreadystatechange = displayFile;     request.send(null); } function displayFile()     if (request.readyState == 4) {         if (request.status == 200) {             var text = request.responseText;             text = text.replace(/\n/g, "<br />");             document.getElementById("output").innerHTML =                     "<p>" + text + "</p>";         }     } Function displayFile() will be called asynchronously.

40 The XMLHttpRequest Object
Use the properties and methods of the XMLHttpRequest object to control a request from the web browser to the web server. See also: JavaScript, 9th ed. by Tom Negrino and Dori Smith Peachpit Press, 2015 ISBN

41 readyState Property Values
JavaScript, 9th ed. by Tom Negrino and Dori Smith Peachpit Press, 2015 ISBN


Download ppt "CMPE 280 Web UI Design and Development February 22 Class Meeting"

Similar presentations


Ads by Google