Jquery Tutorials - How - Shared
Jquery Tutorials - How - Shared
Acknowledgement
Acknowledgement
I would like to thank John Resig for such a nice invention of jQuery that really changes the way JavaScript code is written. Apart from John I would also like to thanks all the project team who is supporting the development of jQuery and enhancing it on regular basis. It was almost impossible to write this small book without the help from jQuery.com website from where I have learnt and practiced jQuery. So a lot of thanks to the team behind the jQuery.com website.
Acceptance
I do accept that I am not master of any subject as learning is an endless journey, so if you find any error or improvement needed in this book, kindly let me know at Sheo.Narayan@ItFunda.Com.
Copyright
Content of this book is free to use by anyone either for personal or commercial use, however you are not allowed to exactly copy-paste its content (code snippet can be copy-pasted), if you are doing so kindly provide a reference of this book. All Logos, company names, product names, and technology names used here if any are only for reference purposes and they may be respective owner's rights or trademarks. Any other contents are copyright to IT Funda Corporation.
Contents
Acknowledgement .......................................................................................................................................... 2 Purpose of this book ....................................................................................................................................... 2 How this book has been organized ................................................................................................................ 2 Acceptance ..................................................................................................................................................... 2 Copyright ........................................................................................................................................................ 2 Who this book is written for ........................................................................................................................... 3 What is jQuery? .............................................................................................................................................. 8 Why jQuery? ................................................................................................................................................... 8 Where to download jQuery from? ................................................................................................................. 8 How to use jQuery? ........................................................................................................................................ 8 To load local jQuery file ............................................................................................................................. 9 What is the difference between jQuery-x.x.x.js and jQuery.x.x.x-min.js ................................................... 9 Which version of jQuery file should be used? ........................................................................................... 9 Loading jQuery from CDN (Content Distribution Network) ....................................................................... 9 What is CDN? ......................................................................................................................................... 9 Microsoft - To load jQuery from Microsoft AJAX CDN ........................................................................... 9 Google - To load jQuery from Google Libraries API ............................................................................. 10 Why to load jQuery file from CDN? ..................................................................................................... 10 What if the latest jQuery version is available and I am still referring older version of jQuery file from CDNs?................................................................................................................................................... 10 How to load local jQuery file in case CDN is not available? ......................................................................... 11 How to execute jQuery code? ...................................................................................................................... 11 jQuery Core .................................................................................................................................................. 12 jQuery Selectors ........................................................................................................................................... 13 What is Selectors? ............................................................................................................................... 13 How to select all elements of the page? - All Selector (*) ................................................................ 13 How to select a particular element having a specific class? - Class Selector (.class) ........................ 13 How to select all elements of specific type? - Element Selector (element) ...................................... 13 How to select an element having a specific id - ID Selector (#id) ..................................................... 13 How to select multiple elements at a time? Multiple Selector (selector1, selector2, selectorN) ..... 14 How to select an element based on its attribute - Attribute Selector (element*attribute$=name+) ............................................................................................................................................................. 14 How to select the first child of the parent element? - First child selector ........................................... 14 How to select last child of the parent element? Last child selector ................................................. 14 4 jQuery how to - Sheo Narayan, IT Funda Corporation.
Visit DotNetFunda.Com for more articles & tutorials. Visit ITFunda.Com for training materials
How to select a specific child of the parent element? nth child selector ............................................ 15 jQuery Attributes .............................................................................................. Error! Bookmark not defined. How to add a css class to an element? - .addClass() ............................... Error! Bookmark not defined. How to get or set the attribute value of an element? - .attr() ................ Error! Bookmark not defined. How to determine if a given css class name has been used in an element - .hasClass() ................ Error! Bookmark not defined. How to get or set the html content for a particular element - .html() .... Error! Bookmark not defined. How to append html content to the element? .append() ....................... Error! Bookmark not defined. How to append the source element content to the target? - .appendTo() ............Error! Bookmark not defined. How to insert html content at the beginning of an element - .prepend()Error! Bookmark not defined. How to insert html content from source element to the beginning of target - .prependTo() ........ Error! Bookmark not defined. How to get or set the element text? .text() ............................................. Error! Bookmark not defined. How to remove css class from an element? .removeClass() .................... Error! Bookmark not defined. How to remove an attribute from an element? .removeAttr() ............... Error! Bookmark not defined. How to toggle the class of an element? .toggleClass() ............................ Error! Bookmark not defined. How to get or set the value of an element? .val() ................................... Error! Bookmark not defined. jQuery Traversing ............................................................................................. Error! Bookmark not defined. How to add an element to a particular element - .add() ......................... Error! Bookmark not defined. How to get all the children elements of a element? - .children() ............ Error! Bookmark not defined. How to iterate through each specified element of the page? - .each() .. Error! Bookmark not defined. How to find a specific element form the group of similar kind of elements? - .eq() ... Error! Bookmark not defined. How to filter an element from the group of similar kind of elements based on its attribute value? .filter() ..................................................................................................... Error! Bookmark not defined. How to find the descendent of an element - .find() ................................ Error! Bookmark not defined. How to find the first element from the matched element .first() ........ Error! Bookmark not defined. How to find the last element form the matched element - .last() .......... Error! Bookmark not defined. How to find the immediate next element from the element found by the selector - .next() ........ Error! Bookmark not defined. How to find the parent element of an element - .parent() ..................... Error! Bookmark not defined. jQuery Manipulations ....................................................................................... Error! Bookmark not defined. How to place content before a specific element? - .before() .................. Error! Bookmark not defined. How to place content after a specific element? - .after() ........................ Error! Bookmark not defined. 5 jQuery how to - Sheo Narayan, IT Funda Corporation.
Visit DotNetFunda.Com for more articles & tutorials. Visit ITFunda.Com for training materials
How to get and set the height of an element? .height() ......................... Error! Bookmark not defined. How to get and set the width of an element? - .width() ......................... Error! Bookmark not defined. How to insert an element after a specific element? - .insertAfter() ........ Error! Bookmark not defined. How to insert an element before a specific element? - .insertBefore() .. Error! Bookmark not defined. How to retrieve the position of an html element? - .position()............... Error! Bookmark not defined. How to get and set the horizontal scroll position of an element? - .scrollLeft().....Error! Bookmark not defined. How to get and set the vertical position of an element? - .scrollTop() ... Error! Bookmark not defined. How to unwrap the parent element from the specific element? - .unwrap() ........Error! Bookmark not defined. How to wrap an element from a specific element? - .wrap() .................. Error! Bookmark not defined. jQuery Events ................................................................................................... Error! Bookmark not defined. How to attach a blur event to an element - .blur() .................................. Error! Bookmark not defined. How to attach change event to an element - .change() .......................... Error! Bookmark not defined. How to attach a click event to an element - .click() ................................ Error! Bookmark not defined. How to attach double click event to an element - .dblclick() .................. Error! Bookmark not defined. How to attach and detach an event to and from an element? - .bind() & .unbind() .... Error! Bookmark not defined. How to attach an event to a particular type of element for the whole life of the page - .live() .... Error! Bookmark not defined. How to detach an event from a particular type of element for the whole life of page - .die() ...... Error! Bookmark not defined. How to attach an error event to an element? - .error() .......................... Error! Bookmark not defined. How to get the mouse position? - event.pageX & event.pageY .............. Error! Bookmark not defined. How to stop the default behavior of an element? event.preventDefault() ............Error! Bookmark not defined. How to find out which element has initiated a particular event - event.target .....Error! Bookmark not defined. How to attach focus event to an html element? - .focus() ...................... Error! Bookmark not defined. How to attach focus out event to an element? - .focusout() ................... Error! Bookmark not defined. How to attach hover event to an element? - .hover() ............................. Error! Bookmark not defined. How to attach keydown event to an element? - .keydown() .................. Error! Bookmark not defined. How to attach keypress event to an element? - .keypress().................... Error! Bookmark not defined. How to attach key up event to an element? - .keyup() ........................... Error! Bookmark not defined. How to attach load event to an element? - .load().................................. Error! Bookmark not defined. How to attach mouse down event to an element? - .mousedown() ....... Error! Bookmark not defined. 6 jQuery how to - Sheo Narayan, IT Funda Corporation.
Visit DotNetFunda.Com for more articles & tutorials. Visit ITFunda.Com for training materials
How to attach mouse enter event to an element? -.mouseenter() ......... Error! Bookmark not defined. How to attach mouse leave event to an element? - .mouseleave() ........ Error! Bookmark not defined. How to attach mouse move event to an element? - .mousemove() ....... Error! Bookmark not defined. How to attach mouse up event to an element? - .mouseup() ................. Error! Bookmark not defined. How to attach resize event to an element? - .resize() ............................. Error! Bookmark not defined. How to attach scroll event to an element? -.scroll() ............................... Error! Bookmark not defined. How to select text or attach select event to an element? - .select() ...... Error! Bookmark not defined. How to catch the Submit event of the Form element? - .submit() .......... Error! Bookmark not defined. How to attach toggle event to an element? - .toggle() ........................... Error! Bookmark not defined. How to trigger an event of an element? - .trigger() ................................ Error! Bookmark not defined. How to attach unload event? - .unload() ................................................. Error! Bookmark not defined. jQuery effects ................................................................................................... Error! Bookmark not defined. How to animate a particular element? - .animate() ................................ Error! Bookmark not defined. How to hide a particular element? .hide() ............................................... Error! Bookmark not defined. How to hide an element using slide up effect? .slideUp() ....................... Error! Bookmark not defined. How to show an element? - .show() ........................................................ Error! Bookmark not defined. How to toggle display an element with sliding effect? -.slideToggle() .... Error! Bookmark not defined. How to toggle display an element? - .toggle()......................................... Error! Bookmark not defined. How to stop currently executing animation? - .stop() ............................. Error! Bookmark not defined. How to remove unexecuted/unused animation items from the queue? - .clearQueue() .............. Error! Bookmark not defined. How to display an element using slide down effect? - .slideDown() ....... Error! Bookmark not defined. How to display an element using fading effect - .fadeIn() ....................... Error! Bookmark not defined. How to hide an element using fading effect - .fadeOut() ........................ Error! Bookmark not defined. How to adjust the opacity of an element? - .fadeTo() ............................. Error! Bookmark not defined. How to delay the execution of a subsequent method? - .delay() ........... Error! Bookmark not defined. How to get the number of items to be executed on a particular element? - .queue(). Error! Bookmark not defined. How to remove the current executing item from the queue? - .dequeue() ...........Error! Bookmark not defined. How to on and off the animation effect - jQuery.fx.off ........................... Error! Bookmark not defined. jQuery Ajax ....................................................................................................... Error! Bookmark not defined. How to send asynchronous HTTP request to the server and get response? - .ajax(type, url, data, success) .................................................................................................... Error! Bookmark not defined.
What is jQuery?
How to send request to and get response from server using HTTP Get and HTTP Post - .get(), .post() ................................................................................................................. Error! Bookmark not defined. How to load JSON data from server? - .getJSON(Url, data, callBack)...... Error! Bookmark not defined. How to load a page data from the server into a particular element - .load(url, callBack) ............ Error! Bookmark not defined. How to serialize the form element data that can be submitted to the server - .serialize() ........... Error! Bookmark not defined. How to register a handler to be called when first ajax request begins? - .ajaxStart() . Error! Bookmark not defined. How to perform certain operations when ajax request is about to send? -.ajaxSend()................. Error! Bookmark not defined. How to know if my ajax request is successful? - .ajaxSuccess() .............. Error! Bookmark not defined. How to know when my ajax request is complete? - .ajaxComplete() ..... Error! Bookmark not defined. How to know when all ajax request is completed and no other ajax activity is in process? - .ajaxStop() ................................................................................................................. Error! Bookmark not defined. How to know if an error occurred while performing ajax operation - .ajaxError() Error! Bookmark not defined.
What is jQuery?
jQuery is not a language but it is a well written JavaScript code, As quoted on official jQuery website it is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. In order to work with jQuery you should be aware of basics of JavaScript, HTML and CSS. It was released in January 2006 at BarCamp NYC by John Resig. Licensing: It is free, open source software Dual-licensed under the MIT License and the GNU General Public License. Microsoft has integrated jQuery officially into its IDE Visual Studio 2010 and jQuery intellisense is available in Visual Studio 2010 now.
Why jQuery?
jQuery is very compact and well written JavaScript code that increases the productivity of the developer by enabling them to achieve critical UI functionality by writing very less amount of code. It helps to 8 jQuery how to - Sheo Narayan, IT Funda Corporation.
Visit DotNetFunda.Com for more articles & tutorials. Visit ITFunda.Com for training materials
Improve the performance of the application Develop most browser compatible web page Implement UI related critical functionality without writing hundreds of lines of codes Fast Extensible jQuery can be extended to implement customized behavior
Other advantages of jQuery are No need to learn fresh new syntaxes to use jQuery, knowing simple JavaScript syntax is enough Simple and Cleaner code, no need to write several lines of codes to achieve complex functionality.
Ideally this markup is kept in under <head></head> tag of your web page, however you are free to keep anywhere you want.
10
OR
<script src=http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.4.min.js type="text/javascript"></script>
Google - To load jQuery from Google Libraries API jQuery file can be loaded from Google CDN for more details, go to http://code.google.com/apis/libraries/devguide.html. You will need to keep following tag in your page.
<script type="text/javascript" language="Javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></sc ript>
Why to load jQuery file from CDN? You may ask that if we can load the jQuery file from our own server why to load it from the CDNs. The answer is logical and very simple. The browser behavior is that whenever it loads any webpage, it keeps related files (eg. Javascript file, CSS file and Images) used for that page into its cache (also called history). When next time the user browses any web page, browser loads only those files that are new or modified and is not available in the browser cache or history. In this way, browser improves its performance and loads the page. The possibility is that if more and more websites are using CDNs, the user might have already browsed some other web pages that is using CDNs jQuery file and that file may have into browser cache; so when user browse your page and you are also using CDNs 10 jQuery how to - Sheo Narayan, IT Funda Corporation.
Visit DotNetFunda.Com for more articles & tutorials. Visit ITFunda.Com for training materials
11
file, the older cached version of jQuery file will be used. In this way your page will load faster as browser will not have to load the jQuery file for your page again. The benefit 1. Faster page load as jQuery file need not to be downloaded 2. Saves your bandwidth as jQuery file is not loaded from your server 3. Scalable - generally CDNs place these files on the servers located at different geographical locations of the world so that they load faster so irrespective of from where your user is browsing your page, your application runs well. What if the latest jQuery version is available and I am still referring older version of jQuery file from CDNs? Do not worry about it, its a general promise made by CDNs that they will remain hosting the older version of the files on the same location where they had initially released; so even if newer version of the files are released, the older version remains there on the CDNs and your web page still works.
Replace bolded path with your own jQuery file path on the server. In the above code, first line tries to load the jQuery file from CDN, if browser could load the file successfully, jQuery variable will not be undefined and next script will not run otherwise next script will run that will write the script tag to load the jQuery file from your server.
jQuery Core
12
OR
<script language="javascript" type="text/javascript"> $("#div1").css("border", "2px solid green"); </script>
The benefit of executing jQuery code in this way is that it doesnt wait the whole page to load completely, so in case you want user to see the effects as soon as the corresponding elements are loaded, you can use this. However the disadvantage is that if the element on which jQuery has to execute has not loaded then it will error out or you will not get desired result; so while using this way of executing jQuery code, you will have to make sure that the element on which you want to work with jQuery is loaded first (you can place your jQuery code right after your HTML element). 2. Execute jQuery only when the complete DOM objects (the complete page has been loaded). You will have to wrap your code in .ready function.
<script language="javascript" type="text/javascript"> $(document).ready(function () { $("#div1").css("border", "2px solid green"); }); </script>
This is the better and safer way to execute jQuery. This makes sure that jQuery code will execute only if complete page has been loaded in the browser so you are rest assured that user will not see any undesired behavior on the page. As a developer, the decision of where and how to write jQuery code lies on you. I prefer to use 2nd method as it ensures that my complete page is loaded in the browser and I am ready to play with any element available on the page. Note, the url provided in orange color beside each topic below is the part of complete book, please contact at contact@ITFundaCorporation.com for complete book.
jQuery Features
jQuery Core
Demo url: http://localhost:9007/jQueryWeb/jQueryCore.aspx jQuery accepts a string enclosed with double quote () that can contain a CSS selector which is used to match a set of elements on the web page. 12 jQuery how to - Sheo Narayan, IT Funda Corporation.
Visit DotNetFunda.Com for more articles & tutorials. Visit ITFunda.Com for training materials
jQuery Selectors
13
jQuery code can start with either jQuery word or a $ (dollar symbol). Take a look at below code snippet
<script language="javascript" type="text/javascript"> $(function () { jQuery("#div1").css("border", "2px solid red"); }); </script>
OR
<script language="javascript" type="text/javascript"> $(function () { $("#div1").css("border", "2px solid green"); }); </script>
Both above code snippets are functionally same and do the same thing. So you can either user jQuery or $ when you are writing jQuery code.
jQuery Selectors
Demo url: http://localhost:9007/jQueryWeb/Selectors.aspx What is Selectors? To work with an element on the web page, first we need to find them. To find the html element in jQuery we use selectors. jQuery provides many selectors out of the box. Lets explain some of the very useful selectors in how to ways. How to select all elements of the page? - All Selector (*) To select all elements of the page, we can use all selector, for that we need to use * (asterisk symbol).
<script language="javascript" type="text/javascript"> $("*").css("border", "5px dashed green"); </script>
Above code will select all elements of the web page and apply border width as 5 pixel, style as dashed and color as green. Demo url: http://localhost:9007/jQueryWeb/Selectors/AllSelector.aspx How to select a particular element having a specific class? - Class Selector (.class) To select an element with a specific class, class selector can be used. We need to prefix the class name with . (dot).
<script language="javascript" type="text/javascript"> $(".class1").css("border", "5px solid green"); </script>
13
jQuery Selectors
14
Above code will select all elements of the web page having class as class1 and apply css style border width as 5 pixel, style as solid and color as green. Demo url: http://localhost:9007/jQueryWeb/Selectors/ClassSelector.aspx How to select all elements of specific type? - Element Selector (element) To select all elements of specific type, we can use element selector. We need to use the html tag name.
<script language="javascript" type="text/javascript"> $("p").css("border", "5px solid green"); </script>
Above code will select all p (paragraph) elements of the web page and apply css style border width as 5 pixel, style as solid and color as green. Demo url: http://localhost:9007/jQueryWeb/Selectors/ElementSelector.aspx How to select an element having a specific id - ID Selector (#id) To select an element having a specific id, id selector can be used. We need to prefix the id with # (hash symbol). <script language="javascript" type="text/javascript"> $("#p1").css("border", "5px solid green"); </script> Above code will select all html elements having id attribute as p1 and apply css style border width as 5 pixel, style as solid and color as green. Demo url: http://localhost:9007/jQueryWeb/Selectors/IdSelector.aspx How to select multiple elements at a time? Multiple Selector (selector1, selector2, selectorN) To select multiple elements having different attributes, multiple selector can be used. We can mix the class selector, element selector, id selector all in this selector separated by , (comma).
<script language="javascript" type="text/javascript"> $("p.class1, #p1").css("border", "5px solid green"); </script>
Above code will select all paragraph (p) having class attribute set as class1 and all html elements having id attribute as p1 and apply css style border width as 5 pixel, style as solid and color as green. Demo url: http://localhost:9007/jQueryWeb/Selectors/MultipleSelector.aspx How to select an element based on its attribute - Attribute Selector (element*attribute$=name+) To select an element based on a particular attribute value, attribute selector can be used. For example, if we have multiple textboxes on the page but we want to select only one textbox having id as txtName, we can use attribute selector.
<script language="javascript" type="text/javascript"> $('input[id$="txtName"]').val('My data'); </script>
14
jQuery Selectors
15
Above code snippet will select the textbox having id as txtName and set its value as My data. Notice that as against all other selectors, this selector is written in the single quote () instead of double quote () however the attribute value is written in the double quote (). Demo url: http://localhost:9007/jQueryWeb/Selectors/AttributeSelector.aspx How to select the first child of the parent element? - First child selector To select first child of the parent element first child selector can be used.
<script language="javascript" type="text/javascript"> $("#div2 p:first-child").css("background", "red"); </script>
Above code snippet will select the first paragraph (p) element that is inside the div element whose id is div2 and will change the background color as red. Demo url: http://localhost:9007/jQueryWeb/Selectors/firstChildSelector.aspx How to select last child of the parent element? Last child selector To select the last child of the parent element last child selector can be used.
<script language="javascript" type="text/javascript"> $("#div2 p:last-child").css("background", "red"); </script>
Above code snippet will select the last paragraph (p) element that is inside the div element whose id is div2 and will change the background color as red. Demo url: http://localhost:9007/jQueryWeb/Selectors/lastChildSelector.aspx How to select a specific child of the parent element? nth child selector To select the specific child of the parent element nth child select can be used.
<script language="javascript" type="text/javascript"> $("#div2 p:nth-child(2)").css("background", "red"); </script>
Above code snippet will select the 2nd paragraph (p) element that is inside the div element whose id is div2 and will change the background color as red. Demo url: http://localhost:9007/jQueryWeb/Selectors/nthChildSelector.aspx
For rest chapters and complete source code of this book, please contact at contact@ITFundaCorporation.com or call to +91-40-6555-3349 , +91-77025-60638.
15