Presentation is loading. Please wait.

Presentation is loading. Please wait.

DOM & Jquery Nov. 09, 2012. Jquery JavaScript Library DOM (Document Object Model) HTML/XML/etc. Ajax (Asynchronous JavaScript and XML)

Similar presentations


Presentation on theme: "DOM & Jquery Nov. 09, 2012. Jquery JavaScript Library DOM (Document Object Model) HTML/XML/etc. Ajax (Asynchronous JavaScript and XML)"— 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 Javascript DataType 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 function myFunction() { alert("Hello World!"); } Click it Click here to run.

9 JavaScript in BODY section //JavaScript written in BODY Section document.write("JavaScript placed in BODY Section")

10 JavaScript in External File

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 function changetext(id) { id.innerHTML="Ooops!"; } Click on this text!

15 Example – Show/Hide the old way Click here to toggle visibility of #foo 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 Jquery $.func(…); $(selector).func1(…).func2(…).funcN(…); jQuery Object, can be used instead of jQuery Selector syntax, many different selectors allowed Chainable, most functions return a jQuery object Function parameters $ selector func (…)

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 $( 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. $( 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.

20 JQuery Selectors CSS pelement name #ididentifier.classclassname p.classelement with class p aanchor as any descendant of p p > aanchor direct child of p

21 JQuery Selectors XPath /html/body//divpaths 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:firstfirst paragraph li:lastlast list item a:nth(3)fourth link a:eq(3)fourth link p:even or p:oddevery other paragraph a:gt(3) or a:lt(4)every link after the 4th or up to the fourth a:contains(‘click’)links that contain the word click

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

24 jQuery Selector Examples $( html ) – $(‘ Click here! ’) $ ( 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

27

28

29 DOM core objects Document -- Element (maximum of one), ProcessingInstruction, Comment, DocumentType DocumentElementProcessingInstructionComment DocumentType DocumentFragment -- Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference DocumentFragmentElementProcessingInstructionCommentText CDATASectionEntityReference DocumentType -- no children DocumentType EntityReference -- Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference EntityReferenceElementProcessingInstructionCommentTextCDATASection EntityReference Element -- Element, Text, Comment, ProcessingInstruction, CDATASection, EntityReference Element TextCommentProcessingInstructionCDATASection EntityReference Attr -- Text, EntityReference AttrTextEntityReference ProcessingInstruction -- no children ProcessingInstruction Comment -- no children Comment Text -- no children Text CDATASection -- no children CDATASection Entity -- Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference EntityElementProcessingInstructionCommentTextCDATASection EntityReference Notation -- no children Notation http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html

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

31 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

32 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 to See also.removeClass()

33 Jquery DOM.attr({‘name’, ‘value’}) – sets a new attribute (or many) $(‘ hello ’) – Creates a new element $(‘ hello ’).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

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

35 JQuery Effects.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’

36 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.

37 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); });

38

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

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

41 jQuery AJAX Functions var menuId = $("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 ); });

42 jQuery AJAX Functions $(selector).ajaxStart() – ajaxComplete – ajaxError – ajaxSend – ajaxStart – ajaxStop – ajaxSuccess

43 jQuery AJAX Functions Trigger $('.log').ajaxStart(function() { $(this).text('Triggered ajaxStart handler.'); }); $('.trigger').click(function() { $('.result').load('test.php'); });

44 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"); });

45 jQuery Customized 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']);

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

47 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); });

48 Example p { color:red; } span { color:blue; } Has an attached custom event. Trigger custom event $("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" ]); });

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

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


Download ppt "DOM & Jquery Nov. 09, 2012. Jquery JavaScript Library DOM (Document Object Model) HTML/XML/etc. Ajax (Asynchronous JavaScript and XML)"

Similar presentations


Ads by Google