JQuery - RIP Tutorial

3y ago
47 Views
10 Downloads
1.30 MB
88 Pages
Last View : 28d ago
Last Download : 3m ago
Upload by : Mariam Herr
Transcription

jQuery#jquery

Table of ContentsAbout1Chapter 1: Getting started with jQuery2Remarks2Versions2Examples3jQuery Namespace ("jQuery" and " ")3Getting Started3Explanation of code4Include script tag in head of HTML page5Avoiding namespace collisions6Loading jQuery via console on a page that does not have it.8The jQuery Object8Loading namespaced jQuery plugins8Chapter 2: ing HTTP Response Codes with .ajax()11Using Ajax to Submit a Form11Sending JSON data12All in one examples13Ajax Abort a Call or Request14Ajax File Uploads151. A Simple Complete Example152. Working With File Inputs153. Creating and Filling the FormData164. Sending the Files With Ajax16Chapter 3: Append18Syntax18

Parameters18Remarks18Examples18Appending an element to a container18Efficient consecutive .append() usage19HTML19JS19DO NOT do this.20Add to a separate array, append after loop completes20Using modern Array.* methods21Using strings of HTML (instead of jQuery built-in methods)21Manually create elements, append to document fragment22Dive deeperjQuery appendChapter 4: Attributes222324Remarks24Examples24Get the attribute value of a HTML element24Setting value of HTML attribute25Removing attribute25Differece between attr() and prop()25Chapter 5: Checkbox Select all with automatic check/uncheck on other checkbox change26Introduction26Examples262 select all checkboxes with corresponding group checkboxesChapter 6: CSS Manipulation2627Syntax27Remarks27Examples28Set CSS property28Get CSS property28

Increment/Decrement Numeric Properties28CSS – Getters and Setters28CSS Getter29CSS Setter29Chapter 7: document-ready eventExamples3030What is document-ready and how should I use it?30jQuery 2.2.3 and earlier31jQuery 3.031Notation31Asynchronous31Difference between (document).ready() and (window).load()32Attaching events and manipulating the DOM inside ready()32Difference between jQuery(fn) and executing your code before33Chapter 8: DOM ManipulationExamples3434Creating DOM elements34Manipulating element classes34Other API Methods37.html()38Sorting elements38Make it cute39Add a sort button39Set the initial value of sorting direction40Cache our DOM elements and sortList() out here to minimize our DOM processing40Wrap everything up in a doSort() function40Add click handler for ('#btn-sort')40All together now40Multi-level sorting (grouping sorted elements)41Add another button to toggle disabled group sorting42Chapter 9: DOM TraversingExamples4343

Select children of element43Iterating over list of jQuery elements43Selecting siblings44closest() method44Get next element45Get previous element46Filter a selection46The d() methodChapter 10: Each functionExamples474949Basic use49jQuery each function49Chapter 11: Element Visibility50Parameters50Examples50Overview50Toggle possibilities50Chapter 12: Events53Remarks53Examples53Attach and Detach Event HandlersAttach an Event Handler5353HTML53jQuery53Detach an Event Handler53HTML53jQuery53

jQueryDelegated Events5454Example HTML54The problem54Background information - Event propagation55Solution55In detail how solution works55Document Loading Event .load()56Events for repeating elements without using ID's56originalEvent57Get Scroll Direction57Switching specific events on and off via jQuery. (Named Listeners)58Chapter 13: Getting and setting width and height of an element59Examples59Getting and setting width and height (ignoring border)59Getting and setting innerWidth and innerHeight (ignoring padding and border)59Getting and setting outerWidth and outerHeight (including padding and border)59Chapter 14: jQuery .animate() Method61Syntax61Parameters61Examples61Animation with callbackChapter 15: jQuery Deferred objects and Promises6164Introduction64Examples64Basic promise creation64Asynchronous Promises Chaining64jQuery ajax() success, error VS .done(), .fail()65Get the current state of a promise66Chapter 16: PluginsExamples6767

