1 / 45

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

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

  7. 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 href attribute containing ‘ntpcug’

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

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

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

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

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

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

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

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

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

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

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

  19. 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=‘cities’] option:selected”).val()

  20. More on Selectors

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

  22. Getting a Specific Dom Element Returns the 2ndDOM element of the selection *starts at 0 • $(“div”).get(1) or$(“div”)[1]

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

  24. each(fn) traverses every selected element calling fn() this – is the current DOM element • var sum = 0;$(“div.number”).each( function(){ sum += (+this.innerHTML); });

  25. each(fn) also passes an indexer • $(“table tr”).each( function(i){ if (i% 2) $(this).addClass(“odd”); }); $(this) – convert DOM to jQueryi - index of the current element

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

  27. Check for expression • $(“table td”).each(function() { if ($(this).is(“:first-child”)) { $(this).addClass(“firstCol”); }});

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

  29. Advanced Chaining • $(“<li><span></span></li>”) // li .find(“span”) // span .html(“About Us”) // span .addBack() // span, li .addClass(“menu”) // span,li .end() // span .end() // li .appendTo(“ul.main-menu”); .addBack( [selector ] ) : Add the previous set of elements on the stack to the current set, optionally filtered by a selector.

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

  31. HTML Manipulation

  32. Getting and Setting Inner Content • $(“p”).html(“<div>Hello $!</div>”); • $(selector).method(content); • // set content div.a to the content of div.b • $(“div.a”).text($(“div.b”).html()); • .text if the content you want to insert is just text, and • .html if the content you want to insert is 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 • // add to selector • $(‘#target’).before (‘<p>Inserted before #target</p>’); • $(‘#target’).after (‘<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. Replacing Elements While Keeping the Content • $(“h3”).each(function(){ $(this).replaceWith(“<div>” + $(this).html() + ”</div>”);});

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

  39. 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”)

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

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

  42. 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”)) { //… }

  43. 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”});

  44. 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)

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

More Related