CS 174: Web Programming October 26 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak www.cs.sjsu.edu/~mak Web Browser – Web Server Cycle Each time you submit form data from the web browser to the web server, you must wait : 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. Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 2 Web Browser – Web Server Cycle, cont’d Example: Click the submit button. PHP 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. Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 3 Web Browser – Web Server Cycle, cont’d <form action="nonajax.php" method="get"> <input type="hidden" name="hidden" value="hidden" /> <input type="submit" /> </form> <hr /> <div id="output"> <p> <?php $hidden = filter_input(INPUT_GET, "hidden"); if ($hidden != NULL) { $fp = fopen("lorem.txt", "r") or die("File error."); while (!feof($fp)) { $line = fgets($fp); $line = str_replace("\n", "<br />", $line); print " $line\n"; } } else { print " Watch this space!\n"; } ?> </p> nonajax.php </div> Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 4 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. Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 5 AJAX, cont’d <body onload = "init()"> <h1>AJAX</h1> ajax.html <canvas id = "canvas" height = "200" width = "200"> <p>Canvas not supported!</p> </canvas> <form action=""> <button type="button" onclick="doAJAX()"> Click for AJAX! </button> </form> <hr /> <div id="output"> <p>Watch this space!</p> </div> </body> Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 6 AJAX, cont’d ajax.html var request; function doAJAX() { request = new XMLHttpRequest(); request.open("GET", "lorem.txt"); 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>"; } } CS 174: Web Programming }Computer Science Dept. Fall 2015: October 26 © R. Mak 7 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: http://www.w3schools.com/xml/dom_http.asp Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak JavaScript, 9th ed. by Tom Negrino and Dori Smith Peachpit Press, 2015 ISBN 978-0-321-99670-1 8 readyState Property Values Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak JavaScript, 9th ed. by Tom Negrino and Dori Smith Peachpit Press, 2015 ISBN 978-0-321-99670-1 9 jQuery A lightweight but powerful JavaScript library. Greatly simplifies JavaScript programming, especially animation and AJAX. Adds new capabilities to DOM elements. Adds new user interface widgets. Cross-platform: Works with different browsers. Highly extensible. Free and open source. Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 10 jQuery Downloads Visit jquery.com Download either jQuery 1.11.3 jQuery 2.1.4 Same as jQuery 1.x but without support for Microsoft Internet Explorer The compressed versions will enable your web pages that use jQuery to download faster. Create a symbolic link jquery.js to the version you downloaded. Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 11 Using the jQuery Library To use the jQuery library in your web page: <script type="text/javascript” src ="jquery.js"> </script> You can also download from a Content Delivery Network (CDN) such as Google hosted libraries: <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"> </script> Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 12 jQuery API For the complete jQuery API, see http://api.jquery.com Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 13 Simple AJAX with jQuery ajax.html <body> <h1>Simple AJAX with jQuery</h1> <div id="output"></div> </body> ajax.js $(document).ready(init); function init() { $("#output").load("lorem.txt"); } Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak Demo 14 jQuery Objects Create a jQuery object from a DOM element. Use the $() function. Example: $("#output") creates a jQuery object from the div with id output: <div id="output"></div> Simpler than: document.getElementById("output") Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 15 jQuery Objects, cont’d A jQuery object adds new functionality to its DOM element. Example: $("#output").load("lorem.txt"); Perform an AJAX document load and replace the contents of the div with the document contents. Example: $("#output").html("<h2><em>Hello, world!</em></h2>"); Equivalent to: document.getElementById("output") Computer Science Dept. CS 174: Web Programming Fall 2015: October 26 © R. Mak .innerHTML("<h2><em>Hello, world!</em></h2>"); 16 jQuery Initialization Instead of: <body onload="init()"> Call init() after the entire page is displayed. Use the jQuery statement: $(document).ready(init); Call init() after the entire page is loaded but before the page displays. A shortcut: $(init); Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 17 Selecting Elements jQuery uses CSS-style selectors. Example: $("h1") Refer to all h1 headings. Example: $("#output") Refer to the object with id output. Example: $(".indented") Refer to the objects with class indented. Example: $("li img"); Refer to images that are in list items. Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 18 Setting Style Use jQuery’s css() method to set the style of an object or a set of objects. Example: Two parameters $("h1").css("backgroundColor", "yellow"); Set the background of all h1 headings to yellow. Example: One parameter: JavaScript Object Notation (JSON) $("#warning").css( {"backgroundColor":"yellow", "color":"red"} ); Set the background of the paragraph with id warning to yellow and its text to red. Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 19 Example: Hover Event <body> hover.html <h1>Hover Demo</h1> <ul> <li>Computer Science</li> <li>Mathematics</li> <li>Physics</li> <li>Chemistry</li> </ul> </body> Note: $this refers to a DOM element. $(this) refers to the corresponding jQuery object. Computer Science Dept. Fall 2015: October 26 Demo $(init); hover.js function init() { $("li").hover(highlight, plain); } function highlight() { $(this).css( {"background": "black", "color": "white"} ); } function plain() { $(this).css( {"background": "white", "color": "black"} ); CS 174: Web Programming 20 ©} R. Mak jQuery Events Mouse click dblclick mousedown mouseup mouseover mouseout mousemove hover load unload ready resize scroll Keyboard keypress keydown keyup Document/window Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 21 jQuery Events, cont’d Form submit reset change focus blur Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 22 Changing Classes Dynamically addClass() removeClass() toggleClass() class.css .highlighted { background: red; color: yellow; } $(init); class.js function init() { $("li").click(toggleHighlight); } function toggleHighlight() { $(this).toggleClass("highlighted"); Computer Science Dept. CS 174: Web Programming } Fall 2015: October 26 © R. Mak Demo 23 jQuery/AJAX Templates jQuery and AJAX make it easy to create a template for a content management system. Dynamically construct the parts of the CMS at run time from data files on the web server. Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak Demo 24 jQuery/AJAX Templates, cont’d courses.html <body> <div id="all"> <div id="header"></div> <div id="menu"> <h2>Courses</h2> <div id="names"></div> </div> Only one course div in the template. <div class="course"></div> <div id="footer"></div> </div> </body> Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 25 jQuery/AJAX Templates, cont’d courses.js $(init); function init() { $("#header").load("parts/header.html"); ... $("#footer").load("parts/footer.html"); } Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 26 jQuery/AJAX Templates, cont’d function init() courses.js { ... var files = new Array("CS149.html", "CS153.html", "CS174.html", "CS235.html"); var nameItems = "<ul>\n" + courseName(files[0]); var course = $(".course"); course.load("courses/" + files[0]); for (var i = 1; i < files.length; i++) { course = course.clone().insertAfter(course); “function chaining” course.load("courses/" + files[i]); nameItems += courseName(files[i]); } nameItems += "</ul>\n"; $("#names").html(nameItems); ... } Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 27 jQuery/AJAX Templates, cont’d function courseName(name) courses.js { return " <li><a href=''>" + name.split(".")[0] + "</a></li>"; } Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 28 Automatic Looping with each() Most jQuery methods automatically loop over each element in a selection. Example: $("img").hide(); Make every image disappear. Use the each() function to provide your own callback function to apply to each element in a selection. Example: $("img").each(myFunction); Call function myFunction() on each image. Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 29 Automatic Looping with each(), cont’d <body> <div class="text"> <h1>Automatic Pull Quotes</h1> pullquote.html <h2>Vestibulum semper</h2> <p> Vestibulum semper tincidunt sem. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec pulvinar, justo non fringilla dapibus, sapien tortor cursus erat, at posuere magna nisi tincidunt sapien. Sed nisl. Fusce venenatis, libero porta porta fringilla, sapien odio tincidunt sem, id aliquam tellus sapien sit amet quam. <span class="pq">Vivamus justo mi, aliquam vitae, eleifend et, lobortis quis, eros.</span> Ut felis arcu, mollis ut, interdum molestie, vehicula a, sapien. Sed nisi nunc, bibendum vel, ... </p> ... </div> Computer Science Dept. </body> Fall 2015: October 26 CS 174: Web Programming © R. Mak 30 Automatic Looping with each(), cont’d .text { pullquote.css font-family: sans-serif; width: 600px; margin-top:2em; margin-left: auto; margin-right: auto; min-height: 600px; } Computer Science Dept. Fall 2015: October 26 .pullquote { float: right; clear: right; width: 200px; padding: 10px; font-size: 20px; background-color: #DDD; border-radius: 10px; margin: 20px 0 10px 10px; font-style: italic; CS 174: Web Programming © R. Mak } 31 Automatic Looping with each(), cont’d $(init); pullquote.js function init() { $('span.pq').each(pullQuotes); } function pullQuotes() { var quote = $(this).clone(); quote.removeClass('pq'); quote.addClass('pullquote'); $(this).before(quote); } What is the result? Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak Demo 32 jQuery Object Effects Method Operation show() Make the object visible. hide() Make the object invisible. toggle() Toggle visible/invisible. fadeIn() Fade the object in. fadeOut() Fade the object out. fadeToggle() Toggle fade in/fade out. slideDown() Slide the object into view from top to bottom. slideUp() Slide the object out of view from bottom to top. slideToggle() Toggle slide down/slide up. Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 33 jQuery Object Effects, cont’d <body> <h1>Object Effects</h1> effects.html <div id="buttons"> <h2 id="show">Show</h2> <h2 id="hide">Hide</h2> <h2 id="toggle">Toggle</h2> <h2 id="slideDown">Slide Down</h2> <h2 id="slideUp">Slide Up</h2> <h2 id="fadeIn">Fade In</h2> <h2 id="fadeOut">Fade Out</h2> <h2 id="wrap">Wrap</h2> <h2 id="unwrap">Unwrap</h2> </div> <p id="content"> <img src="images/Bristol.png" width="400" id="image"/> </p> </body> Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 34 jQuery Object Effects, cont’d #buttons { float: left; } effects.css #content { float: right; } h2 { width: 10em; border: 3px outset black; background-color: lightgray; text-align: center; font-family: sans-serif; border-radius: 5px; box-shadow: 5px 5px 5px gray; } Computer Science Dept. Fall 2015: October 26 .wrapped { border: 3px solid red; padding: 2px; CS 174: Web Programming } © R. Mak 35 jQuery Object Effects, cont’d $(init); effects.js var showing = false; var wrapped = false; function init() { $("#content").hide(); $("#show").click(showContent); $("#hide").click(hideContent); $("#toggle").click(toggleContent); $("#slideDown").click(slideDown); $("#slideUp").click(slideUp); $("#fadeIn").click(fadeIn); $("#fadeOut").click(fadeOut); $("#wrap").click(wrapImage); $("#unwrap").click(unwrapImage); } Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 36 jQuery Object Effects, cont’d function showContent() effects.js { $("#content").show(); showing = true; } function hideContent() { $("#content").hide(); showing = false; } function toggleContent() { $("#content").toggle(); showing = !showing; } Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 37 jQuery Object Effects, cont’d effects.js function slideDown() { $("#content").slideDown("medium"); showing = true; } function slideUp() { $("#content").slideUp(500); showing = false; } Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 38 jQuery Object Effects, cont’d effects.js function fadeIn() { $("#content").fadeIn(1000, meow); showing = true; } function fadeOut() { $("#content").fadeOut("fast"); showing = false; } function meow() { alert("MEOW!"); } Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 39 jQuery Object Effects, cont’d effects.js function wrapImage() { if (showing) { $("#image").wrap("<div class='wrapped'></div>"); wrapped = true; } } function unwrapImage() { if (showing && wrapped) { var image = $("#image").clone(); $(".wrapped").remove(); $("#content").append(image); wrapped = false; } } Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak Demo 40 jQuery Object Animation Use the css() method to change an object’s position. Use chaining: $("#content").css("left", "10px").css("top", "120px"); Or use a JSON object: $("#content").css( {"left": "10px", "top": "120px"} ); Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 41 jQuery Object Animation, cont’d The jQuery animate() method changes any DOM characteristics (such as position) over time. Example: var end = {"left": "500px", "top": "300px"}; ... $("#content").animate(end, 2000); Change the left and top attribute values to 500px and 300px, respectively, over a span of 2 seconds. Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 42 jQuery Object Animation, cont’d The animation can occur in two modes: swing: The animation starts slowly, speeds up, and then ends slowly (like a child on a swing). This is the default mode. linear: The animation occurs at a constant speed. $("#content").animate(end, 2000, "linear"); Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 43 jQuery Object Animation, cont’d <form action = ""> <fieldset> <button type = "button" Home </button> <button type = "button" Swing glide </button> <button type = "button" Linear glide </button> <button type = "button" &lt;-</button> <button type = "button" --> </button> </fieldset> </form> animate.html id = "home"> id = "swing"> id = "linear"> id = "left"> id = "right"> <p id="content"> <img src="images/Bristol.png" width="200" id="image"/> </p> Computer Science Dept. Fall 2015: October 26 CS 174: Web Programming © R. Mak 44 jQuery Object Animation, cont’d animate.js $(init); var start = {"left": "10px", "top": "120px"}; var end = {"left": "500px", "top": "300px"}; function init() { $("#home").click(home); $("#swing").click(swingGlide); $("#linear").click(linearGlide); $("#left").click(left); $("#right").click(right); } Computer Science Dept. Fall 2015: October 26 function home() { $("#content").css(start); CS 174: Web Programming } © R. Mak 45 jQuery Object Animation, cont’d function swingGlide() { home(); $("#content").animate(end, 2000); } animate.js function linearGlide() { home(); $("#content").animate(end, 2000, "linear"); } function left() { $("#content").animate({"left": "-=10px"}, 100); } function right() { $("#content").animate({"left": "+=10px"}, 100); Computer Science Dept. CS 174: Web Programming } Fall 2015: October 26 © R. Mak Demo 46