Plugins - Getting Started67jQuery.fn.extend() method69Chapter 17: PrependExamples7070Prepending an element to a container70Prepend method70Chapter 18: 72Types of Selectors72Combining selectors75Descendant and child selectors76Other combinators76Group Selector : ","76Multiples selector : "" (no character)76Adjacent Sibling Selector : " "77General Sibling Selector : " "77Overview77Basic selectors77Relational operators77Caching Selectors77DOM Elements as selectors78HTML strings as selectors79Credits80

AboutYou can share this PDF with anyone you feel could benefit from it, downloaded the latest versionfrom: jqueryIt is an unofficial and free jQuery ebook created for educational purposes. All the content isextracted from Stack Overflow Documentation, which is written by many hardworking individuals atStack Overflow. It is neither affiliated with Stack Overflow nor official jQuery.The content is released under Creative Commons BY-SA, and the list of contributors to eachchapter are provided in the credits section at the end of this book. Images may be copyright oftheir respective owners unless otherwise specified. All trademarks and registered trademarks arethe property of their respective company owners.Use the content presented in this book at your own risk; it is not guaranteed to be correct noraccurate, please send your feedback and corrections to info@zzzprojects.comhttps://riptutorial.com/1

Chapter 1: Getting started with jQueryRemarksjQuery is a JavaScript library which simplifies DOM operations, event handling, AJAX, andanimations. It also takes care of many browser compatibility issues in underlying DOM andjavascript engines.Each version of jQuery can be downloaded from https://code.jquery.com/jquery/ in bothcompressed (minified) and uncompressed formats.VersionsVersionNotesReleaseDate1.0First stable le introduced into core2009-01-141.42010-01-141.5Deferred callback management, ajax module rewrite2011-01-311.6Significant performance gains in the attr() and val() methods2011-05-031.7New Event APIs: on() and off().2011-11-031.8Sizzle rewritten, improved animations and (html,1.9Removal of deprecated interfaces and code cleanup2013-01-151.10Incorporated bug fixes and differences reported from both the 1.9and 2.0 beta 14-01-241.122016-01-082.0Dropped IE 6–8 support for performance improvements andreduction in 42

VersionNotes2.2ReleaseDate2016-01-083.0Massive speedups for some jQuery custom selectors2016-06-093.1No More Silent Errors2016-07-07ExamplesjQuery Namespace ("jQuery" and " ")is the starting point for writing any jQuery code. It can be used as a function jQuery(.) or avariable jQuery.foo.jQueryis an alias for jQuery and the two can usually be interchanged for each other (except wherejQuery.noConflict(); has been used - see Avoiding namespace collisions). Assuming we have this snippet of HTML div id "demo div" class "demo" /div We might want to use jQuery to add some text content to this div. To do this we could use thejQuery text() function. This could be written using either jQuery or . i.e. jQuery("#demo div").text("Demo Text!");Or ("#demo div").text("Demo Text!");Both will result in the same final HTML div id "demo div" class "demo" Demo Text! /div As is more concise than jQuery it is the generally the preferred method of writing jQuery code.jQuery uses CSS selectors and in the example above an ID selector was used. For moreinformation on selectors in jQuery see types of selectors.Getting StartedCreate a file hello.html with the following content: !DOCTYPE html html head https://riptutorial.com/3

title Hello, World! /title /head body div p id "hello" Some random text /p /div script src "https://code.jquery.com/jquery-2.2.4.min.js" /script script (document).ready(function() { ('#hello').text('Hello, World!');}); /script /body /html Live Demo on JSBinOpen this file in a web browser. As a result you will see a page with the text: Hello,World!Explanation of code1. Loads the jQuery library from the jQuery CDN: script src "https://code.jquery.com/jquery-2.2.4.min.js" /script This introduces the global variable, an alias for the jQuery function and namespace.Be aware that one of the most common mistakes made when including jQuery isfailing to load the library BEFORE any other scripts or libraries that may dependon or make use of it.2. Defers a function to be executed when the DOM (Document Object Model) is detected to be"ready" by jQuery:// When the document is ready , execute this function . (document).ready(function() { . });// A commonly used shorthand version (behaves the same as the above) (function() { . });3. Once the DOM is ready, jQuery executes the callback function shown above. Inside of ourfunction, there is only one call which does 2 main things:1. Gets the element with the id attribute equal to hello (our selector #hello). Using aselector as the passed argument is the core of jQuery's functionality and naming; theentire library essentially evolved from extending document.querySelectorAllMDN.2. Set the text() inside the selected element to Hello,World!.# - Pass a selector to jQuery, returns our element ('#hello').text('Hello, World!');# - Set the Text on the elementhttps://riptutorial.com/4

