1 / 39

Web Design:

Web Design:. Fall 2010 Mondays 7-9pm 200 Sutardja -Dai Hall. Basic to Advanced Techniques. jQuery and AJAX. Lecture Code: 788458. Today’s Agenda. Review JavaScript from last lecture Forms: Post, Get jQuery APIs Ajax: jQuery Ajax API Effects: jQuery Effects API

Download Presentation

Web Design:

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.


Presentation Transcript

  1. Web Design: Fall 2010 Mondays 7-9pm 200 Sutardja-Dai Hall Basic to Advanced Techniques jQuery and AJAX Lecture Code: 788458

  2. Today’s Agenda • Review JavaScript from last lecture • Forms: Post, Get • jQuery APIs • Ajax: jQuery Ajax API • Effects: jQuery Effects API • Events: jQuery Events API • Manipulation: jQuery Maniplation API • Traversing: jQuery Traversing API • Ajax

  3. Announcements • MP #2 Part 2 deadline extended Friday (10/29) • YouTube video tutorial up • MP #3 tWDDer due Monday (11/1) • Finish today’s lab and turn in for MP #3 • Office hours Wednesday night? 7PM? • CSS Positioning • MP #2 & MP #3 help • Final Project Reminder

  4. Feedback #1 • Lecture • Summarize key points form prev. lecture • More social interaction (group work) • More live examples • Mini Projects • More screencasted assignments • Help Outside of Class • Office Hours • Workshops • Additional Resources • List of Resources • Photoshop Tutorial • Supplemental Worksheets • Syntax Cheatsheets

  5. Feedback #1 Cont. • Lecturers • Alex • Will provide more examples • Shouldn’t miss any more class (missed a few lectures due to business trips) • Amber • Will talk slower • Jon • Will be more enthusiastic and engaging • Opportunities • ? Last semester had a few recruiters probably because of summer • Ask Alex, Amber, and Jon if you want to get more info on freelance work or working on a project

  6. Changing After Load • WDD fishes and clouds move • Google changes results on the fly

  7. JavaScript or PHP? • JavaScript allows us to do one of the two criteria for dynamic pages. Which one? • “Change After Load” or “Different Depending on Request”? A: Change After Load

  8. What is JavaScript? Client Side Server Side Web Server Serve Website Send HTML and CSS files Send images • Web Browser • HTTP Request (visit website) • Interpret and render received files • Send JavaScript code • Execute JavaScript • PHP and MySQL Runs in your browser – on the client side Q: Why can’t JavaScript serve a different page depending on request? A: Executed on the client side after page load

  9. What does JavaScript do? • “Plays with the blocks” • Modifies HTML and CSS • “Moves blocks around” • Change position of HTML objects via CSS • “Buys new and throws away old blocks” • Can create and delete HTML objects and CSS rules • “Stacks blocks” • Can change nested structure of HTML code • Essentially change HTML and CSS in anyway it wants • Anything you could have created or styled ahead of time in HTML and CSS, JavaScript can create or style after the page has loaded

  10. How do we spot JavaScript? • If a HTML and CSS page is anything but static, there’s JavaScript there. • Only exception is :hover, :active, :visited pseudo classes for links

  11. How does JavaScript do it? • Browser represents web page as a DOM tree • DOM = Document Object Model html <html> <head> <title></title> </head> <body> <div> <h1></h1> <p></p> </div> </body> </html> head body title div h1 p

  12. DOM Tree • Each HTML element is a node on the tree (an object) • Its container (whatever it is nested in) is its parent • What is nested within it is its children • Each object has attributes (HTML and CSS) • <img src=“http://awi.com/i.gif” /> • img { border: 1px solid black; } src http://awi.com/i.gif img style border 1px solid black;

  13. Basic Coding Flow in jQuery • Select element that you want to modify using $() syntax • $(‘CSS Select String’) • Chain function calls after select tag • $(‘p’).css(‘color’, ‘red’).click(function(){$(this).remove(); });

  14. Selecting HTML Elements • jQuery allows us to use CSS selectors in conjunction with $ to select objects in HTML • $(‘#myElement’) gives us the element with id=“myElement” • $(‘img’) gives us an array of all images on page • Selecting elements with $ also gives the element some additional JavaScript functionality which include…

  15. Changing Element Attributes • Method: .attr • Get attributes with: • $(‘#myImg’).attr(‘src’); • Set attributes with: • $(‘#myImg’).attr(‘src’, ‘someImage.jpg’); • $(‘#myImg’).attr({ src : ‘someImage.jpg’, alt : ‘some image’ });

  16. Changing CSS Properties • Method: .css • Get properties with: • $(‘h1’).css(‘color’); • Set properties with: • $(‘h1’).css(‘color’, ‘red’); • $(‘h1’).css({ color: ‘red’, ‘font-weight’ : ‘normal’ });

  17. Adding CSS Class • Method: .addClass • $(‘#myDiv’).addClass(‘header’); • Method: .removeClass • $(‘#myDiv’).removeClass(‘header’);

  18. Event handling • Mouse click • $(“#blah").click(function() { alert("Hello world!"); }); • Hover • $('#blah').mouseover(function() { alert(“Hello world!”); }); • Keyup/down/press, onfocus/blur, etc. • For more, check out the Jquery API: http://api.jquery.com/category/events/

  19. JavaScript Functions • Doesn’t do anything until called • Controlled execution • Repetitive (code reusability) • function doSomething(var1, var2, …){ //body }

  20. Math Functions (Remember from algebra?) • f(x) = x2 + x + 3 • f(1) = 12 + 1 + 3 = 5 • f(x, y) = x3 + y2 + 1 • f(2, 1) = 23 + 12 + 1 = 10 • Basic idea: Functions are machines that take can take an input, do some stuff, then spit a result out. These functions can also have variable number of inputs/arguments.

  21. JavaScript Functions (cont’d) • Anonymous functions • Assign it to a variable to call later • var eatCakeAnon = function(){ alert("So delicious and moist"); }; eatCakeAnon(); • Pass it directly as a function argument (callback) • $('#target').click(function() { alert(‘Something happened!'); });

  22. Stringing along jQuery commands • With jQuery you can string along any other jQuery commands, as long as you’ve selected the element first. • $(“div”).attr(title, “newTitle”) • $(“div”).css(background-color, “newColor”); • $(“div”).attr(title, “newTitle”).css(background-color, “newColor”);

  23. .append() vs .appendTo() • $('<p>Test</p>').appendTo('.inner'); • This first creates an HTML element with inner text and appends to all elements in the existimg HTML DOM with class “inner” • $('.inner').append('<p>Test</p>'); • This looks for all element with class “inner” first, then appends “<p>Test</p>” to each one

  24. Demo jQuery Traversal • .add(selector) • .children(selector) • .first() • .last() • .parent() • .find(selector) • .closest()

  25. Demo jQuery Manipulation • .addClass()—covered this • .removeClass()—covered this • .append(), .prepend() —covered this • .appendTo(), .prependTo() —covered this • .after(), .before() • .remove() • .val()

  26. Demo jQuery Effects • .slideDown() • .slideUp() • .slideToggle() • .hide() • .show() • .animate()

  27. HTML Forms <form name="input" action="html_form_action.php" method="get"> </form> • action: the URL you will be directing the submitting arguments to • name: specifies the name of the form. It’s not strictly necessary, but can be referenced in a script (ie. document.forms[“input"]). • Method: either ‘get’ or ‘post’. More about this next. • Main point: this allows us to pass values to a server (like updating facebook statuses).

  28. GET • A GET request will generate a parameters driven URL • Parameters are passed in the following form: • <URL>?key1=value1&key2=value2&key3=… • ? – lets the browser know anything thereafter are parameters to be passed to the server • Each parameter is formulated by a ‘key=value’ pair. Each ‘key=value’ pair is delaminated (separated) by a ‘&’ character

  29. GET Example • Our Domain: http://twdder.decal.aw-industries.com/ • The URL we want to send parameters to: http://twdder.decal.aw-industries.com/messages/retrieve • Attach parameters like so: • ?key=tWDDer>twitter&created_after=2000-1-1 00:00:00 • key, created_after – these are the ‘keys’ names of parameters we wish to send. • tWDDer>twitter, 2000-1-1 00:00:00 – these are the ‘values’ of their respective ‘keys’

  30. POST • Can’t really be visualized, but we can see the results by looking at the web traffic through FireBug. • <form action="form_action.asp“ method=“post”> • First name: <input type="text" name="FirstName" /> • Last name: <input type="text" name="LastName" /> • <input type="submit" value="Submit" /> • </form>

  31. POST Good: More secure, hides the data away from plain sight Good: Handles long requests well, since it’s not limited by URL length Bad: the server cannot cache these values If you are doing password inputs, use this! Sensitive data should use this. GET Good: Server Caches the parameters, so if you submit with the same parameters more than once, it might not have to do the computation over again. Good: remains in browser history Can be bookmarked, therefore also available for distribution among friends (ie sending google search results) Bad: Values available in plain sight POST vs. GET • There’s a huge discussion around when and how to use it. Resource: The Definitive Guide to GET vs POST

  32. What is AJAX? …We’re not talking about your household cleanser!

  33. Demo: maps.google.com What is AJAX? • Asynchronous JavaScript And XML • Asynchronous—fetches/sends data to the server without a page refresh • JavaScript—you know this already • XML—Extensible Markup Language (Like HTML!). It’s human readable, but don’t worry about it too much. • It’s part of Javascript, so it’s Client-side technology • So what can it do for us? <book> <title>AJAX for dummies</title> <publisher>Berkeley Books</publisher> <author>Some guys you've never heard of</author> </book> Example

  34. 1.a 1.b What’s going on? (just the Ajax view) • Synchronous Actions (Initial load) • You visit http://maps.google.com • Google’s Web Server receives request and serves you the web page. • Asynchronous Actions • Event triggered by zooming (actually .click()). Each magnification “redraws” the map. • Client-side makes Ajax call to retrieve the new map images at the set zoom level. 2.a. 2.b.

  35. Demo: tWDDer Lab How do we do Ajax with jQuery? $.ajax({ url: <URL>, data: { key1:value1, key2:value2, key3=… }, dataType: 'jsonp', success: function(data, textStatus, XMLHttpRequest){ //This is your callback, where you do stuff after a success } error: function (XMLHttpRequest, textStatus, errorThrown){ //fallback in case the request failed. } }); Resource: jQuery .ajax()

  36. Callbacks • Piece of executable code that is passed as an argument to other code • Allows us control timing of function calls • Allows us to execute X only if Y was sucessful. • Just like the jQuery .click() $("p").click(function () { $(this).slideUp(); });

  37. The Future of Ajax • Ajax is everywhere on the web today (google, facebook, twitter). • Limitations • It is a Pull Technology: we have to keep blindly asking the server for data, even if it’s not available yet. Not good if we want a live feed application with twitter updates. • It might be better for the server to send us data when it’s available. There is much less wasteful traffic and overhead. • The next cool thing: HTML 5 WebSockets. • Allows Push Technology: when the data is read, the server contacts us. • For the web enthusiasts…this works by keeping a persistent connection • Q: Is this Client-side? A: Yes, AND also Server-side!

  38. References & Additional Resources • jQuery APIs • Ajax: jQuery Ajax API • Effects: jQuery Effects API • Events: jQuery Events API • Manipulation: jQuery Maniplation API • Traversing: jQuery Traversing API • Websockets • HTML 5 Web Sockets vs. Comet and Ajax • HTML5 Web Sockets: A Quantum Leap in Scalability for the Web

  39. JavaScript Date() – Just a reference… • It is part of plain JavaScript, not jQuery! • To create it, you will need to do • var myDate = new Date(); • Some functions it has • myDate .getTime() - Milliseconds since 1/1/1970 @ 12:00 AM • myDate . getSeconds() - Number of seconds (0-59) • myDate. getMinutes() - Number of minutes (0-59) • myDate . getHours() - Number of hours (0-23) • myDate . getDay() - Day of the week(0-6). 0 = Sunday, ... , • myDate . getDate() - Day of the month (0-31) • myDate . getMonth() - Number of month (0-11) • myDate . getFullYear() - The four digit year (1970-9999) Resources: Javascript Tutorial – Date, JavaScript Date Object

More Related