Introduction to j Query Giuseppe Attardi Universit di
- Slides: 56
Introduction to j. Query Giuseppe Attardi Università di Pisa Some slides from: Bread. Fish
Java. Script l A script language interpreted by browser l OOP (prototype based, not class based) l Dynamic typing l Run-time evaluation
Java. Script l Cannot access host computer (except cookie) l Same origin policy l Non-persistence l Cannot access history object l Cannot write the value of file upload field
Java. Script Libraries l j. Query l Mootools l Prototype l YUI
Introduction to j. Query l Developed in 2006 by John Resig at Rochester Institute of Technology l j. Query is a lightweight Java. Script library that emphasizes interaction between Java. Script and HTML l j. Query is free, open source software Dual-licensed under the MIT License and the GNU General Public License l Helps web developers to create simple pieces of interaction without being forced to write long, complex, book-length pieces of code
Introduction to j. Query l Why do I want it § Rich Internet Applications (RIA) § Dynamic HTML (DHTML) l How do I get it § www. jquery. com l How can I learn it § § § § § j. Query in Action by Bibeault & Katz, Manning j. Query Visual Quickstart Guide by Holzner, Peachpit www. jquery. com docs. jquery. com www. visualjquery. com www. Jqueryfordesigners. com www. gscottolson. com/weblog/ - cheat sheet www. javascripttoolbox. com/jquery http: //www. w 3 schools. com/jquery_examples. asp
Summary Introduction, installation, “Howdy World”, Ready function, DOM, Selecting and Formatting web page elements l Events and Animations l j. Query Plugin libraries l AJAX l
Introduction to j. Query l Installation § just download the jquery-2. x. x. js file and put it in your website folder l Using j. Query § Visual Web Developer Express Edition § Expression Web
What j. Query Does l “Unobtrusive” Java. Script § separation of behavior from structure l CSS § separation of style from structure Allows adding Java. Script to your web pages l Advantages over just Java. Script l § Much easier to use § Eliminates cross-browser problems
5 Things j. Query Provides l l l Select DOM (Document Object Model) elements on a page – one element or a group of them Set properties of DOM elements, in groups (“Find something, do something with it”) Creates, deletes, shows, hides DOM elements Defines event behavior on a page (click, mouse movement, dynamic styles, animations, dynamic content) AJAX calls
The DOM l l l Document Object Model j. Query is “DOM scripting” Heirarchal structure of a web page You can add and subtract DOM elements on the fly You can change the properties and contents of DOM elements on the fly
The DOM “a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Aspects of the DOM (such as its "Elements") may be addressed and manipulated within the syntax of the programming language in use. ” Wikipedia
The j. Query Function l l l l j. Query() = $() $(function) The “Ready” handler $(‘selector’) Element selector expression $(element) Specify element(s) directly $(‘HTML’) HTML creation $. function() Execute a j. Query function $. fn. myfunc(){} Create j. Query function
The Ready Function Set up a basic HTML page and add j. Query l Create a “ready” function l Call a function l 5 ways to specify the ready function l § § § jquery(document). ready(function(){…}; ); jquery(). ready(function(){…}; ) jquery(dofunc); $(dofunc);
Selecting Elements - Creating a “wrapped set” l l $(selector) selector: § § § § § $(‘#id’) id of element $(‘p’) tag name $(‘. class’) CSS class $(‘p. class’) <p> elements having the CSS class $(‘p: first’) $(‘p: last’) $(‘p: odd’) $(‘p: even’) $(‘p: eq(2)’) gets the 2 nd <p> element (1 based) $(‘p’)[1] gets the 2 nd <p> element (0 based) $(‘p: nth-child(3)) gets the 3 rd <p> element of its parent. $(‘p: nth-child(odd)) gets the odd <p> element of its parent. $(‘p: nth-child(5 n+1)’) gets the 1 st element after every 5 th one $(‘p a’) <a> elements, descended from a <p> $(‘p>a’) <a> elements, direct child of a <p> $(‘p+a’) <a> elements, directly following a <p> $(‘p, a’) <p> and <a> elements $(‘li: has(ul)’) <li> elements that have at least one <ul> descendent $(‘: not(p)’) all elements but <p> elements $(‘p: hidden’) only <p> elements that are hidden $(‘p: empty’) <p> elements that have no child elements
Selectors Live l https: //www. tutorialspoint. com/jqueryselectors. htm
Selecting Elements, cont. $(‘img’[alt]) $(‘a’[href^=http: //]) $(‘a’[href$=. pdf]) $(‘a’[href*=ntpcug]) <img> elements having an alt attribute <a> elements with an href attribute starting with ‘http: //’ <a> elements with an href attribute ending with ‘. pdf’ <a> elements with an href attribute containing ‘ntpcug’
Useful j. Query Functions. each() iterate over the set. size() number of elements in set. end() reverts to the previous set. get(n) get just the nth element (0 based). eq(n) get just the nth element (0 based) also. lt(n) &. gt(n). slice(n, m) gets only nth to (m-1)th elements. not(‘p’) don’t include ‘p’ elements in set. add(‘p’) add <p> elements to set. remove() removes all the elements from the page DOM. empty() removes the contents of all the elements. filter(fn/sel) selects elements where the func returns true or sel. find(selector) selects elements meeting the selector criteria. parent() returns the parent of each element in set. children() returns all the children of each element in set. next() gets next element of each element in set. prev() gets previous element of each element in set. siblings() gets all the siblings of the current element https: //www. tutorialspoint. com/jquery-utilities. htm
Formatting Elements l . css(property, value) l https: //www. tutorialspoint. com/jquerycss. htm l . html() l https: //www. tutorialspoint. com/jquerydom. htm . val() (form elements) l. text() l. add. Class(‘class’) l. remove. Class(‘class’) l
Add Page Elements l l $(‘#target’). before(‘<p>Inserted before #target</p>’); $(‘#target’). after(‘<p>This is added after #target</p>’); $(‘#target’). append(‘<p>Goes inside #target, at end</p>’); $(‘#target’). wrap(‘<div></div>’);
Adding Events Mouseover events – bind, hover, toggle l Button click events l Keystrokes l
Event Background l DOM Level 2 Event Model § Multiple event handlers, or listeners, can be established on an element § These handlers cannot be relied upon to run an any particular order § When triggered, the event propagates from the top down (capture phase) or bottom up (bubble phase) § IE doesn’t support the “capture phase”
Basic Syntax of Event Binding $(‘img’). bind(‘click’, function(event){alert(‘Howdy’; }); l $(‘img’). bind(‘click’, imgclick(event)); l § Allows unbinding the function $(‘img’). unbind(‘click’, imgclick()); l $(‘img’). unbind(‘click’); l $(‘img’). one(‘click’, imgclick(event)); l § Only works once $(‘img’). click(imgclick); l $(‘img’). toggle(click 1, click 2); l $(‘img’). hover(mouseover, mouseout); l l https: //www. tutorialspoint. com/jqueryevents. htm
Element Properties – “this” l l l l l this. id this. tag. Name this. attr this. src this. classname this. title this. alt this. value (for form elements)
‘Event’ properties l l l l event. target ref to element triggering event Event. target. id id of element triggering event. current. Target event. type of event triggered event. data second parm in the bind() func Various mouse coordinate properties Various keystroke related properties
Event Methods. stop. Propagation(). prevent. Default(). trigger(event. Type) no bubbling no <a> link, no <form> submit does not actually trigger the event, but calls the appropriate function specified as the one tied to the event. Type. click(), blur(), focus(), select(), submit() With no parameter, invokes the event handlers, like trigger does, for all the elements in the wrapped set
Shortcut Event Binding l l l . click(func). submit(func). dblclick(func). mouseover(func). mouseout(func). select(func)
Useful Event Functions. hide() display: none. show() display: true. toggle(func 1, func 2) first click calls func 1, next click executes func 2. hover(over, out) mouseover, mouseout https: //www. tutorialspoint. com/jquery-effects. htm
Examples of Events l l l Toggle. html Hover 1. html Events. html Table. Stripes. html Collapsible. list. html Custom. effects. html Opacity of picture Hover using. bind Expanding a DIV Table highlighting Expandable List Animations
Other examples l l Table stripes Animations Expanding Lists ASP. NET Gridview
Extending j. Query Creating a j. Query function l https: //www. tutorialspoint. com/jqueryplugins. htm l
j. Query Plugins (UI Library) Tab example l Slider example l l https: //www. tutorialspoint. com/jqueryslidebar. htm l Carousel example l https: //www. tutorialspoint. com/jqueryslideshow. htm l Photomatic example l http: //www. isquery. com/devel/jqueryinaction/secon d/chapter 7/photomatic. html
Widgets l Accordion § Enable to collapse the content, that is broken into logical sections. l Autocomplete § Enable to provides the suggestions while you type into the field. l Datepicker § It is to open an interactive calendar in a small overlay. l Progressbar § It shows the progress information. l Tabs § It is used to swap between content that is broken into logical sections.
j. Query Core l j. Query(selector, [ context ]): Accepts a string containing a CSS selector which is then used to match a set of elements and returns a j. Query object. § § l j. Query(element) j. Query(element. Array) j. Query(j. Query object) j. Query() can be written as $()
j. Query Events l . ready(handler) : execute handler when the DOM is fully loaded. js function printhello(){ $(“#hello”). html(“Hello, j. Query!”); } $(document). ready(printhello()); v Same as window. onload? ? ? js $(document). ready(function(){ $(“#hello”). html(“Hello, j. Query!”); });
j. Query Events l l l l l . bind(). blur(). change(). click(). focus(). hover(). select(). toggle(). trigger(). submit() l l l . mousedown(). mouseenter(). mouseleave(). keypress(). keyup()
j. Query Events $(document). keyup(function(event) { switch(event. which) { case 32: alert(“ 32 pressed”); break; } }); v event. prevent. Default() v event. stop. Propagation()
j. Query Selectors l follows CSS 1~3 Selectors http: //www. w 3. org/TR/css 3 -selectors : animated l : has() l : gt() l
j. Query Attributes l l l l . add. Class(). remove. Class(). has. Class(). toggle. Class(). attr(). removeattr(). val(). html()
j. Query Each l . each() : Iterate over a j. Query object, executing a function for each matched element. html <ul> <li>garbage</li> <li>food</li> <li>abroad</li> </ul> js $(document). ready(function(){ $('li'). each(function(index) { alert(index + ': ' + $(this). text()); });
j. Query Traversing l l l l . add(). children(). contents(). filter(). find(). next(). not(). prev()
j. Query Manipulations l l l l . append(). append. To(). clone(). detach(). insert. After(). insert. Before(). remove()
j. Query CSS l l l l . css(). height(). width(). position(). offset(). scroll. Top(). scroll. Left()
j. Query Effect l . animate() html <button id="left">left</button> <button id="right">right</button> <div class="block"></div> js $(document). ready(function(){ $(". block"). css({ 'position': 'absolute', 'background. Color': "#abc", 'left': '100 px', 'width': '90 px', 'height': '90 px', 'margin': '5 px' }); $("#left"). click(function(){ $(". block"). animate({left: "-=50 px"}, "slow"); }); $("#right"). click(function(){ $(". block"). animate({left: "+=50 px"}, "slow"); });
j. Query Effect l l . fade. In(). hide(). show(). toggle()
AJAX l l Asynchronous Java. Script And XML The basic AJAX function – XMLHttp. Request Initiating a request Getting the response
j. Query AJAX l j. Query. get(url, [data], [callback(data, text. Status, XMLHttp. Request)], [data. Type]) Returns: XMLHttp. Request l j. Query. post() l j. Query. get. JSON() l j. Query. load() l j. Query. get. Script()
AJAX Example Does ‘username’ exist? yes/no username j. Query HTML print server check…
j. Query AJAX html <div id="user_check"> <input id="username" type="text"></input> <input id="username_submit" type="button" value="submit"></input> <p id="check_result"></p> </div> js $(document). ready(function(){ $("#username_submit"). click(function(){ $. get('jqtest. cgi', {"username" : $("#username"). val()}, function(data){ $('#check_result'). html(data); }); }); CGI #! /usr/bin/python import cgi import os form = cgi. Field. Storage() print "Content-Type: text/htmlnn“ name = form. getvalue('username', '1') if os. path. exists("/home/“ + name + "/"): print "exists" else: print "not exists"
JSONP Avoids limitation of same origin requests l Trick: <script> elements are not constrained l Use <script> to retrieve Java. Script code that operates on dynamically generated JSONformatted data from other origins l
JSONP Mechanism Suppose a request to http: //server/User? Id=1234 returns {"Name": “Pippo", "Id" : 1234, "Rank": 7} Add parameter to request <script type="text/javascript" src="http: //server/User? User. Id=1234&jsonp=p arse. Response"> </script> So that the answer becomes: parse. Response({"Name": "Foo", "Id" : 1234, "Rank": 7})
JSONP Example j. Query. get. JSON("http: //search. twitter. com/search. json? call back=? ", { q: "Arsenal“ }, function(tweets) { // Handle response here console. info("Twitter returned: ", tweets); });
CORS l l l Cross-Origin Resource Sharing W 3 C specification Allows cross-domain communication from the browser Uses XMLHttp. Request Supported by some browsers
CORS Example // Create the XHR object. function create. CORSRequest(method, url) { var xhr = new XMLHttp. Request(); if ("with. Credentials" in xhr) { // XHR for Chrome/Safari/Firefox. xhr. open(method, url, true); } else if (typeof XDomain. Request != "undefined") { // XDomain. Request for IE. xhr = new XDomain. Request(); xhr. open(method, url); } else // CORS not supported. xhr = null; return xhr; }
var xhr = create. CORSRequest('GET', url); if (!xhr) { throw new Error('CORS not supported'); } xhr. onload = function() { var response. Text = xhr. response. Text; console. log(response. Text); // process the response. }; xhr. onerror = function() { console. log('There was an error!'); };
Embedding a Map <iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http: //maps. google. com/maps? f=q& sou rce=s_q& hl=en& geocode=& q=lar go+pontecorvo+3, +pisa, +italy& aq=& sll =37. 0625, 95. 677068& sspn=33. 901528, 36. 474609&a mp; vpsrc=0& ie=UTF 8& hq=& hnea r=Via+Pellegrino+Pontecorvo, +3, +56121+Pisa, + Toscana, +Italy& t=m& z=14& ll=43. 682725, 10. 428894& output=embed"> </iframe> https: //www. tutorialspoint. com/jquery/src/whatsnear by/index. htm
- Gerardo attardi
- Universit
- Erasmus university rotterdam economics
- Universit of london
- Scuio ip nanterre
- Universit sherbrooke
- Iterative query
- Query tree and query graph
- Query tree and query graph
- Introduction to structured query language (sql)
- Introduction to structured query language (sql)
- Free car giuseppe calvanese
- Giuseppe garibaldi biography
- Giuseppe della ricca
- Mario montessori giuseppe montesano
- Giuseppe d'agostino unifi
- Istituto san giuseppe lugo
- Istituto borgo san giuseppe
- Prigiotti giuseppe
- Nabucco trama
- Patrizia amadio
- Giuseppe valitutti
- Ungaretti opere
- Fratelli ungaretti: parafrasi
- Biografia giuseppe ungaretti
- Analisi della poesia fratelli di ungaretti
- Lezioni di fisica giuseppe ruffo
- Giuseppe grande matematico del 700
- Arcimboldo képek
- Giuseppe fortunino francesco verdi
- Giuseppe fiorelli pompeii excavation
- Renato cacciapuoti
- Giuseppe baldacci
- Terza media giuseppe verdi mappa concettuale
- Giuseppe tizza
- Www.giuseppechiumeo
- Giuseppe azzarone
- Giuseppe fortuna
- Giuseppe aliperti md
- Ungaretti biografia breve
- Giuseppe flavio contro apione pdf
- Arcimboldo winter
- Giuseppe acciaro
- Intranet arnas garibaldi
- Giuseppe rossi unical
- Giuseppe di guglielmo
- Giuseppe perpiglia
- Giuseppe angelica
- Laura bassi giuseppe veratti
- Istituto san giuseppe lugo
- Giuseppe brinchi
- Antonella chiricosta
- Giuseppe baldini
- Giuseppe ungaretti fratelli e sorelle
- Giuseppe carenini
- Giuseppe verdi composities
- Giuseppe garibaldi nickname