For more refer to the jQuery - Documentation page.Include script tag in head of HTML pageTo load jQuery from the official CDN, go to the jQuery website. You'll see a list of differentversions and formats available.Now, copy the source of the version of jQuery, you want to load. Suppose, you want to loadjQuery 2.X, click uncompressed or minified tag which will show you something like this:https://riptutorial.com/5

Copy the full code (or click on the copy icon) and paste it in the head or body of your html.The best practice is to load any external JavaScript libraries at the head tag with the asyncattribute. Here is a demonstration: !DOCTYPE html html head title Loading jquery-2.2.4 /title script src "https://code.jquery.com/jquery-2.2.4.min.js" async /script /head body p This page is loaded with jquery. /p /body /html When using async attribute be conscious as the javascript libraries are then asynchronously loadedand executed as soon as available. If two libraries are included where second library is dependenton the first library is this case if second library is loaded and executed before first library then itmay throw an error and application may break.Avoiding namespace collisionsLibraries other than jQuery may also use as an alias. This can cause interference between thoselibraries and jQuery.To release for use with other libraries:https://riptutorial.com/6

jQuery.noConflict();After calling this function, is no longer an alias for jQuery. However, you can still use the variablejQuery itself to access jQuery functions:jQuery('#hello').text('Hello, World!');Optionally, you can assign a different variable as an alias for jQuery:var jqy jQuery.noConflict();jqy('#hello').text('Hello, World!');Conversely, to prevent other libraries from interfering with jQuery, you can wrap your jQuery codein an immediately invoked function expression (IIFE) and pass in jQuery as the argument:(function( ) { (document).ready(function() { ('#hello').text('Hello, World!');});})(jQuery);Inside this IIFE, is an alias for jQuery only.Another simple way to secure jQuery's alias and make sure DOM is ready:jQuery(function( ) { // DOM is ready// You're now free to use alias ('#hello').text('Hello, World!');});To summarize, : no longer refers to jQuery, while the variable jQuery does.var jQuery2 jQuery.noConflict() - no longer refers to jQuery, while the variable jQuerydoes and so does the variable jQuery2.jQuery.noConflict()Now, there exists a third scenario - What if we want jQuery to be available only in jQuery2? Use,var jQuery2 jQuery.noConflict(true)This results in neither nor jQuery referring to jQuery.This is useful when multiple versions of jQuery are to be loaded onto the same page. script src 'https://code.jquery.com/jquery-1.12.4.min.js' /script script var jQuery1 jQuery.noConflict(true); /script script src 'https://code.jquery.com/jquery-3.1.0.min.js' /script script // Here, jQuery1 refers to jQuery 1.12.4 while, and jQuery refers to jQuery 3.1.0. /script https://riptutorial.com/7

