Valdosta State University



jQueryIntroductionjQuery is a library that is written on top of the JavaScript DOM and makes it much easier to manipulate HTML elements. This allows developers to write simple code to provide an enhanced user experience. Anything you can do in jQuery, you can do in JavaScript, but in many cases it would take much more code. As discussed previously, the DOM is an API to access HTML elements allowing us to use JavaScript to access elements by:id attribute – getElementByIdname attribute – getElementsByNameOr, to crawl through the tree representation of the page using methods such as: nextSibling, firstChild, etc.jQuery provides a way select elements in many different ways: id, class, name, attribute, and many more.This is the way it works: there is a jQuery function that selects HTML element(s) and returns a jQuery object that wraps the element(s). Then, there are over 300 methods for manipulating the elements through the jQuery object. Below, I list a few of these methods. Keep in mind that these methods/functions work on a single element or a collection of them: FunctionDescriptioncssChange CSS dynamicallyaddClassApply a currently defined CSS class. See also: removeClass, toggleClassanimateAnimate anything very simply.appendInsert contents into an element(s). See also: prepend, after, beforepreventDefaultStops any element with a default action from firingdataAttach data to an elementmatchFiltering string valuesfindSearches for elements that meet a criterionchildrenFind all the children elements of an elementhideHides an element(s). See also: showSome methods return jQuery objects which allows function calls to be chained. Other methods return an HTML element(s) and so the jQuery methods do not apply. Finally, some methods just perform an action on the element(s).See the jQuery API for information on the available methods.How does jQuery Work?Use the jQuery function to select the element(s) you are interested in. For example, to select all the <h2> tags:var h2s = jQuery("h2");Then, to change the text that is displayed in all these elements:h2s.text("Header is changed");The jQuery function has an alias, $, thus, we can write the first line above:var h2s = $("h2");Unless there was a need to define a variable, we would usually just chain the operations together:$("h2").text("Header is changed");The basic syntax is: $(selector).action()$ – Used to access jQueryselector – Used to find HTML element(s)action – Action to be performed on the element(s)Examples:$(this).hide()// hides the current element.$("p").hide() // hides all <p> elements.$(".test").hide() // hides all elements with class="test".$("#test").hide() // hides the element with id="test".The major selectors are:TypeDescriptionExampleElementSelects all elements of a particular type$(“p”)IdSelects the element with a specific id$(“#balance”)ClassSelects all elements with a particular CSS class$(“.checkbook”)AttributeSelects all elements with a particular attribute value$( "input[name='first_name']" );Some other selectors:$(“*”)Selects all elements$(this)Selects the current HTML element$("p.intro")Selects all <p> elements with class="intro"$("p:first")Selects the first <p> element$("ul li:first")Selects the first <li> element of the first <ul>$("ul li:first-child")Selects the first <li> element of every <ul>$("[href]")Selects all elements with an href attribute$("a[target='_blank']")Selects all <a> elements with a target attribute value equal to "_blank"$("a[target!='_blank']")Selects all <a> elements with a target attribute value NOT equal to "_blank"$(":button")Selects all <button> elements and <input> elements of type="button"$("tr:even")Selects all even <tr> elements$("tr:odd")Selects all odd <tr> elementsThe Document Ready EventConsider the hideParagraph JavaScript function below that uses jQuery. This function doesn’t actually hide paragraphs. What it does is:Assign the click event to all paragraphsDefine an event handler via an anonymous function which hides a paragraph when it is clicked. function hideParagraph() { $("p").click(function () { $(this).hide(); }); }Almost all jQuery functions are inside the document ready event. This is done so that no jQuery code can run until the page has finished loading. For example, the hideParagraph function would be executed like this: $(document).ready(hideParagraph);The more usual way to write this would be to use an anonymous function to implement the event handler for the ready event. <script> $(document).ready(function () { $("p").click(function () { $(this).hide(); }); // Assign more event handlers }); </script>Technical Note (optional): Notice above that we still pass an anonymous function to the click function. If we were to write this as a named function, we would need to define a parameter and pass it which is a little more involved. We won’t consider passing arguments. The obvious advantage to naming functions is that we can reuse them.The general syntax is:$(document).ready(function(){ // jQuery methods go here...});ExampleExample – Illustrates “hello world” using jQuery. Also shows how to hide and redisplay a button. See jq_1.html on the website.<html><head> <title>JS Simple Example 1</title> <script src="jquery-1.11.2.js"></script><script> $(document).ready(function () { $("#jqButton").click(function () { alert("jQuery Hello World"); }); $("#hide").click(function () { if ($(this).text() === "Hide JS Button") { $("#jsButton").hide(); $(this).text("Show JS Button"); } else if ($(this).text() === "Show JS Button") { $("#jsButton").show(); $(this).text("Hide JS Button"); } }); });</script></head><body> <h2>JQ/JS Simple Example 1</h2> <form id="hello"> <button type="button" id="jsButton" onclick="helloWorld()">Java Script Hello World</button>&nbsp; <button type="button" id="jqButton">jQuery Hello World</button> <p> <button type="button" id="hide">Hide JS Button</button> </p> </form></body></html>Note:In JavaScript, “===” returns true only when the operands are the same type and the contents are the same.Using jQueryYou can use jQuery in one of two ways:Include it from a Content Delivery Network (CDN) by adding this in head section:<script?src=""></script>Download it from: then put it in your folder where you pages are. Then, reference it by adding this in the head section:<script?src="jquery-3.3.1.min.js"></script>ExamplesExample – Illustrates processing form elements. See jq_2.html on website.$(document).ready(function () { $("#process").click(function () {HTML - TextBox<p>Name <input id="name" class="inVals" type="text" /></p>jQueryvar name = $("#name").val();HTML – Dropdown, Single Selection<select id="classification" class="inVals" name="D1"><option value="1">Freshman</option><option value="2">Sophomore</option><option value="3">Junior</option><option value="4">Senior</option></select>jQueryvar classificationDesc = $("#classification option:selected").text(); var classificationNum = $("#classification option:selected").val();HTML - Checkboxes <p>Activities: <input name="activities" class="acts" type="checkbox" value="Soccer" />Soccer <input name="activities" class="acts" type="checkbox" value="Chess" />Chess <input name="activities" class="acts" type="checkbox" value="ACM" />ACM </p>jQuery var activities = []; $("input[name='activities']:checked").each(function() { activities.push($(this).val()); });HTML - RadioButtons<p>Mood:<input name="mood" type="radio" value="Happy" />Happy <input name="mood" type="radio" value="Copacetic" />Copacetic <input name="mood" type="radio" value="Sad" />Sad </p> jQueryvar mood = $("input[name='mood']:checked").val();HTML – Dropdown, Multiple Selection<select size="5" id="classes" multiple="multiple"><option value="3">CS 3300</option><option value="2">CS 3340</option><option value="4">CS 3410</option><option value="4">CS 3520</option><option value="3">CS 4721</option></select>jQuery var classes = []; var credits = []; var totalCredits = 0; $("#classes option:selected").each(function () { classes.push($(this).text()); credits.push($(this).val()); totalCredits += parseInt($(this).val()); });HTML – TextArea<p><textarea rows="10" id="message" cols="50"></textarea></p>jQuery var message = "Name: " + name + "\n"; message += "Class: " + classificationDesc + "-" + classificationNum + "\n"; message += "Activities: "; for (i = 0; i < activities.length; i++) message += activities[i] + (i<activities.length-1 ? ", " : ""); message += "\nMood: " + mood + "\n"; message += "Classes: "; for (i = 0; i < classes.length; i++) message += classes[i] + "-" + credits[i] + (i < classes.length - 1 ? ", " : ""); message += "\nTotal Credits: " + totalCredits; $("#message").val(message); });});ExamplesSee jq_ex1.html to illustrate double-click, css, fadeSee jq_styles.html to illustrate add css class, and toggling classesSee jq_ex2.html to illustrate loading a file from server.Optional Additional NotesEventsWhen the user interacts with a page, we want to change things in response. User interactions fire events which jQuery can respond to.See: the full list of jQuery events: do we change the HTML?See: the full list of jQuery effects: FunctionsSome functions take an optional argument which is a callback function. A callback function is executed after an effect is finished. many jQuery functions return a jQuery object, a second function can be chained to the result of the first function, etc. and Set ContentsHow do we get or set the contents of elements? These methods are useful:text() - Sets or returns the text content of selected elementshtml() - Sets or returns the content of selected elements (including HTML markup)val() - Sets or returns the value of form fieldsExamples (get): (set): HTML/CSS Reference: ContentsAdd/Remove the contents of a tag or tags themselves: CSSWe can add/remove existing CSS classes or add CSS on the fly.: How jQuery Works, jQuery Event Basics and Introduction to Effects. jQuery Fundamentals: jQuery Basics, Events & Event Delegation.External ExamplesjQuery API - all jQuery functionsjQuery Examples – Tons of examples20 Examples - Examples of 20 jQuery Learning Center - Nicely organized Chapters. jQuery Fundamentals - Chapter based tutorial with editor to try examples. To view the JavaScript Console: (a) Chrome: right-click page and choose: Inspect Element, (b) IE, press F12.ExpectationsYou have completed the required reading on jQuery and these are the expectations: ExpectationsGiven a description of client-side dynamic behavior write the HTML and jQuery to implement.Know how to process form elements.Know how to apply jQuery selectors (tag, class, id)Know how to apply jQuery actions (hide, show)Know how to apply jQuery click event ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download