1 / 44

JQuery Getting Started

JQuery Document Ready & Selectors. JQuery Getting Started. The jQuery Function $() - Document Ready. jQuery () = $() $(function) The “Ready” handler $(‘selector’) Element selector expression $(element) Specify element(s) directly

anthea
Download Presentation

JQuery Getting Started

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. JQuery Document Ready & Selectors JQueryGetting Started

  2. The jQuery Function$() - Document Ready • jQuery() = $() • $(function) The “Ready” handler • $(‘selector’) Element selector expression • $(element) Specify element(s) directly • $(‘HTML’) HTML creation Create DOM elements on-the-fly from the provided String of raw HTML • $.function() Execute a jQuery function • $.fn.myfunc(){} Create jQuery function

  3. jQuery 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.

  4. The Ready Function • Set up a basic HTML page and add jQuery • Create a “ready” function • 5 ways to specify the ready function • jquery(document).ready(function(){…};); • jquery().ready(function(){…};) • jquery(function(){…};) • jquery(dofunc); • $(func); - A shorthand for $(document).ready(), allowing you to bind a function to be executed when the DOM document has finished loading.

  5. jQuery Selectors

  6. $( html ) Create DOM elements on-the-fly from the provided String of raw HTML. $( elems ) Wrap jQuery functionality around single or multiple DOM Elements. $( func) 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. jQuery Selectors

  7. jQuery Selector Examples • $( html ) • $(‘<p><a href=“index.html”>Click here!</a></p>’) • $ ( elems ) • $(document), $(window), $(this) • $(document.getElementsByTagName(“p”)) • $ ( func) • $(function() { alert(“Hello, World!”) }); • $ ( expr, context ) • $(“p”), $(“form”), $(“input”) • $(“p#content”), $(“#content”), $(“.brandnew”), $(“p span.brandnew:first-child, #content”) • $(“p/span”), $(“p/span[@class=brandnew]”), $(p/span:first), $(p:first/span:even) • $(“input:checkbox[@checked]”), $(“div:visible p[a]”) • var xml = ‘<d><it w=“h1”><nm>One</nm></it><it w=“h2”><nm>Two</nm></it></d>’; $(“d it nm:contains(‘One’)”, xml), $(“it[@w^=h]”,xml)

  8. Selecting Elements • $(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 2nd <p> element (1 based) • $(‘p’)[1] gets the 2nd <p> element (0 based) • $(‘p:nth-child(3)) gets the 3rd <p> element of the parent. n=even, odd too. • $(‘p:nth-child(5n+1)’) gets the 1st element after every 5th 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

  9. Selecting Elements, cont. • $(selector) • selector: • $(‘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 • $(‘img’[alt]) <img> elements having an alt attribute • $(‘a’[href^=http://]) <a> elements with an hrefattribute starting with ‘http://’ • $(‘a’[href$=.pdf]) <a> elements with an href attribute ending with ‘.pdf’ • $(‘a’[href*=ntpcug]) <a> elements with an hrefattriutecontaining ‘ntpcug’

  10. Useful jQuery 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

  11. All Selector Selectors return a pseudo-array of jQuery elements • $(“*”) // find everything

  12. Basic Selectors By Tag: • $(“div”) • // <div>Hello jQuery</div> By ID: • $(“#usr”) • // <span id=“usr”>John</span> By Class: • $(“.menu”) • // <ul class=“menu”>Home</ul>

  13. More Precise Selectors • $(“div.main”) // tag and class • $(“table#data”) // tag and id

  14. Combination of Selectors • // find by id + by class • $(“#content, .menu”) • // multiple combination • $(“h1, h2, h3, div.content”)

  15. Hierarchy Selectors • $(“table td”) // descendants • $(“tr > td”) // children • $(“label + input”) // next • $(“#content ~ div”) // siblings

  16. Selection Index Filters • $(“tr:first”) // first element • $(“tr:last”) // last element • $(“tr:lt(2)”) // index less than • $(“tr:gt(2)”)// index greater than • $(“tr:eq(2)”) // index equals

  17. Visibility Filters • $(“div:visible”) // if visible • $(“div:hidden”) // if not

  18. Attribute Filters • $(“div[id]”) // has attribute • $(“div[dir=‘rtl’]”) // equals to • $(“div[id^=‘main’]”) // starts with • $(“div[id$=‘name’]”) // ends with • $(“a[href*=‘msdn’]”) // contains

  19. Forms Selectors • $(“input:checkbox”) // checkboxes • $(“input:radio”) // radio buttons • $(“:button”) // buttons • $(“:text”) // text inputs

  20. Forms Filters • $(“input:checked”) // checked • $(“input:selected”) // selected • $(“input:enabled”) // enabled • $(“input:disabled”) // disabled

  21. Find Drop Down Selected Item • <select name=“cities”> • <option value=“1”>Tel-Aviv</option> • <option value=“2” selected=“selected”>Yavne</option> • <option value=“3”>Raanana</option> • </select> • $(“select[name=‘ddl’] option:selected”).val()

  22. More on Selectors

  23. A Selector returns a pseudo array of jQuery objects Returns number of selected elements. It is the best way to check selector. • $(“div”).length

  24. Getting a Specific Dom Element Returns the 2ndDOM element of the selection • $(“div”).get(2) or$(“div”)[2]

  25. Getting a Specific jQuery Element Returns the 2ndjQuery element of the selection • $(“div”).eq(2)

  26. Traversing the DOM • .next(expr) // next sibling • .prev(expr) // previous sibling • .siblings(expr) // siblings • .children(expr) // children • .parent(expr) // parent

  27. Find in selected • // select paragraph and then find // elements with class ‘header’ inside $(“p”).find(“.header”).show(); // equivalent to:$(“.header”, $(“p”)).show();

  28. Get Part of Selected Result • $(“div”) .slice(2, 5) .not(“.green”) .addClass(“middle”);

  29. Exercise 1

  30. Finding Things • Using FindingThings.html, find the following things: • The friends list • All list items in every list on the page • The list items inside the friends list • Everything with the class fl-centered • The first form element on the page • The last item in the friends list • The label for the username text field • Give each thing a background colour

  31. HTML Manipulation

  32. Getting and Setting Inner Content • $(“p”).html(“<div>Hello $!</div>”); • // set content div.a to the content of div.b • $(“div.a”).text($(“div.b”).html()); The get mode is the empty method call; passing in no value to the method performs a get call. When passing in a value, this performs a set operation, overriding the innercontent.

  33. Getting and Setting Values • // get the value of the checked checkbox$(“input:checkbox:checked”).val(); • // set the value of the textbox$(“:text[name=‘txt’]”).val(“Hello”); • // select or check lists or checkboxes$(“#lst”).val([“NY”,”IL”,”NS”]);

  34. Inserting New Elements • // select > append to the end$(“h1”).append(“<li>Hello $!</li>”); • // select > append to the beginning$(“ul”).prepend(“<li>Hello $!</li>”); • // create > append/prepend to selector$(“<li/>”).html(“9”).appendTo(“ul”); • $(“<li/>”).html(“1”).prependTo(“ul”);

  35. Add Page Elements • $(‘#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>’);

  36. Replacing Elements • // select > replace$(“h1”).replaceWith(“<div>Hello</div>”); • // create > replace selection$(“<div>Hello</div>”).replaceAll(“h1”);

  37. Deleting Elements • // remove all children$(“#mainContent”).empty(); • // remove selection$(“span.names”).remove(); • // change position$(“p”).remove(“:not(.red)”) .appendTo(“#main”);

  38. Handling Attributes • $(“a”).attr(“href”,”home.htm”);// <a href=“home.htm”>…</a> • // set the same as the first one$(“button:gt(0)”).attr(“disabled”, $(“button:eq(0)”).attr(“disabled)); • // remove attribute - enable$(“button”).removeAttr(“disabled”)

  39. Setting Multiple Attributes • $(“img”).attr({ “src” : “/images/smile.jpg”, “alt” : “Smile”, “width” : 10, “height” : 10});

  40. Handling CSS Classes • // add and remove class$(“p”).removeClass(“blue”).addClass(“red”); • // add if absent, remove otherwise$(“div”).toggleClass(“main”); • // test for class existance if ($(“div”).hasClass(“main”)) { //… }

  41. CSS Manipulations • // get style$(“div”).css(“background-color”); • // set style $(“div”).css(“float”, “left”); • // set multiple style properties$(“div”).css({“color”:”blue”, “padding”: “1em” “margin-right”: “0”,marginLeft: “10px”});

  42. Formatting Elements • .css(property, value) • .html() • .val() (form elements) • .text() • .addClass(‘class’) • .removeClass(‘class’)

  43. Dimensions • // get window heightvarwinHeight = $(window).height(); • // set element height$(“#main”).height(winHeight); • //.width() – element • //.innerWidth() – .width() + padding • //.outerWidth() – .innerWidth() + border • //.outerWidth(true) – including margin The default unit is Pixel (px)

  44. Positioning • // from the document$(“div”).offset().top; • // from the parent element$(“div”).position().left; • // scrolling position$(window).scrollTop();

More Related