680 likes | 998 Views
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;
E N D
DOM & Jquery Nov. 09, 2012
Jquery • JavaScript Library • DOM (Document Object Model) HTML/XML/etc. • Ajax (Asynchronous JavaScript and XML)
JavascriptDataType • Dynamic Types using variable var x = 1; var y = “something”; var z = “some ‘thing’”; var a = 6e-5; var b = true; false;
Javascript Array var s = new Array(); s[0] = “a”; var s = new Array(“a”, ”b”, ”c”); var s = [“a”, ”b”, ”c”];
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”
Javascript Function • function myfunction() { var a = 0; return a; }
Javascript Location JavaScript in HEAD section JavaScript in BODY section JavaScript in External File
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>
JavaScript in BODY section • </head> • <body> <script type="text/javascript"> //JavaScript written in BODY Sectiondocument.write("JavaScript placed in BODY Section") </script> </body>
JavaScript in External File <head> <script src="../example.js"></script> </head>
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
Get and Change HTML Element • var x=document.getElementById("main");var y=x.getElementsByTagName("p"); • document.getElementById("p1").innerHTML="New text!";
Change CSS • document.getElementById("p2").style.color="blue";
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>
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'; }
Example – Show/Hide with jQuery $().ready(function(){ $("a").click(function(){ $("#more").toggle("slow"); return false; }); });
$ 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(…);
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.
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.
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
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
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
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
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]”)
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.
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
Document • $(document).ready(function(){}) • $().ready(function(){}) (this is not recommended) • $(function(){}))
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
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()
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
JQuery Events • bind(eventname, function) method • ‘click’ • ‘change’ • ‘resize’ • $(“a[@href]”).bind(‘click’,function(){ $(this).addClass(‘red’);});
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’
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.
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); });
jQuery AJAX Functions • $.ajax, $.ajaxSetup • async • beforeSend • complete • contentType • data • dataType • error • global • ifModified • processData • success • timeout • type • url
jQuery AJAX Functions • $.ajax({ type: "POST", url: "some.php", data: { name: "John", location: "Boston" }}).done(function( msg ) { alert( "Data Saved: " + msg );});
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 );});
jQuery AJAX Functions • $(selector).ajaxStart() • ajaxComplete • ajaxError • ajaxSend • ajaxStart • ajaxStop • ajaxSuccess
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'); });
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");});
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']);
Jquery.Event • var event = jQuery.Event("logged");event.user = "foo";event.pass = "bar";$("body").trigger(event); • $("body").trigger({type:"logged",user:"foo",pass:"bar"});
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); });
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>
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
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/