1 / 50

DOM & Jquery

DOM & Jquery. Nov. 09, 2012. Jquery. JavaScript Library DOM (Document Object Model) HTML/XML/etc. Ajax (Asynchronous JavaScript and XML). Javascript DataType. Dynamic Types using variable var x = 1; var y = “something”; var z = “some ‘thing’”; var a = 6e-5;

yanka
Télécharger la présentation

DOM & Jquery

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.

E N D

Presentation Transcript


  1. DOM & Jquery Nov. 09, 2012

  2. Jquery • JavaScript Library • DOM (Document Object Model) HTML/XML/etc. • Ajax (Asynchronous JavaScript and XML)

  3. JavascriptDataType • Dynamic Types using variable var x = 1; var y = “something”; var z = “some ‘thing’”; var a = 6e-5; var b = true; false;

  4. Javascript Array var s = new Array(); s[0] = “a”; var s = new Array(“a”, ”b”, ”c”); var s = [“a”, ”b”, ”c”];

  5. Javascript Object • var protein = { id: 1234, length: 200, name: somename } • var Name = protein.name; • var Name = protein[“name”]; • You can new String, Number, Boolean, Array, Object • You can set empty object to “null”

  6. Javascript Function • function myfunction() { var a = 0; return a; }

  7. Javascript Location JavaScript in HEAD section JavaScript in BODY section JavaScript in External File

  8. JavaScript in HEAD section <!DOCTYPE html><html><head><script>function myFunction(){alert("Hello World!");}</script></head><body><input type="submit" onclick="myFunction();">Click it</input> <a href="javascript:myFunction();">Click here to run.</a></body></html>

  9. JavaScript in BODY section •   </head> •    <body>     <script type="text/javascript">         //JavaScript written in BODY Sectiondocument.write("JavaScript placed in BODY Section")     </script>    </body>

  10. JavaScript in External File <head> <script src="../example.js"></script> </head>

  11. Javascript and DOM • DOM scripting: javascript • change all the HTML elements in the page • change all the HTML attributes in the page • change all the CSS styles in the page • react to all the events in the page

  12. Get and Change HTML Element • var x=document.getElementById("main");var y=x.getElementsByTagName("p"); • document.getElementById("p1").innerHTML="New text!";

  13. Change CSS • document.getElementById("p2").style.color="blue";

  14. React events • <!DOCTYPE html><html><head><script>function changetext(id){id.innerHTML="Ooops!";}</script></head><body><h1 onclick="changetext(this)">Click on this text!</h1></body></html>

  15. Example – Show/Hide the old way <a href="#" onclick="toggle_visibility('foo');">Click here to toggle visibility of #foo</a> function toggle_visibility(id) { var e = document.getElementById(id); if(e.style.display == 'block') e.style.display = 'none'; else e.style.display = 'block'; }

  16. Example – Show/Hide with jQuery $().ready(function(){ $("a").click(function(){ $("#more").toggle("slow"); return false; }); });

  17. $ selector func (…) jQuery Object, can be used instead of jQuery Selector syntax, many different selectors allowed Chainable, most functions return a jQuery object Function parameters Jquery • $.func(…); • $(selector).func1(…).func2(…).funcN(…);

  18. The jQuery/$ Object • Represented by both $ and jQuery • To use jQuery only, use jQuery.noConflict(), for other frameworks that use $ • By default, represents the jQuery object. When combined with a selector, can represent multiple DOM Elements, see next slide. • Used with all jQuery functions.

  19. jQuery Selectors • $( expr, context ) This function accepts a string containing a CSS or basic XPath selector which is then used to match a set of elements. Default context is document. Used most often for DOM transversal. • Selectors will return a jQuery object, which can contain one or more elements, or contain no elements at all. • $( html ) Create DOM elements on-the-fly from the provided String of raw HTML. • $( elems ) Wrap jQuery functionality around single or multiple DOM Elements. • $( fn ) A shorthand for $(document).ready(), allowing you to bind a function to be executed when the DOM document has finished loading.

  20. JQuery Selectors • CSS p element name #id identifier .class classname p.class element with class p a anchor as any descendant of p p > a anchor direct child of p

  21. JQuery Selectors • XPath /html/body//div paths a[@href] anchor with an href attr div[ol] div with an ol inside //a[@ref='nofollow'] any anchor with a specific value for the ref attribute

  22. JQuery Filters p:first first paragraph li:last last list item a:nth(3) fourth link a:eq(3) fourth link p:even or p:odd every other paragraph a:gt(3) or a:lt(4) every link after the 4th orup to the fourth a:contains(‘click’) links that contain the word click

  23. Xpath and DOM • Xpath • http://www.w3schools.com/xpath/xpath_syntax.asp • DOM transversal • http://www.w3.org/TR/DOM-Level-2-Traversal-Range/traversal.html

  24. jQuery Selector Examples • $( html ) • $(‘<p><a href=“index.html”>Click here!</a></p>’) • $ ( elems ) • $(document), $(window), $(this) • $(document.getElementsByTagName(“p”)) • $ ( fn ) • $(function() { alert(“Hello, World!”) }); • $ ( expr, context ) • $(“p”), $(“form”), $(“input”) • $(“p#content”), $(“#content”), $(“.brandnew”), $(“p span.brandnew:first-child, #content”), • $("input:radio", document.forms[0]); • $(“p/span”), $(“p/span[@class=brandnew]”), $(p/span:first), $(p:first/span:even) • $(“input:checkbox[@checked]”), $(“div:visible p[a]”)

  25. Chained Functions • Attached to the jQuery object or chained off of a selector statement. • Most functions return the jQuery object they were originally passed, so you can perform many actions in a single line. • The same function can perform an entirely different action based on the number and type of parameters.

  26. DOM core objects • Document -- Element (maximum of one), ProcessingInstruction, Comment, DocumentType • DocumentFragment -- Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference • DocumentType -- no children • EntityReference -- Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference • Element -- Element, Text, Comment, ProcessingInstruction, CDATASection, EntityReference • Attr -- Text, EntityReference • ProcessingInstruction -- no children • Comment -- no children • Text -- no children • CDATASection -- no children • Entity -- Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference • Notation -- no children • http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html

  27. Document • $(document).ready(function(){}) • $().ready(function(){}) (this is not recommended) • $(function(){}))

  28. Jquery DOM • Selecting part of document is fundamental operation • A JQuery object is a wrapper for a selected group of DOM nodes • $() function is a factory method that creates JQuery objects • $(“dt”) is a JQuery object containing all the “dt” elements in the document

  29. Jquery DOM • addClass() method changes the DOM nodes by adding a ‘class’ attribute • The ‘class’ attribute is a special CSS construct that provides a visual architecture independent of the element structures • $(“dt”).addClass(“emphasize”) will change all occurrences of <dt> to <dt class=“emphasize”> • See also .removeClass()

  30. Jquery DOM • .attr({‘name’, ‘value’}) • sets a new attribute (or many) • $(‘<i>hello</i>’) • Creates a new element • $(‘<i>hello</i>’).insertAfter(‘div.chapter p’); • Creates element and inserts it into the document • .html() or .text() or .empty() will replace matched elements with newly created elements

  31. JQuery Events • bind(eventname, function) method • ‘click’ • ‘change’ • ‘resize’ • $(“a[@href]”).bind(‘click’,function(){ $(this).addClass(‘red’);});

  32. JQueryEffects • .css(‘property’, ‘value’) • .css({‘prop1’:‘value1’, ‘prop2’:’value2’…}) • E.g. .css(‘color’, ‘red’) • .hide(speed) or .show(speed) • Where speed is ‘slow’, ‘normal’ or ‘fast’

  33. jQuery AJAX Functions • jQuery has a series of functions which provide a common interface for AJAX, no matter what browser you are using. • Most of the upper level AJAX functions have a common layout: • $.func(url[,params][,callback]), [ ] optional • url: string representing server target • params: names and values to send to server • callback: function executed on successful communication.

  34. jQuery AJAX Functions • $.func(url[,params][,callback]) • $.get • $.getJSON • $.getIfModified • $.getScript • $.post $.get(“controller/actionname", { name: "John", time: "2pm" }, function(data){ alert("Data Loaded: " + data); }); $.post(“controller/actionname", { name: "John", time: "2pm" }, function(data){ alert("Data Loaded: " + data); });

  35. jQuery AJAX Functions • $.ajax, $.ajaxSetup • async • beforeSend • complete • contentType • data • dataType • error • global • ifModified • processData • success • timeout • type • url

  36. jQuery AJAX Functions • $.ajax({  type: "POST",  url: "some.php",  data: { name: "John", location: "Boston" }}).done(function( msg ) {  alert( "Data Saved: " + msg );});

  37. jQuery AJAX Functions • varmenuId = $("ul.nav").first().attr("id");var request = $.ajax({  url: "script.php",  type: "POST",  data: {id : menuId},dataType: "html"});request.done(function(msg) {  $("#log").html( msg );});request.fail(function(jqXHR, textStatus) {  alert( "Request failed: " + textStatus );});

  38. jQuery AJAX Functions • $(selector).ajaxStart() • ajaxComplete • ajaxError • ajaxSend • ajaxStart • ajaxStop • ajaxSuccess

  39. jQuery AJAX Functions • <div class="trigger">Trigger</div> • <div class="result"></div> • <div class="log"></div> • $('.log').ajaxStart(function() { $(this).text('Triggered ajaxStart handler.'); }); • $('.trigger').click(function() { $('.result').load('test.php'); });

  40. jQuery AJAX Functions • $(selector).load() inject HTML • load • loadIfModified • .load( url [, data] [, complete(responseText, textStatus, XMLHttpRequest)] ) • $("#feeds").load("feeds.html"); • $('#result').load('ajax/test.html #container'); • $("#objectID").load("test.php", { 'choices[]': ["Jon", "Susan"] } ); • $("#feeds").load("feeds.php", {limit: 25}, function(){alert("The last 25 entries in the feed have been loaded");});

  41. jQueryCustomized Event • $('#foo').bind('click', function() { alert($(this).text()); }); • $('#foo').trigger('click'); • $('#foo').bind('custom', function(event, param1, param2) { alert(param1 + "\n" + param2); }); • $('#foo').trigger('custom', ['Custom', 'Event']);

  42. Jquery.Event • var event = jQuery.Event("logged");event.user = "foo";event.pass = "bar";$("body").trigger(event); • $("body").trigger({type:"logged",user:"foo",pass:"bar"});

  43. Jquery.Event • var message = 'Spoon!'; • $('#foo').bind('click', {msg: message}, function(event) { alert(event.data.msg); }); message = 'Not in the face!'; $('#bar').bind('click', {msg: message}, function(event) { alert(event.data.msg); });

  44. Example • <!DOCTYPE html><html><head>  <style>p { color:red; }span { color:blue; }</style>  <script src="http://code.jquery.com/jquery-latest.js"></script></head><body>  <p>Has an attached custom event.</p><button>Trigger custom event</button><span style="display:none;"></span><script>$("p").bind("myCustomEvent", function(e, myName, myValue){$(this).text(myName + ", hi there!");$("span").stop().css("opacity", 1).text("myName = " + myName).fadeIn(30).fadeOut(1000);});$("button").click(function () {$("p").trigger("myCustomEvent", [ "John" ]);});</script></body></html>

  45. Summary • JavaScript animation • Hundreds of plugins for pre-built user interfaces, advanced animations, form validation, etc • Expandable functionality using custom plugins • Cross browser support and detection • AJAX functions • CSS functions • DOM manipulation • DOM transversal • Attribute manipulation • Event detection and handling

  46. Links & References • Official website • http://www.jquery.com • http://docs.jquery.com/Tutorials • http://docs.jquery.com/Discussion • http://docs.jquery.com/Main_Page • http://http://api.jquery.com/ • http://docs.jquery.com/Sites_Using_jQuery • Learning • http://www.visualjquery.com • http://jquery.bassistance.de/api-browser/ • http://www.learningjquery.com/

More Related