The Script.aculo.us JavaScript Library Part I - Custom Training ...

19 downloads 35 Views 3MB Size Report
Unzip and grab .js files out of “src” folder. – Usually put in subdirectory of scripts since there are many files. • This tutorial corresponds to Scriptaculous 1.8.1.
© 2009 Marty Hall

The Script.aculo.us JavaScript Library Part I: j p Features Ajax-Specific Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/ajax.html p j Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

© 2009 Marty Hall

For live Ajax & GWT training, see training courses att http://courses.coreservlets.com/. htt // l t / Taught by the author of Core Servlets and JSP, More Servlets and JSP, JSP and this tutorial. tutorial Available at public venues, or customized versions can be held on-site at your organization. • Courses C d developed l d and d ttaught ht b by M Marty t H Hallll – Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF 1.x & 2.0, Ajax, GWT, custom mix of topics – Ajax courses can concentrate on EE one library (jQuery, Prototype/Scriptaculous, Ext-JS, Dojo) or survey several Customized Java Training: http://courses.coreservlets.com/

• Courses developed and taught by coreservlets.com experts (edited by Marty)

Servlets, –JSP, JSFHibernate/JPA, 1.x & JSF 2.0, Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Spring, EJB3,Struts Ruby/Rails Contact [email protected] for details Developed and taught by well-known author and developer. At public venues or onsite at your location.

Topics in This Section • Overview of Scriptaculous • Installation and documentation • Autocomplete textfields – Local version – Ajax version

• In-place In place Editor – Free-text values – Values from combo box

5

© 2009 Marty Hall

Introduction Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Overview • Foundation – Built B il on top off Prototype P

• Ajax-specific features – Autocompleting textfields • Textfields with dropdown list of matching choices • Covered in first half of this section

– In-place editors • Clickable text that you can edit and send to server • Covered in second half of this section

• General features – Visual effects (fade in, fade out, highlighting) • Covered in next section

– Drag and drop • Covered in later section 7

Downloading and Installation • Download – http://script.aculo.us/downloads • Unzip and grab .js files out of “src” folder – Usually put in subdirectory of scripts since there are many files

• This tutorial corresponds to Scriptaculous 1.8.1

• Online documentation – http://wiki.script.aculo.us/

• Online forum – http://groups.google.com/group/rubyonrails-spinoffs htt // l / / b il i ff

• Prerequisite – Scriptaculous requires Prototype. Prototype I am using 1.6. 16 8

• So your HTML page needs to load both libraries • See separate lectures on Prototype

© 2009 Marty Hall

Autocompleter.Local Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Autocompleter.Local • Idea

– Specify JavaScript array that has choices for textfield. textfield Dropdown box shown with choices that start with what has been typed so far • http://wiki.script.aculo.us/scriptaculous/show/Autocompletion

• Steps

– Make an instance of Autocompleter.Local • new Autocompleter.Local(textFieldID, divID, array) – Enable it when page loads • window.onload window onload = function() { new Autocompleter.Local(...); Autocompleter Local( ); }; • Prototype gurus might use document.observe("dom:loaded", ...) instead of window.onload – Make an empty div with a designated CSS name •
– Attach style sheet that makes div absolutely positioned, puts border on div, turns off bullets for ul lists, and makes a different background color for li.selected

10