onflicts-other-libraries/Loading jQuery via console on a page that does not have it.Sometimes one has to work with pages that are not using jQuery while most developers are usedto have jQuery handy.In such situations one can use Chromeloaded page by running following:Developer Toolsconsole (F12) to manually add jQuery on avar j document.createElement('script');j.onload function(){ jQuery.noConflict(); };j.src ead')[0].appendChild(j);Version you want might differ from above(1.12.4) you can get the link for one you need here.The jQuery ObjectEvery time jQuery is called, by using () or jQuery(), internally it is creating a new instance of jQuery. This is the source code which shows the new instance:// Define a local copy of jQueryjQuery function( selector, context ) {// The jQuery object is actually just the init constructor 'enhanced'// Need init if jQuery is called (just allow error to be thrown if not included)return new jQuery.fn.init( selector, context );}Internally jQuery refers to its prototype as .fn, and the style used here of internally instantiating ajQuery object allows for that prototype to be exposed without the explicit use of new by the caller.In addition to setting up an instance (which is how the jQuery API, such as .each, children,filter,etc. is exposed), internally jQuery will also create an array-like structure to match the result of theselector (provided that something other than nothing, undefined, null, or similar was passed as theargument). In the case of a single item, this array-like structure will hold only that item.A simple demonstration would be to find an element with an id, and then access the jQuery objectto return the underlying DOM element (this will also work when multiple elements are matched orpresent).var div ("#myDiv");//populate the jQuery object with the result of the id selectorvar div div[0];//access array-like structure of jQuery object to get the DOM ElementLoading namespaced jQuery pluginsTypically when loading plugins, make sure to always include the plugin after jQuery.https://riptutorial.com/8

script src "https://code.jquery.com/jquery-3.1.1.min.js" /script script src "some-plugin.min.js" /script If you must use more than one version of jQuery, then make sure to load the plugin(s) after therequired version of jQuery followed by code to set jQuery.noConflict(true); then load the nextversion of jQuery and its associated plugin(s): script src "https://code.jquery.com/jquery-1.7.0.min.js" /script script src "plugin-needs-1.7.min.js" /script script // save reference to jQuery v1.7.0var oldjq jQuery.noConflict(true); /script script src "https://code.jquery.com/jquery-3.1.1.min.js" /script script src "newer-plugin.min.js" /script Now when initializing the plugins, you'll need to use the associated jQuery version script // newer jQuery document readyjQuery(function( ){// " " refers to the newer version of jQuery// inside of this function// initialize newer plugin ('#new').newerPlugin();});// older jQuery document ready oldjq(function( ){// " " refers to the older version of jQuery// inside of this function// initialize plugin needing older jQuery ('#old').olderPlugin();}); /script It is possible to only use one document ready function to initialize both plugins, but to avoidconfusion and problems with any extra jQuery code inside the document ready function, it wouldbe better to keep the references separate.Read Getting started with jQuery online: tartedwith-jqueryhttps://riptutorial.com/9

Chapter 2: AjaxSyntax var jqXHR .ajax( url [,settings] )var jqXHR .ajax( [settings] )jqXHR.done(function( data, textStatus, jqXHR ) {});jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});jqXHR.always(function( jqXHR ) {});ParametersParameterDetailsurlSpecifies the URL to which the request will be sentsettingsan object containing numerous values that affect the behavior of the requesttypeThe HTTP method to be used for the requestdataData to be sent by the requestsuccessA callback function to be called if the request succeedserrorA callback to handle errorstatusCodeAn object of numeric HTTP codes and functions to be called when theresponse has the corresponding codedataTypeThe type of data that you're expecting back from the servercontentTypeContent type of the data to sent to the server. Default is "application/x-wwwform-urlencoded; charset UTF-8"contextSpecifies the context to be used inside callbacks, usually this which refers tothe current target.RemarksAJAX stands for Asynchronous JavaScript and XML. AJAX allows a webpage to perform anasynchronous HTTP (AJAX) request to the server and receive a response, without needing toreload the entire page.Exampleshttps://riptutorial.com/10

