450 likes | 586 Views
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
E N D
JQuery Document Ready & Selectors JQueryGetting Started
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
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.
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.
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
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’
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
All Selector Selectors return a pseudo-array of jQuery elements • $(“*”) // find everything
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>
More Precise Selectors • $(“div.main”) // tag and class • $(“table#data”) // tag and id
Combination of Selectors • // find by id + by class • $(“#content, .menu”) • // multiple combination • $(“h1, h2, h3, div.content”)
Hierarchy Selectors • $(“table td”) // descendants • $(“tr > td”) // children • $(“label + input”) // next • $(“#content ~ div”) // siblings
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
Visibility Filters • $(“div:visible”) // if visible • $(“div:hidden”) // if not
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
Forms Selectors • $(“input:checkbox”) // checkboxes • $(“input:radio”) // radio buttons • $(“:button”) // buttons • $(“:text”) // text inputs
Forms Filters • $(“input:checked”) // checked • $(“input:selected”) // selected • $(“input:enabled”) // enabled • $(“input:disabled”) // disabled
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()
A Selector returns a pseudo array of jQuery objects Returns number of selected elements. It is the best way to check selector. • $(“div”).length
Getting a Specific Dom Element Returns the 2ndDOM element of the selection *starts at 0 • $(“div”).get(1) or$(“div”)[1]
Getting a Specific jQuery Element Returns the 2ndjQuery element of the selection • $(“div”).eq(2)
each(fn) traverses every selected element calling fn() this – is the current DOM element • var sum = 0;$(“div.number”).each( function(){ sum += (+this.innerHTML); });
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
Traversing the DOM • .next(expr) // next sibling • .prev(expr) // previous sibling • .siblings(expr) // siblings • .children(expr) // children • .parent(expr) // parent
Check for expression • $(“table td”).each(function() { if ($(this).is(“:first-child”)) { $(this).addClass(“firstCol”); }});
Find in selected • // select paragraph and then find // elements with class ‘header’ inside $(“p”).find(“.header”).show(); // equivalent to:$(“.header”, $(“p”)).show();
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.
Get Part of Selected Result • $(“div”) .slice(2, 5) .not(“.green”) .addClass(“middle”);
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.
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”]);
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”);
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>’);
Replacing Elements • // select > replace$(“h1”).replaceWith(“<div>Hello</div>”); • // create > replace selection$(“<div>Hello</div>”).replaceAll(“h1”);
Replacing Elements While Keeping the Content • $(“h3”).each(function(){ $(this).replaceWith(“<div>” + $(this).html() + ”</div>”);});
Deleting Elements • // remove all children$(“#mainContent”).empty(); • // remove selection$(“span.names”).remove(); • // change position$(“p”).remove(“:not(.red)”) .appendTo(“#main”);
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”)
Setting Multiple Attributes • $(“img”).attr({ “src” : “/images/smile.jpg”, “alt” : “Smile”, “width” : 10, “height” : 10});
Formatting Elements • .css(property, value) • .html() • .text() • .val() (form elements) • .addClass(‘class’) • .removeClass(‘class’)
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”)) { //… }
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”});
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)
Positioning • // from the document$(“div”).offset().top; • // from the parent element$(“div”).position().left; • // scrolling position$(window).scrollTop();