Autocompleter.Local Example: JavaScript var langString = "Java,C,C++,PHP,Visual Basic,..."; var langArray = languageString languageString.split( split(","); ); window.onload = function() { new Autocompleter.Local( Autocompleter Local("langField1", langField1 , "langMenu1", langMenu1 , langArray); }; function googleSearch(id) { var language = getValue(id); window.location.href = "http://www.google.com/search?q=" + language; }

11

function getValue(id) { return(escape(document.getElementById(id).value)); }

Autocompleter.Local Example: HTML Header p // g/ / Scriptaculous and Autocomplete / / sc pt s src= c / / If you know you will only use certain parts of scriptaculous library, library you can save download time by loading only some of it. To load all of it, just omit the "load=" part. I.e., . Autocomplete is in controls, but relies on effects internally. 12

Autocompleter.Local Example: Main HTML ... Autocomplete.Local Programming language:
...

13

Autocompleter.Local Example: CSS .autocomplete { position: absolute; color: #333333; background-color: #ffffff; border: 1px solid #666666; font-family: Arial, sans-serif; overflow: hidden; } .autocomplete ul { padding: 0; a g : 0; margin: list-style: none; overflow: auto; }

14

Autocompleter.Local Example: CSS (Continued) .autocomplete li { display: block; white-space: nowrap; cursor: pointer; margin: 0px; padding-left: 5px; padding-right: 5px; border: 0px solid #ffffff; } .autocomplete li.selected { background-color: bac g ou d co o : #ccee #cceeff; ; border-top: 1px solid #99bbcc; border-bottom: 1px solid #99bbcc; }

15

Autocompleter.Local Example: Results

16

© 2009 Marty Hall

Ajax.Autocompleter Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Ajax.Autocompleter • Idea

– Specify URL that computes list of choices. choices Dropdown box shown with choices that start with what has been typed so far • http://wiki.script.aculo.us/scriptaculous/show/Autocompletion

• Steps: summary

– Same steps as with Autocompleter.Local except • Specify url instead of array (url should return
    list) • Use class Ajax.Autocompleter instead of Autocompleter.Local

    • Steps

    – Make an instance of Ajax.Autocompleter j p ( divID, url)) • new Ajax.Autocompleter(textFieldID, – Enable it when page loads • window.onload = function() { new Ajax.Autocompleter(...); }; – Make an empty div with a designated CSS name •
    – Attach same style sheet as with Autocompleter.Local

    18

    Ajax.Autocompleter Example: JavaScript var langString = "Java,C,C++,PHP,Visual Basic,..."; var langArray = languageString languageString.split( split(","); ); window.onload = function() { new Autocompleter Autocompleter.Local("langField1", Local("langField1" "langMenu1" "langMenu1", langArray); new Ajax.Autocompleter("langField2", "langMenu2", "l "languages"); ") };

    This is the relative URL. URL By default it will be passed POST data of name-of-langField2=value-of-langField2

    19

    Ajax.Autocompleter Example: HTML Ajax Autocomplete Ajax.Autocomplete Programming language: g


    By default, default name of field is parameter name

    20

    Ajax.Autocompleter Example: Servlet public class LanguageCompleter extends HttpServlet { private static final String languageString = "Java,C,C++,..."; private static final String[] languageArray = languageString.split(","); public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); The name (not id!) of textfield was "langPrefix". String languagePrefix = request.getParameter("langPrefix"); List g languages g g = findLanguages(languagePrefix); g g g g request.setAttribute("languages", languages); String outputPage = "/WEB-INF/results/language-list.jsp"; RequestDispatcher q p dispatcher p = request.getRequestDispatcher(outputPage); dispatcher.include(request, response); } 21

    Ajax.Autocompleter Example: Servlet (Continued) public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } private List findLanguages(String languagePrefix) { languagePrefix = languagePrefix.toUpperCase(); List languages = new ArrayList(); for(String language: languageArray) { if(language.toUpperCase().startsWith(languagePrefix)) { languages.add(language); } } return(languages); } } 22

    Ajax.Autocompleter Example: JSP
    • ${language}


    23

    Return value of URL should be
    • ...
    • ...
    • ...
    Style sheet on client will suppress the bullets.

    Ajax.Autocompleter Example: web xml web.xml LanguageCompleter LanguageCompleter coreservlets.LanguageCompleter LanguageCompleter LanguageCompleter /languages

    24

    Ajax.Autocompleter Example: Results

    25

    © 2009 Marty Hall

    Autocompleter Options Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

    Autocompleter Options • Idea – Autocompleter.Local and Ajax.Autocompleter accept an options array as the fourth argument • new Ajax.Autocompleter(fieldID, Ajax Autocompleter(fieldID divID divID, url url, { opt1: ..., opt2: ..., ... });

    • Legal properties for both classes – autoSelect (default: false) • Should value automatically be inserted into textfield if there is only y one matching g choice?

    – frequency (default: 0.4) • Interval in seconds between attempts to autocomplete

    – minChars i Ch (default: (d f lt 1) • The number of characters before autocompletion kicks in 27

    Autocompleter Options (Continued) • Options for Autocompleter.Local – choices h i (default (d f l 10) • Maximum number of entries to display

    – partialSearch (default true) • Should match be made at beginning of any word? False means to match beginning of first word only.

    – partialChars (default 2) • Number of characters before partial search kicks in. When number of chars is greater or equal to minChars but less than partialChars, you get a non-partial search (first word).

    – fullSearch f llSearch (default (defa lt false) • Should match be anywhere? False means to match only at the beginning of each candidate.

    – selector (default: function that searches array) • Function that does real work of doing match and building ul list. 28

    Autocompleter Options (Continued) • Options for Ajax.Autocompleter – indicator i di (default: (d f l none)) • Id of element that should be shown while waiting for server result, then hidden again

    – paramName N (d (default: f lt name off textfield) t tfi ld) • parameter name sent to server (parameter value is textfield value, of course)

    – parameters t (default: (d f lt empty) t ) • Extra string sent to server (fixed parameters)

    – tokens (default: empty) • Array of delimeters: each entry outside delimeters is autocompleted separately

    – afterUpdateElement (default: none) • Function to run when user makes choice. Lets you respond automatically to selections. 29

    Autocompleter Options Example: JavaScript var langString = "Java,C,C++,PHP,Visual Basic,..."; var langArray = languageString languageString.split( split(","); ); window.onload = function() { new Autocompleter.Local( Autocompleter Local("langField1", langField1 , "langMenu1", langMenu1 , langArray); new Ajax.Autocompleter("langField2", "langMenu2", "languages"); languages ); new Ajax.Autocompleter("langField3", "langMenu3", "languages-slow", { indicator: "indicatorRegion", g , paramName: "langPrefix"}); };

    30

    Autocompleter Options Example: HTML Ajax Autocomplete with Indicator Ajax.Autocomplete g y g Loading...
    Programming language:


    31

    Autocompleter Options Example: Java public class SlowLanguageCompleter extends LanguageCompleter { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Thread.sleep(2000); } catch(InterruptedException ie) {} super.doGet(request, response); } }

    32

    Autocompleter Options Example: web xml web.xml SlowLanguageCompleter SlowLanguageCompleter coreservlets.SlowLanguageCompleter SlowLanguageCompleter SlowLanguageCompleter /languages-slow

    33

    Autocompleter Options Example: Results

    34

    © 2009 Marty Hall

    In-Place Editors Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

    In-Place Editors • Idea – Text that you can click on, on edit, edit and send to server – Text is highlighted when mouse over it – Text passed to server as “value” request parameter • Text shown as “Saving Saving...” while waiting for server

    – Value returned from server is new textual value • Might not be exactly what user entered

    • Basics – new Ajax.InPlaceEditor("id-of-element", "url"); – Click on text to get editable textfield

    – new Ajax.InPlaceCollectionEditor ("id-of-element", "url" { collection: ["Option1", ... "OptionN"]}); – Click on text to get select box of options

    – Documentation • http://wiki.script.aculo.us/scriptaculous/show/InPlaceEditing 36

    InPlaceEditor Example • JavaScript window.onload = function() { new Ajax.InPlaceEditor("element-to-edit", "show-value.jsp"); };

    • HTML

    Here is Some Text



    • JSP You sent "${param.value}" 37

    InPlaceEditor Example: Results

    38

    InPlaceCollectionEditor Example • JavaScript window.onload i d l d = f function() ti () { new Ajax.InPlaceEditor("element-to-edit", "show-value.jsp"); new Ajax.InPlaceCollectionEditor ("flyer-status", "show-value.jsp", { collection: ["Silver", "Gold", "Platinum", "Wood", "Hay", "Stubble"]}); };

    • HTML

    Frequent Flyer Status: Silver



    • JSP

    You sent "${param.value}" 39

    InPlaceCollectionEditor Example: Results

    40

    In-Place Editor Options: Basic Options • okButton (default: true) – Should you use "ok" button? Often set to false.

    • okText (default: "ok") – Text T off confirmation fi i button b

    • cancelLink (default: true) – Should you have "cancel" cancel link?

    • savingText (default "Saving...") – Text to show while waiting for server response

    • clickToEditText (default: "Click to edit") – Text to show in tooltip p when mouse hovers over text

    • paramName (default: "value") 41

    – Request parameter name

    In-Place Editor Options: Ajax Request Options Ajax.Request • Idea – You can use ajaxOptions to specify an options object that gets passed to the underlying Ajax.Request object • new Ajax Ajax.InPlaceEditor( InPlaceEditor("id" id , "url" url , { ajaxOptions: { blah }); • For {blah} above, you can use all of the same options as discussed in the earlier section on the Prototype Ajax libraries

    • Most important usage: extra parameters – You are editing a first name, but what customer id does that first name go with? • var params = { param1: $("div-id").innerHTML, param2: $F("textfield-id")}; p ( )} • var options = { parameters: params } • new Ajax.InPlaceEditor("id", "url", { ajaxOptions: options }); 42

    In-Place Editor Options: Collection Options • collection – Array of choices

    • loadCollectionURL – URL that h returns JavaScript J S i array off choices h i

    • loadCollectionText – Text to show while waiting for server to send array of choices

    43

    In-Place Editor Options: Styling Options • highlightColor (default: pale yellow) – Color to show when mouse is over and when result first comes back from server

    • highlightendColor (default: white) – Color to show temporarily when hightlighting finishes

    • hoverClassName, formClassName, loadingClassName, savingClassName • (defaults: none, "inplaceeditor-form", "inplaceeditorl di " "i loading", "inplaceeditor-saving") l dit i ")

    – CSS name of elements at different stages

    • formID – id of form that is created when you click 44

    In-Place Editor Options: Callback Options • onEnterHover – Defaults to setting background color

    • onLeaveHover – Defaults D f l to fading f di out background b k d color l

    • onEnterEditMode • onFailure – Defaults to showing error message

    • onComplete – This is often used when you are doing server-side validation of values. You can check a custom header from the server and show error message if needed.

    • onLeaveEditMode 45

    Advanced Example: JavaScript window.onload = function() { var options = { okButton: false, clickToEditText: "Click to update your info" }; new Ajax.InPlaceEditor("firstName", "update-firstName", options); new Ajax Ajax.InPlaceEditor( InPlaceEditor("lastName" lastName , "update-lastName", options); new Ajax.InPlaceEditor("email", j ( , "update-email", options); new Ajax.InPlaceEditor("flyerNum", " d t fl "update-flyerNum", N " options); }; 46

    Advanced Example: Servlet for Initial Page public class ShowTraveler extends HttpServlet { public void doGet(HttpServletRequest p p q request, q HttpServletResponse response) throws ServletException, IOException { response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", response.setHeader( Pragma , "no-cache"); no cache ); HttpSession session = request.getSession(); Traveler traveler = (Traveler)session.getAttribute("traveler"); if (traveler == null) { traveler = new Traveler(); session.setAttribute("traveler", traveler); } String outputPage = "/WEB-INF/results/show-traveler.jsp"; RequestDispatcher dispatcher = request.getRequestDispatcher(outputPage); dispatcher.include(request, response); } } 47

    Advanced Example: JSP for Initial Page ...
      18px >
    • First name: ${traveler.firstName}
    • Last name: ${traveler.lastName}
    • Email address: ${traveler.email}
    • Frequent Flyer Number: ${traveler.flyerNum}
    ...

    48

    Advanced Example: Helper Class for Initial Page public class Traveler implements Serializable { private String p g firstName = "Joe"; ; private String lastName = "Traveler"; private String email = "[email protected]"; private String flyerNum = "a1234"; public Traveler(String firstName, String lastName, String email, String flyerNum) { setFirstName(firstName); setLastName(lastName); setEmail(email); setFlyerNum(flyerNum); } public Traveler () {} // Standard getters and setters } 49

    Advanced Example: Initial Page: Results

    50

    Advanced Example: Servlets for Updating • Purpose – These are the servlets specified earlier in the Ajax.InPlaceEditor constructors • update-firstName update firstName, update-lastName update lastName, update-email update email, update-flyerNum

    • Behavior – They look up the session, get a Traveler object from the session, then store first name, last name, etc. in that object – They also have a delay to simulate use on a loaded network • This lets you see "Saving..." message while waiting for server update 51

    Advanced Example: Servlets for Updating (Parent) public abstract class UpdateTraveler extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { p ( , "no-cache"); ) response.setHeader("Cache-Control", response.setHeader("Pragma", "no-cache"); HttpSession session = request.getSession(); Traveler traveler = (Traveler)session.getAttribute("traveler"); if (traveler == null) { traveler = new Traveler(); session.setAttribute("traveler", i tAtt ib t ("t l " t traveler); l ) }

    52

    Advanced Example: Servlets for Updating (Parent, (Parent Cont.) Cont ) String newVal = request.getParameter("value"); if ((newVal != ! null) && !(newVal.trim().equals( !(newVal trim() equals(""))) ))) { doUpdate(traveler, newVal); } p g () PrintWriter out = response.getWriter(); try { Thread.sleep(2000); } catch(InterruptedException ie) {} out.print(getResult(traveler)); } public abstract void doUpdate(Traveler traveler, St i String newVal); V l) public abstract String getResult(Traveler traveler); }

    53

    Advanced Example: Servlets for Updating (First Name) public class UpdateFirstName extends UpdateTraveler { public void doUpdate(Traveler traveler, String newVal) { traveler.setFirstName(newVal); } public String getResult(Traveler traveler) { return(traveler.getFirstName()); } }

    54

    Advanced Example: Results

    55

    © 2009 Marty Hall

    Wrap-up Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

    Recommended Books • Prototype and script.aculo.us: You Never K Knew J JavaScript S i C Could ld Do D Thi This!! – By Christophe Porteneuve

    • Prototype and Scriptaculous in Action – By Dave Crane, Bear Bebeault, Tom Locke

    57

    Summary window.onload = function() { new Autocompleter.Local( Autocompleter Local("fieldID1" fieldID1 , "divID1", arrayOfChoices); new Ajax.Autocompleter( Ajax Autocompleter("fieldID2" fieldID2 , "divID2", "urlThatReturnsList"); new Ajax.Autocompleter("fieldID3", Ajax Autocompleter("fieldID3" "divID3", "urlThatReturnsList" { indicator indicator: "ind "ind-id", id" paramName: "p-name", more-options...}); }; 58

    Summary (Continued) window.onload = function() { new Ajax.InPlaceEditor("id-to-edit-1", "url-to-send-value"); new Ajax.InPlaceCollectionEditor ("id-to-edit-2", "url-to-send-value", { collection: ["Option1",...,"OptionN"]}); };

    59

    © 2009 Marty Hall

    Questions? Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.