Handling HTTP Response Codes with .ajax()In addition to .done, .fail and .always promise callbacks, which are triggered based on whetherthe request was successful or not, there is the option to trigger a function when a specific HTTPStatus Code is returned from the server. This can be done using the statusCode parameter. .ajax({type: {POST or GET or PUT etc.},url: {server.url},data: {someData: true},statusCode: {404: function(responseObject, textStatus, jqXHR) {// No content found (404)// This code will be executed if the server returns a 404 response},503: function(responseObject, textStatus, errorThrown) {// Service Unavailable (503)// This code will be executed if the server returns a 503 il(function(jqXHR, textStatus){alert('Something went wrong: ' textStatus);}).always(function(jqXHR, textStatus) {alert('Ajax request was finished')});As official jQuery documentation states:If the request is successful, the status code functions take the same parameters as thesuccess callback; if it results in an error (including 3xx redirect), they take the sameparameters as the error callback.Using Ajax to Submit a FormSometimes you may have a form and want to submit it using ajax.Suppose you have this simple form form id "ajax form" action "form action.php" label for "name" Name : /label input name "name" id "name" type "text" / label for "name" Email : /label input name "email" id "email" type "text" / input type "submit" value "Submit" / /form The following jQuery code can be used (within a (document).ready call) ('#ajax com/11

event.preventDefault();var form (this); .ajax({type: 'POST',url: form.attr('action'),data: form.serialize(),success: function(data) {// Do something with the response},error: function(error) {// Do something with the error}});});Explanation - the form, cached for reuse ('#ajax form').submit(function(event){ - When the form with ID "ajax form" is submitted runthis function and pass the event as a parameter. event.preventDefault(); - Prevent the form from submitting normally (Alternatively we canuse return false after the ajax({}); statement, which will have the same effect) url: form.attr('action'), - Get the value of the form's "action" attribute and use it for the"url" property. data: form.serialize(), - Converts the inputs within the form into a string suitable forsending to the server. I

Chapter 1: Getting started with jQuery 2 Remarks 2 Versions 2 Examples 3 jQuery Namespace ("jQuery" and " ") 3 Getting Started 3 Explanation of code 4 Include script tag in head of HTML page 5 Avoiding namespace collisions 6 Loading jQuery via console on a page that does not have it. 8 The jQuery Object 8 Loading namespaced jQuery plugins 8 .

Related Documents:

To get started with the jQuery UI library, you'll need to add the jQuery script, the jQuery UI script, and the jQuery UI stylesheet to your HTML. First, download jQuery UI; choose the features you need on the download page.

jQuery is the starting point for writing any jQuery code. It can be used as a function jQuery(.) or a variable jQuery.foo. is an alias for jQuery and the two can usually be interchanged for each other (except where jQuery.noConflict(); has been used - see Avoiding namespace collisions). Assuming we have this snippet of HTML -

jQuery is the starting point for writing any jQuery code. It can be used as a function jQuery(.) or a variable jQuery.foo. is an alias for jQuery and the two can usually be interchanged for each other (except where jQuery.noConflict(); has been used - see Avoiding namespace collisions). Assuming we have this snippet of HTML -

11 am - Bernie O'Malley, RIP Kevin O'Brien, RIP 5 pm - Gary Gilliland, RIP Mon. April 19th - 9 am - John Blair, Jr., RIP Tues. April 20th - 9 am - Michael & Gwen LaHair, RIP Wed. April 21st - 9 am - Anthony Dunn Thurs. April 22nd - 9 am - David Acevedo, RIP Fri. April 23rd - 9 am - Edmund Kelly, RIP Sat. April 24th - 9 am - Louis White, RIP

Rip Van Winkle! Rip Van Winkle! NARRATOR: Rip looked all around but could see no one. RIP: Did you hear that, boy? STRANGER: (distantly yelling) Rip Van Winkle! Rip Van Winkle! WOLF: Grrrr. NARRATOR: Wolf bristled up his back, looking down the valley. Then Rip saw a strange figure slowly toiling up the side of

browsers. However, the jQuery team has taken care of this for us, so that we can write AJAX functionality with only one single line of code jQuery - AJAX load() Method jQuery load() Method The jQuery load() method is a simple, but powerful AJAX method. The load() method loads data from a server and puts the returned data into the selected element.

jQuery UI 1.8.16 jQuery Timepicker Addon 1.4.5 jquery-2.1.0 jQuery-ui-1.10.4 jquery-2.1.0 jQuery.event.drag - v 2.2 . WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH T

2nd Grade English Language Arts Georgia Standards of Excellence (ELAGSE) Georgia Department of Education April 15, 2015 Page 1 of 6 . READING LITERARY (RL) READING INFORMATIONAL (RI) Key Ideas and Details Key Ideas and Details ELAGSE2RL1: Ask and answer such questions as who, what, where, when, why, and how to demonstrate understanding of key details in a text. ELAGSE2RI1: Ask and answer .