jQuery

Ajax relative/absolute paths

http://api.jquery.com/jquery.ajax/
1. If we put slash at the beginning of ajax url, ajax url pattern will be `hostname/yourFile` example:
// current url: http://sample.com/users
// ajax code load from users page

$.ajax({
   url: '/yourFile.php',
   ...
});

// ajax url will be: http://sample.com/yourFile.php
2. If we don't use slash at the beginning, ajax url will add to the current url in the browser. example:
// current url: http://sample.com/users
// ajax code load from users page

$.ajax({
    url: 'yourFile.php',
    ...
});

//...ajax url will be http://simple.com/users/yourFile.php

If you invoke a page without an ending /:
http://atlas/Reporter  
the relative urls from ajax calls on that page are ignoring the last segment:
http://atlas/_relative_url_passed_to_ajax

If you end with /:
http://atlas/Reporter/  
the relative urls are using the last path segment Reporter:
http://atlas/Reporter/_relative_url_passed_to_ajax
find() vs children():

  1. find() – search through the matched elements’ child, grandchild, great-grandchild... all levels down.
  2. children() – search through the matched elements’ child only (single level down).
How to find out jQuery's version

  • jQuery.fn.jquery
  • jQuery().jquery
  • $.fn.jquery
  • $().jquery
filter(selector)
Consider a page with a simple list on it:
1
2
3
4
5
6
7
8
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
</ul>
We can apply this method to the set of list items:

$( "li" ).filter( ":even" ).css( "background-color", "red" );

The result of this call is a red background for items 1, 3, and 5, as they match the selector (recall that :even and :odd use 0-based indexing).
filter(fn)
<ul>
<li><strong>list</strong> item 1 - one strong tag</li>
<li><strong>list</strong> item <strong>2</strong> -
two <span>strong tags</span></li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
</ul>
We can select the list items, then filter them based on their contents:
1
2
3
4
5
$( "li" )
.filter(function( index ) {
return $( "strong", this ).length === 1;
})
.css( "background-color", "red" );

1
2
3
4
5
$( "li" )
.filter(function( index ) {
return index % 3 === 2;
})
.css( "background-color", "red" );

$( "div" )
.css( "background", "#c8ebcc" )
.filter( ".middle" )
.css( "border-color", "red" );
Selectors:
type1:

<input name="man-news">//matches
<input name="milkman">//matches
<input name="letterman2">//matches
<input name="newmilk">
<script>
$( "input[name*='man']" ).val( "has man in it!" );
</script>
type2:
<input name="man-news">
<input name="milk man">//matches
<input name="letterman2">
<input name="newmilk">
<script>
$( "input[name~='man']" ).val( "mr. man is in it!" );
</script>
type3:

<a href="example.html" hreflang="en">Some text</a>//macthed
<a href="example.html" hreflang="en-UK">Some other text</a>//macthed
<a href="example.html" hreflang="english">will not be outlined</a>
<script>
$( "a[hreflang|='en']" ).css( "border", "3px dotted green" );
</script>
type4:

<input name="newsletter">//matched
<input name="milkman">
<input name="jobletter">//matched
<script>
$( "input[name$='letter']" ).val( "a letter" );
</script>
jQuery's design pattern:
I believe jQuery uses this pattern in its core, as well as encouraging plug-in developers to use the pattern. Using this pattern is a handy and efficient way of keeping the global namespace clear of clutter, which is further useful by assisting developers in writing clean, encapsulated code.

Lazy Initialization:
$(document).ready(function(){
    $('div.app').myPlugin();
});
$('div').css({
    opacity: .1 // opacity in modern browsers, filter in IE.
});
// higher level interfaces (facades) for $.ajax();
$.getJSON();
$.get();
$.getScript();
$.post();
// jQuery utilizes it's own event system implementation on top of DOM events.
$('div').click(function(){})
$('div').trigger('click', function(){})
$.each(function(){});
$('div').each(function(){});
$('div').toggle(function(){}, function(){});
$.proxy(function(){}, obj); // =oP
$('<div class="hello">world</div>');
// this feels like cheating...
$.fn.plugin = function(){}
$('div').plugin();
// CONFIG is shared
$.fn.plugin = function(CONFIG){
     CONFIG = $.extend({
         content: 'Hello world!'
     }, CONFIG);
     this.html(CONFIG.content); 
}
The Composite pattern is also very commonly used in jQuery. Having worked with other libraries, I can see how this pattern is not so obvious as it looks at first sight. The pattern basically says that,
a group of objects are to be treated in the same way as a single instance of an object.
For example, when dealing with a single DOM element or a group of DOM elements, both can be treated in a uniform manner.
$('#someDiv').addClass('green'); // a single DOM element

$('div').addClass('green');      // a collection of DOM elements
noConflict()
Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all the functionality is available without using $.
Run $.noConflict() method to give control of the $ variable back to whichever library first implemented it. This helps us to make sure that jQuery doesn't conflict with the $ object of other libraries.
Here is simple way of avoiding any conflict −
// Import other Library
// Import jQuery Library
$.noConflict();
// Code that uses other library's $ can follow here.
This technique is especially effective in conjunction with the .ready() method's ability to alias the jQuery object, as within the .ready() we can use $ if we wish without fear of conflicts later −

// Import other library
// Import jQuery
$.noConflict();
jQuery(document).ready(function($) {
   // Code that uses jQuery's $ can follow here.
});
// Code that uses other library's $ can follow here.

animate(cssProperties, duration, easing, callback)

Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The default duration is 400milliseconds. The strings 'fast' and 'slow' can be supplied to indicate durations of 200 and 600 milliseconds, respectively.


An easing function specifies the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.
$( "p" ).animate({
height: 200,
width: 400,
opacity: 0.5
}, 1000, "linear", function() {
alert( "all done" );
});

data():

jQuery's data function allows you to store and retrieve any associated data with any jQuery object.
Primarily, it can also be used to read data- attributes set on any node in the html.
Example 1
HTML: <div id="myNode" data-foo="bar"></div>.
jQuery Code: $("#myNode").data("foo") //bar
Example 2
Likewise I can store a value w.r.t any node too.
jQuery Code:
$("#myNode").data("foo","baz") $("#myNode").data("foo") //baz
One important thing to note here is, that when one sets a data on the note using the data API, the html is not updated in the DOM. If you want to update the HTML, you might want to stick to the attr("data-foo","baz") method.
While one can read strings stored in HTML data attributes, you can also assign an object while storing a value using the data API.
There are various use-cases where developers link an object with a node.
e.g.
var obj = {
  name : "test"
}
$("#myNode").data("foo",obj);

$("#myNode").data("foo") === obj //true

Go ahead, explore the API here.

bind() vs live() vs delegate() vs on

bind() doesn't ork on dynamically added elements and below is short hand method for bind().
one of the cons is the method attaches the same event handler to every matched element in the selection.
.click(fn(){
})

.bind(): This is the easiest and quick method to bind events. But the issue with bind() is that it doesn't work for elements added dynamically that matches the same selector. bind() only attach events to the current elements not future element. Above that it also has performance issues when dealing with a large selection.

.delegate(): The .delegate() method behaves in a similar fashion to the .live() method, but instead of attaching the selector/event information to the document, you can choose where it is anchored and it also supports chaining.

.live(): This method overcomes the disadvantage of bind(). It works for dynamically added elements or future elements. Because of its poor performance on large pages, this method is deprecated as of jQuery 1.7 and you should stop using it. Chaining is not properly supported using this method.

.on(): Since live was deprecated with 1.7, so new method was introduced named ".on()". This method provides all the goodness of previous 3 methods and it brings uniformity for attaching event handlers.

Q. What is jQuery?
jQuery can simply be interpreted as most advanced JavaScript framework which is used for performing high-level applications which include feature-rich, fast,and  lightweight framework which assists in to through the HTML DOM, add Ajax interaction,build animations, manipulation of the page content, modify the alignment and render cool UI effect. This is a client-side scripting language.
Q. Can differentiate between jQuery and JavaScript?
The difference between the jQuery and the JavaScript can simply be explained.
JavaScript can simply be interpreted as a high-level application language whereas, jQuery can be interpreted as a library which is built within the JavaScript language & helps in the better functioning of JavaScript. 
Q. Can a jQuery library be used for server scripting?
jQuery can be interpreted as an internally built library which is being used in the JavaScript.
And jQuery is strictly been designed with the functionality of client-side scripting. jQuery is not compatible with server-side scripting. 
Q. Explain the basic requirement, to begin with, jQuery?
In order to get begin with the jQuery, all that one needs to do at the beginning is to make a reference to its complete library. After this, you will be having access to all the application files which are present within the library. jQuery latest version can now get downloaded from jQuery.com.
Enthusiastic about exploring the skill set of jQuery? Then, have a look at the jQuery Training Course together additional knowledge. 
Q. Why exactly is the need for the use of jQuery?
jQuery is a highly programmed internal library for the better functioning of JavaScript. It handles a number of applications and its prominence can never be ignored. The following list will be depicting the reasons for why is the need to use jQuery?
jQuery comes very handily for the purpose of designing user-friendly web applications.
* By making an effective use of jQuery the performance of an application can be greatly enhanced.
* Very fast and extensible.
* Only minimal lines of codes will be sufficient for writing UI related functions. 
Q. State different jQuery methods that are used to provide effects?
 jQuery has a set of methods implying which we can expect to provide different effects within the system. Some of the jQuery methods include
* FadeOut()
* Toggle()
* Hide()
* Show()
* FadeIn() and
Q. Describe the minimized version of the jQuery and its benefits.
With the minimized version of the jQuery, the efficiency of the webpage can be greatly improved. The effectiveness of the webpage which is having a minimized version of jQuery will be a lot better than the effectiveness of the webpage which is having a normal js file.
This is the reason why most of the web pages are nowadays are found to have a minimized version of the jQuery. 
Q. Explain about different scenarios where jQuery can be effectively implemented?
jQuery is a highly advanced library application which extensively is used in following scenarios:
* Apply CSS static or dynamic functions.
* Calling functions on events.
* For the purpose of manipulation.
* For creating different animation effects.
Having the presence of all the advanced library applications jQuery is best at maintaining different applications with a higher degree of effectiveness. 
Q. Explain about the jQuery connect?
 jQuery connect can simply be interpreted as a plug-in which is used to connect or bind one function to the another. This will be helpful for executing the fro any other function or the plug-in is executed. 
Q. Which parameters are being used for the jQuery Ajax method?
JQuery Ajax method makes use of four different parameters which include
* URL – The URL must be clearly specified in order to send the request.
* type – Specifies the type of request(Get or Post)
* data – Specifies data to be sent to the server
* Cache – This tells if the browser should index the specific page or not. 
Q. Explain the ways through which we can include jQuery on a page?
Including jQuery in a page can be done with the help of the following ways.
* Local copy inside script tag
Remote copy of jQuery.com
* By keeping a remote copy of Ajax API
* Making a local copy of script manager control
* Embedded script using client script object
Q. Differentiate the concepts of ID selector and class selector in jQuery?
Just like they are used in the CSS, both ID selector and Class selector are used for the same functioning .
In order explain the functioning of both the concepts in simpler words, ID selector uses ID while class selector makes use of a class to select the different elements.
In the case where you are needed to select only one element then we have to go with the ID selector. And if you want to select a group of elements, then we have to go with the class selector.

jQuery Practical Interview Questions & Answers

Q. Explain the exact purpose of the animate function in jQuery.
The animate function is extensively being used in the jQuery. It is an advanced concept which is well received by the audience. Well, the main feature of the animation function in jQuery is to apply the custom animation effect to different elements. 
The syntax for this function is as follows
Syntax:
$(selector).animate({params}, [duration], [easing], [callback])  
Here,
* "param" defines the CSS properties where are intended to apply the animation.
* "duration" it simply depicts for what exact period of time the animation will run. Its values are:   "slow", "fast", "normal" or it can even be milliseconds.
* "easing" is the string which specifies the function for the transition.
* "callback" it is the function with the help of which we can call an action upon the completion of the animation. 
Q. What is JQuery.noConflict?
In order to help the system to overcome the conflicts between the different libraries and frameworks the jQuery no-conflict option given by the jQuery. This concept is really advanced which has been developed over the recent times. In the case of any conflicts which arise between the libraries and frameworks using this jQuery.noConflict function will help in overcoming all the conflicts. 
Q. Explain the concept of fade effect in jQuery?
1. In jQuery there are three different applications applying which we can avail the fade effect. 
 Fade effect can be availed by using the functions which are fadeIn, fadeOut and fadeTo.
2. The opacity of elements gets changed with animation through the effect of these methods.
The syntax for the fading effect includes
Syntax:
$(selector).fadeIn(speed,callback)
$(selector).fadeOut(speed,callback)
$(selector).fadeTo(speed,opacity,callback)
 “speed” this can be one among the following values: “slow”, “fast”, “normal” or milliseconds.
“opacity” this is used to specify the capacity of fading to give opacity.
“callback” it is the function with the help of which we can call an action upon the completion of fading. 
Q. Explain the Struts2 jQuery plug-in and its advantages.
The struts2 jQuery plug-in is used to:
* Easy integration of Ajax and widgets will be provided to the user.
 * The extent of coding needed to be done will be reduced.
For ex:
Result Div
Run AJAX Action
The advantages of using truts2 jQuery are:
1. It greatly reduces the extent of coding needed to be done for a particular action.
2. It also supports ajax form validation.
3. The readability levels of the code will be very high and so it will become much easier to perform the debugging. 
Q. Explain how the jQuery stores data related to an element?
Information of an element can be stored in the simple javascript by simply adding a domain object model property to the element. This results in the rising of issues such as leakage of memory in the browsers.
But in the case of jQuery the user does not need to be bothered by the memory management issues.
For ex : Storing and retrieving data related to an element:
$(‘#myDiv’).data(‘keyName’, { foo : ‘bar’ });
$(‘#myDiv’).data(‘keyName’); // { foo : ‘bar’ }
Q. Describe the procedure of extracting a query string with regular expressions?
The procedure of extracting a query string with regular expressions can be done in two ways.
1. Approach of String-based:
It is considered to be the simplest way in use for extracting a query string with regular expressions. This method is carried ahead by making the utilisation of the .replace() method to function.
For ex : 
var data = string.replace("http://localhost/view.php?", "");
The above procedure will be fine but it has some flexible issues. 
2. Regular expression approach:
This is the most powerful method for extracting a query string and the pattern must be used that seeks about the question mark among the string. When done, the JS regular expressions are delimited  
Q. Differentiate the concepts of .js and .min.js?
jQuery library has two different versions Development and Production. The other name for the deployment version is minified version. 
Considering the functionality, both the files they are much similar to each other. Being smaller in size, the  .min.js   gets loaded quickly saving the bandwidth.
Q. What is a CDN?
The term CDN relates to the concept of Content Delivery Network. In general, CDN can be interpreted as a large system of servers that are deployed in multiple data centers across the internet. 
CDN is mainly aimed at delivering the content to the end-users by enabling them to have high availability and high performance. 
Q. Explain the advantages of the CDN.
The benefits of CDN are quite effective in relation to the working functionality of the jQuery.
Some of the benefits of the CDN include
CDN greatly diminishes the load from your server.
* Saving the bandwidth CDN helps the jQuery to load faster than the usual time
* The most prominent feature of the CDN is that it if any user visits a website which is running on jQuery it caches it.
Q. What is an event?PreventDefault?
The event.preventDefault() method function is to stop the default action of an element from taking place  or to halt the default action from happening. 
Q. Differentiate onload() and document.ready().

The main differentiating factor of onload() and document.ready() is that
At max, a page supports the existence of only one onload function, & all the other onload functions will be getting terminated
While coming to the document.ready function, a page can have more than one document.ready function.

Also, the document.ready function is called when the DOM gets loaded and whereas the onload function gets called only when the DOM images get loaded on the page.

Q.  Why is jQuery better than JavaScript?
In general, jQuery is considered to be far better than the JavaScript. jQuery can be interpreted as an application for developing Ajax application and helps in simplifying the code & the code readability will also be good. 
jQuery also supports the creation of animations and delivers such high-level functionalities. 
Related Page: AngularJS Vs. JQuery
Q. Explain the types of selectors in jQuery?
There are three types of selectors in jQuery:
* CSS Selector
XPath Selector
* Custom Selector
Q. Explain the concept of Grouping?
The concept of grouping can simply be explained as whenever the same declaration gets shared by more than one selector they get separated by a common separated list. 
This helps in greatly reducing the size of the CSS and helps it in making it become more readable. 
Q. Explain the concept of finish method in jQuery?
In order to stop all the queued animations and to help them place in their final state the .finish() method is used. This method was introduced in jQuery 1.9.
Q. Differentiate between calling stop (true, true) and finish method?
The .finish() method will be quite similar to .stop(true, true). It helps in clearing the queue & thereby helps the animations to enter into their end state. In .finish() it also causes the CSS property of all queued animations to jump to their end values, as well.
Q. Which is the latest version of the jQuery library?
The latest version (when this post is written) of jQuery is 1.10.2 or 2.0.3. jQuery 2.x has the same API as jQuery 1.x but does not support Internet Explorer 6, 7, or 8.
Q. Explain the concept of writing the browser specific code using jQuery?
We can write browser specific code by simply making use of the jQuery.browser property. This property contains flags for the user agent, read from navigator.userAgent. 
This property was excluded from jQuery 1.9.
Q. What is the procedure to check the data type of any variable in jQuery?
 By using $.type(Object) which returns the built-in JavaScript type for the object.
Explain the width() vs css(‘width’) ?
We have 2 ways to change the width of the element.
One would be .width() & .css(‘width’)
Example:
$(‘#namediv’).width(100);

$(‘#namediv’).css(‘width’,’300px’);
  • The difference in both of them is the datatype we specify or return of both the functions.
  • In .width() we do not add pixel but in css.(‘width’) we need to add ‘px’.
  • If you want to get width of ‘namediv’ then .width() will give you only integer 300 where as in .css(‘width’) will give ‘300px’.
Difference between ‘new’ and $(new) in jQuery?
Example:
$(document).ready(function()

{

$(‘#button).click(function()

{

     alert($(new).text());

     alert(new.innerText);

});

});
new and $(new) refers to same element, the difference was that “new” used via traditional way but when “new” used with in $() it holds a jQuery object in which we use the functions with jQuery.
In the above example, if we use “new” than we use jQuery in  text() function whereas to get before the element, as it is not jQuery object. If the “new” is wrapped in $() w use jQuery function to text of the element.

Explain what is .empty() vs .detach() vs .remove() ?

The .empty() method likely to remove all child elements from matched ones.

The .remove() method likely to remove the matched elements with this you can remove all jQuery data associated to matched element.
The .detach() method likely the same as .remove() method none that the .detach() method cannot remove jQuery data linked with matched elements.

The .remove() is faster & quicker than .detach() or .empty() method.

Syntax:

$(selector).empty();

$(selector).detach();

$(selector).remove();

Why use jQuery?
Easy to learn.
Fast & extensible.
Performance of the application improves.
Provides cross-browser support in scripting.

How to check element is empty in jQuery?
Below is the code::
$(render).ready(function(){
if ($('#owncodelid’).is(':empty')){
//Code here for Empty element
}
});

Advantages of jQuery

Web developers usually use JavaScript to bring the required functionality to websites that they create. jQuery is one tool that offers a great deal of flexibility and power to web designers. This is a JavaScript library that aids in standardizing and simplifying interactions between HTML elements and JavaScript code. Read on to know the benefits of using jQuery instead of building your own library or writing raw JavaScript.
jQuery is widely used
jQuery is quite popular with website developers because of its simplicity and ease of use. You will get an endless list of resources and information about jQueryon the internet, for example, code snippets, blog posts, quality tutorials, documentation, and much more. With jQuery, you will never have a shortage of resources and you will always find whatever you need and have all your questions answered when working with this popular language.
Promotes simplicity
Most website developers find jQuery to be easy to learn and intuitive as the library is built using simpler and shorter codes. With its open coding standards and simple syntax, web designers can shorten the time that it takes to deploy a site or application. With jQuery, developers do not have to be expert web designers or programmers for them to come up with excellent styles for their websites. Web developers that have done some testing and coding of CSS files will appreciate the easy implementation of jQuery.
Cross-browser compatibility
One of the characteristic benefits of using jQuery is the fact that it deals with many cross-browser issues and bugs that you would experience while developing using JavaScript only. Handling a cross-browser web development problem can be quite a harrowing experience. This is because website design elements might work perfectly in one browser version and completely break down in another. With the jQuery library, most of these cross-browser issues have been dealt with. This means that you can develop a website that will work properly on all types of browsers and different versions, saving you from lots of headaches.
Clean and beautiful syntax
jQuery makes use of powerful, clean, and simple syntax that makes it easier to pick the DOM elements on the webpage that you want to change with JavaScript and enable you to chain effects and actions together for effective code. It is common to replace dozens or more JavaScript lines with one line of jQuery code. jQuery makes use of Cascading Style Sheets(CSS) version 3 for selecting elements, and this means that you do not have to learn a new syntax when using this language.
Lightweight and lean
To keep the jQuery library lean and lightweight, most functions have been omitted and others have been moved to the plug-in section. If you require any of these omitted features, you can easily add them to your website as plugins. The lean library keeps the coding at a restricted level and helps save on bandwidth to guarantee faster loading. The core jQuery library is just 24 kb, which is smaller than a photograph on most websites, and browser applications will only download and cache it once for use on all your webpages. The best Web design company New York has will use jQuery because of its many benefits.
Open source library
jQuery is an open source library that is free and supported well across different applications. This means that anyone can use this language in their applications without worrying about any licensing or compatibility issues. Further more, jQuery has been officially integrated into the IDE Visual Studio 2010 by Microsoft. Additionally, JQuery intelligence is now supported well in the Visual Studio 2010.
Animations and cool effects
Flash developers are quite costly and developing in Flash needs lots of experience and may take years of practice for one to come up with movie-like creations that make flash popular. Conversely, jQuery is free and only necessitates knowledge of HTML and JavaScript. JQuery utilizes a combination of CSS, AJAX, JavaScript, and HTML. These markup-based technologies have been designed to work perfectly together. As a result, you can use optimization strategy on your website without necessarily making special adjustments that technologies like Flash require. With jQuery, you can create great-looking effects and animations that will keep your target audience engaged.  
Highly extensible
The primary jQuery library is designed to be focused and kept tight, eliminating any non-essential features. However, a plugin framework is provided, making it easy to extend jQuery and this includes both official jQuery plugins and thousands of third-party plugins. This means that your page will only download the specific features that it requires. In case you need other features that are not included in the main library, then you can easily get superior quality downloads online.
Pages load faster
Search engines like Google use page load time as a key factor when ranking websites.  As a result, every web developer must strive to ensure that their code is concise and light as possible. jQuery files are usually stored separately from the webpage itself. This allows developers to make modifications to the entire website using one central repository rather than search through numerous folder structures.
SEO-friendly
The way that a developer codes a website can greatly affect the way it can be found on the search engines. jQuery can easily be optimized for the search engines and has lots of plug-ins that can help developers achieve this. One of the SEO-friendly practices that you can use is embedding jQuery elements using unordered lists.  
Utility features
JQuery provides utility functions that aid in coding string iteration, trimming, array manipulation, and many more features. These functions provide a seamless integration between JavaScript and jQuery. With these essential utility features, the code writing process will be hassle-free and easier.
It is important for website developers to learn jQuery because it is worth the effort, time, and money and is also a key component of HTML5. This library can offer stunning effects on your website, which will surely bring success. With little coding and more HTML5 integration, jQuery will be a big part of web development in the near future. jQuery has all the tools you need to build a website or web app that is interactive and highly engaging.

SelectorExampleSelects
*$(“*”)All elements
#id$(“#lastname”)The elements with id=lastname
.class$(“.intro”)All the elements with id=lastname
element$(“p”)All p elements
.class.class$(.intro.demo)All elements with the classes “intro” and “demo”
:first$(“p:first”)The first p element
:last$(“p:last”)The last p element
:even$(“tr.even”)All even tr elements
:odd$(“tr.odd”)Alll odd tr elements
:eq(index)$(“ulli:eq(3)”)The fourth element in list (index starts at 0)
:gt(no)$(“ulli:gt(3)”)list elements with an index greater than 3
:lt(no)$(“ulli:lt(3)”)list elements with an index less than 3
:not(selector)$(“input:not(:empty)”)All the inputs elements that are not empty.
:header$(“:header”)All header elements h1, h2….
:animated$(“:animated”)All animated elements
:contains(text)$(“:contains(‘W3Schools’)”)All elements which contains the text.
:empty$(“:empty”)All elements with no child (elements) nodes
:hidden$(“p:hidden”)All hidden p elements
:visible$(“table:visible”)All visible tables
s1,s2,s3$(“th,td,.intro”)All elements with matching selectors
[attribute]$(“[href]”)All element with a href attribute.
[attribute=valve]$(“[href=’default.htm’]”)All elements with a href attribute value equal to “default.htm”
[attribute!=value]$(“[href1=’default.htm’]”)All elements with a href attribute value not equal to “default.htm”
[attribute$=valve]$(“[href$=’.jpg’]”)All elements with a  href attribute value ending with “.jpg”
:input$(“.input”)All input elements
:text$(“.text”)All input elements with type=”text”
:password$(“:password”)All input elements with type=”password”
:radio$(“:radio”)All input elements with type =”radio”
:checkbox$(“:checkbox”)All input elements with type =”checkbox”
:submit$(“:submit”)All input elements with type=”submit”
:reset$(“:reset”)All input elements with type=”reset”
:button$(“:button”)All input elements with type=”button”
:image$(“:image”)All input elements with type=”image”
:file$(“:file”)All input elements with type=”file”
:enabled$(“:enabled”)All  enabled input elements
:disabled$(“:disabled”)All disabled input elements
:selected$(“:selected”)All selected input elements
:checked$(“:checked”)All selected input elements
Similar to above syntax and examples, following example would give you understanding on using different type of other useful selectors
$(‘*’)    2 This selector selects all elements in the document.
$(“p>*”)2 This selector selects all elements that are children of a paragraph element.
$(“#specialID”)2:This selector function gets the element with id=”specialID”.
$(“.specialClass”)2 This selector gets all the elements that have the class of specialClass.
$(“li:not(.myclass)”)2Selects all elements matchbody <li> that do not have class=”my class”.
$(“a#specialID.specialClass”)2This selector matches links with an id of specialID and a class of specialClass.
$(“p a.specialClass”)2 This selector matches links with a class of specialclass declared with in <p> elements.
$(“ulli:first”)2 This selector gets only the first <li> elementof the <ul>.
$(“container p”)2 Selects all elements matched by <p> that are descendants of an element that has an id of container.
$(“li>ul”)2Select all elements matched by <ul> that are children of an element matched by <li>
$(“strong+em”)2Selects all elements matched by <em> that immediately follow a sibling element matched by <strong>
$(“p~ul”) 2Selects all elements matched by <ul> that follow a sibling element matched by <p>.
$(“code, em, strong)2Selects all elements matched by <code> or <em>or <strong>.
$(“p strong ,.myclass”)2 Selects all elements matched by <strong> that are descendants of an element matched by <p> as well as all elements that have a class of myclass.
$(“.empty”)2 Selects all elements that have no children.
$(“p:empty”)2Selects all elements matched by <p> that have no children.
$(“div[p]”)2Selects all elements matched by <div> that contain an element matched by <p>
$(“p[.my class]”)2Selects all elements matched by <p> that contain an element with aclass of myclass.
$(“a[@rell]”)2Selects all elements matched by<a> that have a rel attribute.
$(“input[@name=myname]”)2Selects all elements matched by <input> that have a name value exactly equal to myname.
$(“input[@name^=myname]”)2Selects all elements matched by <input> that have a name value beginning with myname.
$(“a[@rel$=self]”)2Selects all elements matched by <p> that have a class value ending with bar.
$(“a[@href*=domain.com]”)2 Selects all elements matched by <a> that have an href value containing domain.com.
$(“li:even”)2Selects all elements matched by <li>that have an even index value.
$(“tr:odd”)2Selects all elements matched by <tr> that have an odd index value.
$(“li:first”)2Selects all the first<li> element.
$(“li:last”)2Selects all the last <li> element.
$(“li:visible”)2Selects all the element matched by<li> that are visible.
$(“li:hidden”)2Selects all elements matched by <li> that re hidden.
$(“:radio”)2Selects all radio buttons in the form.
$(“:checked”)2Selects all checked boxex in the form.
$(“:input”)2Selects only form elements (input, select, textarea, button).
$(“:text”)2 Selects only text elements(input[type=text]).
$(“li:eq(2)”)2 Selects the third <li> element.
$(“li:eq(4)”)2 Selects the fifth <li> element
$(“li:lt(2)”)2Selects all elements matched by <li> element before the third one; in other words, the first two <li> elements.
$(“p:lt(3)”)2Selects all elements matched by <p> elements before the fourth one; in other words the first three <p> elements.
$(“li:gt(1)”)2 Selects all elements matched by <li>after the second one.
$(“p:gt(2)”)2Selects all element matchen by <p> after the third one.
$(“div/p”)2 Selects all elements matched by <p> that are children of an element matched by<div>
$(“div//code”)2 Selects all elements matched by <code> that are descendants of an element matched by <div>.
$(“//p//a”)2Selects all elements matched by<a> that are descendants of an element matched by <p>
$(“li:first-child)”)2 Selects all elements matched by <li> that are the first child of their parent.
$(“li:last-child)”)2 Selects all elements matched by <li> that are the last child of their parent.
$(“:parent”)2Selects all elements that are the parent of another element ,including text.
$(“li:contains (second)”)2 Selects all elements matched by <li> that contain the text second.
You can use all the above selectors with any HTML/XML element in generic way .For example if selector $(“li:first”) works for <li> element then $ (“p:first”) would also work for <p> element.
hide(): $(selector).hide(speed, call back)
Example with Call back
$(“p”),hide(1000.function(){
alert(“The paragraph is now hidden”);
});
Without a callbackparameter, the alert box is displayed before the hide effect is completed.
Example without Call back
$(“p”),hide(1000);
alert(“The paragraph is now hidden”);
Useful Attribute Methods
Following table lists down few useful methods which you can use to manipulate attributes and properties:
MethodsDescription
attr(properties)Set a key /value object as properties to all matched elements.
attr(key,fn)Set a single property to a computes value, on all matched elements.
removeAttr(name)Remove an attribute from each of the matched elements.
hasclass(class)Returns true if the specified class is present on at least one of the set of matched elements.
removeClass(class)Removes all or the specified class(es) form the set of matched elements.
toggleClass(class)Adds the specified class if it is not present, removes the specified class if it is present.
html()Get the html contents (innerHTML) of the first matched element
html(val)Set the html contents of every of every matched element.
text()Get the combined text contents of all matched elements.
text(val)Set the text contents of all matched elements.
val()Get the input value of the first matched element
val(val)Set the attribute of every matched element if it is called on <input> but if it is called on <select>  with the passed <option> value then passed option would be selected, if it is called on check box or radio box then all the matching check box an d radiobox would be checked.
Similar to above syntax and examples, following examples give you understanding on using various attribute methods in different situation
$(“#myID”).attr(“custom”)        2 This would return value of attribute custom for the first element matching with ID myID.
$(“img”).attr(“alt”,”Sample Image”)  2 This sets the alt attribute of all the images to a new value “Sample Image”
$(“input”).attr({value:””,”Sample Image”);   2Sets the value of all <input> elements to the empty string, as well as sets the title to the string please enter a value.
$(“a[href^=http://]”).attr(“target”,”_blank”)    2 selects all links with an href attribute starting with http:// and set its target attribute to _blank
$(“a”).removeAttr(“target”)    2 This would remove target attribute of all the links.
$(“form”).submit(function() { $(“:submit”,this).attr(“disabled”,”disabled”);});   2 This would modify the disabled attribute to the value “disabled” while clicking submit button.
$(“p:last”).hasClass(“selected”)      2 This return true if last <p> tag has associated classselected.
$(“p”).text()  2 Returns string that contains the combined text contents of all matched<p> elements.
$(“p”).text(“<i>Hello World</i>”)   2 this would set “<i>Hello World</I> as text content of the matching <p> elements
$(“p”).html()    2 This returns the HTML content of the all matching paragraphs.
$(“div”).html(“Hello World”)      2 This would set the HTML Content of al matching <div> to Hello world.
$(“input:checkbox:checked”).val()     2Get the first value from a checked checkbox
$(“input:radio[name=bar]:checked”).val()   2Get the first value from a set of radio buttons
$(“button”).val(“Hello”)   2Sets the value attribute of every matched element <button>
$(“input”).val(“on”)       2 This would check all the radio or check box button whose value is “on”.
$(“select”).val(“Orange”)   2This would select Orange option in a dropdown box with options Orange, Mango and Banana.
$(“select”).val(“Orange”,”Mango”)  2 This would select orange and Mango options in a dropdown box with options Orange, Mango and Banana.

JQuery DOM Traversing Methods

Following table lists down useful methods which you can use to filter out various elements from a list of DOM elements:
SelectorDescription
eq(index)Reduce the set of matched elements to a single element.
tilter(selector)Removes all elements from the set of matched elements
that do not match the specified selector(s).
filter(fn)Removes all elements from the set of matched
elements that do not match the specified function.
is(selector)Checks the current selection against an expression and
returns true,if at least one element of the selection fits the given selector.
map(callback)Translate asset of elements in the jQuery object into another set
of values in a jQuery array(which may ,or may not contain elements).
not (selector)Removes elements matching the specified selector from the set of matched elements.
slice(start,[end])Selects a subset of the matched elements.
Following table lists down other useful methods which you can use to locate various elements in a DOM
SelectorDescription
add(selector)Adds more elements, matched by the given selector, to the set of matched elements.
andSelf()Add the previous selection to the current selection
children([selector])Get a set of elements containing all of the unique immediate children of each of the matched set of elements.
closest(selector)Get a set of elements containing the closest parent element that matches the specified selector, the starting element included.
contents()Find all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe.
end()Revert the most recent ‘destructive’ operation, changing the set of matched elements to its previous state.
find(selector)Searches for descendent elements that match the specified selectors.
next([selector])Get a set of elements containing the unique next siblings of each of the given set of elements.
nextAll([selector])Find all sibling elements after the current element.
offsetParent()Returns a jQuery collection with the positioned parent of the first matched element.
parent([selector])Get the direct parent of an element. If called on asset of elements, parent returns a set of their unique direct parent elements.
parents([selector])Get a set of elements containing the unique ancestors of the matched set of elements(except for the root element).
prev([selector])Get a set of elements containing the unique previous siblings of each of the matched set of elements.
prevAll([selector])Find all sibling elements in front of the current element.
siblings([selector])Get a set of elements containing all of the unique siblings of each of the matched set of elements.

size() vs length:
both works on object. whereas size would be slower as this is method and length is a property

DOM Manipulation Methods

Following table lists down all the methods which you can use to manipulate DOM elements
MethodDescription
after(content)Insert content after-each of the matched elements.
append(content)Append content to the inside of every matched element.
appendTo(selector)Append all of the matched elements to another, specified , set of elements
before(content)Insert content before each of the matched elements
clone(bool)Clone matched DOM elements and all their event handlers,
 and select the clones.
clone()Clone matched DOM elements and select the clones.
empty()Remove all child nodes from the set of matched elements.
html(val)Set the html contents of every matched element
html()Get the html contents(inner HTML) of the first matched element.
insertAfter(sector)Insert all of the matched elements after another, specified , set of elements.
insertBefore(selector)Insert all of the matched elements before another, specified, set of elements.
prepend(content)Prepend content to the inside of every matched element.
prependTo(selector)Prepend all of the matched elements to another, specified, set of elements.
remove(expr)Removes all matched elements from the DOM.
replaceAll(selector)Replaces the elements matched by the specified
selector with the matched elements.
replacewith(content)Replaces all matched elements with the specified HTML or DOM elements
text(val)Set the text contents of all matched elements.
text()Get the combined text contents of all matched elements.
wrap(elem)Wrap each matched element with the specified element.
wrap(elem)Wrap all the elements in the matched set into a single wrapper element.
wrapAll(html)Wrap all the elements in the matched set into a single wrapper element.
wrapinner(elem)Wrap the inner child contents of each matched element(including text nodes)
with a DOM element.
wrapinner(html)Wrap the inner child contents of each matched element
(including text nodes) with an HTML structure.
Jquery CSS Methods
Following table lists down all the methods which you can use to play with CSS properties
MethodDescription
css(name)Returns a style property on the first matched element.
css(name,value)Set a single style property to a value on all matched elements.
css(properties)Set a key/value object as style properties to all matched elements
height(val)Set the CSS height of every matched element
height()Get the current computed, pixel,height of the first matched element
innerHeight()Gets the inner height(excludes the border and includes the padding ) for the first matched element.
innerwidth()Gets the inner width(excludes the border and includes the padding) for the first matched element
offset()Get the current offset of the first matched element, in pixels, relative to the document
offsetParent()Returns a jQuery collection with the positioned parent of the first matched element
outerWidth([margin])Get the outer width(includes the border and padding by default) for the first matched element
position()Gets the top and left position of an element relative to its offset parent.
scrollLeft(val)When a value is passed in, the scroll left offset is set to that value on all matched elements.
scrollLeft()Gets the scroll left offset of the first matched element.
scrollTop(val)When a value is passed in, the scroll top offset is set to that value on all matched elements.
scrollTop()Gets the scroll top offset of the first matched element.
width(val)Set the CSS width of every matched element.
width()Get the current computed, pixel, width of the first matched element.
Event Type                        Description
blurOccurs when the element loses focus
changeOccurs when the element changes
clickOccurs when a mouse click
dbclickoccurs when a mouse double-click
errorOccurs when there is an error in loading or unloading etc.
focusOccurs when the element gets focus.
keydownOccurs when key is pressed
keypressOccurs when key is pressed and released.
keyupOccurs when key is released
loadOccurs when document is loaded
mousedownOccurs when mouse button is pressed
mouseenterOccurs when mouse enters in an element region
mouseleaveOccurs when mouse leaves an element region
mousemoveOccurs when mouse pointer moves
mouseoutOccurs when mouse pointer moves out of an element
mouseoverOccurs when mouse pointer moves over an element
mouseupOccurs when mouse button is released
resizeOccurs when window is resized
scrollOccurs when window is scrolled
selectoccurs when a text is selected
submitOccurs when form is submitted
unloadOccurs when documents is unloaded
The Event Object
The callback function takes a single parameter, when the handler is called the JavaScript event object will be passed through it.
The event object is often unnecessary and the parameter is omitted, as sufficient context is usually available when the handler is bound to know exactly what needs to be done when the handler is triggered. However there are certail attributes which you would need to be accessed.
The Event Attributes
The following event properties/attributes are available and safe to access in a platform independent manner.
Property                            Description
altkeySet to true if the Alt key was pressed when the event was triggered, false if not. The Alt key is labeled option on most Mac keyboards.
ctrlKeySet to true if the ctrl key was pressed when the event was triggered, false if not.
dataThe value, if any, passed as the second parameter to the blind() command when the handler was established.
keycodeFor keyup and keydown events, this returns the key that was pressed.
metakeySet to true if the Meta key was pressed when the event was triggered, false if not. The Meta key is the ctrl key on PCs and the command key on Macs.
pageXFor mouse events, specifies the horizontal coordinate of the event relative for the page origin
pageYFor mouse events, specifies the vertical coordinate of the event relative from the page origin.
relatedTargetFor some mouse events, identifies the element that the cursor left or entered when the event was triggered.
screenFor mouse events, specifies the horizontal coordinate of the event relative from the screen origin.
screen YFor mouse events, specifies the vertical coordinate of the event relative from the screen origin
shiftkeyset to true if the shift key was pressed when the event was triggered , false if not.
targetIdentifies the elment for which the event was triggered.
timestampThe timestamp(in milliseconds) when the event was created.
typeFor all events, specifies the type of event that was triggered(for example,click)
whichFor keyboard events, specifies the numeric code for the key that caused the event, and for mouse event, specifies which button was pressed (1 for left,2 for middle, 3 for right)

Binding Methods in jQuery

Following is an example which would bind a click event on all the <div>:
$(“div”).click(function()) {
// do something here
{);
Here is a complete list of all the support methods provided by jQuery
MethodDescription
blur()Triggers the blur event of each matched element.
blur(fn)Bind a function to the blur event of each matched element.
change()Triggers the change event of each matched element.
change(fn)Binds a function to the change event of each matched element.
click()Triggers the click event of each matched element.
click(fn)Binds a function to the click event of each matched element.
dbclick()Triggers the dbclick event of each matched element.
error()Triggers the error event of each matched element.
error(fn)Binds a function to the error event of each matched element.
focus()Triggers the focus event of each matched element.
focus(fn)Binds a function to the focus event of each of each matched element
keydown()Triggers the keydown event of each matched element.
keydown(fn)Bind a function to the keydown event of each matched element.
Keypress()Triggers the keypress event of each matched element.
keypress(fn)Binds a function to the keypress event of each matched element.
keyup()Triggers the keyup event of each matched element.
keyup(fn)Bind a function to the keyup event of each matched element.
load(fn)Binds a function to the load event of each matched element.
mouseenter(fn)Bind a function to the mouseenter event of each matched element.
mouseleave(fn)Bind a function to the mouseleave event of each matched element.
mousemove(fn)Bind a function to the mousemove event of each matched element.
mouseout(fn)Bind a function to the mouseout event of each matched element
mouseover(fn)Bind a function to the mouseover event of each matched element.
mouseup(fn)Bind a function to the mouseup event of each matched element.
resize(fn)Bind a function to the resize event of each matched element.
scroll(fn)Bind a function to the scroll event of each matched element.
select()Trigger the select event of each matched element
select(fn)Bind a function to the select event of each matched element.
submit()Trigger the submit event of each matched element.
submit(fn)Bind a function to the submit event of each matched element
unload(fn)Binds a function to the unload event of each matched element.

jQuery Slide – slideDown , slide Up, slideToggle

The jQuery slide methods gradually change the height for selected elements.
jQuery has the following slide methods :
$(selector).slideDown(speed,callback)
$(selector).slideUp(speed,callback)
$(selector).slideToggle(spped,callback)
The speed parameter can take the following values” “slow” , “fast”, “normal”, or milliseconds.
The callback parameter is the name of a function to be executed after the function completes.

jQuery Fade – fadeIn, fadeout, fadeTo

The jQuery fade methods gradually change the opacity for selected elements.
jQuery has the following fade methods
$(selector).fadeIn(speed,callback)
$(selector).fadeOut(speed,callback)
$(selector).fadeTo(speed,opticity,callback)
The speed parameter can take the following values : “slow”, “fast”, “normal”, or milliseconds.
The opacity parameter in the fadeTo() method allows fading a given opacity.
The callback parameter is the name of a function to be executed after the function completes.

jQuery Methods

animate(params,[duration,easing,callback])
A function for making custom animations.
fadein(speed,[callback])
Fade in all matched elements by adjusting their opacity and firing an optional call-back after completion.
fadeout(speed,[call-back])
Fade out all matched elements by adjusting their opacity to 0, then setting to “none” and firing an optional call-back after completion.
fadeTo(speed,opacity,callback)
Fade the opacity of all matched elements to a specified opacity and firing an optional call-back after completion.
hide()                  
Hides each of the set of matched elements if they are shown.
hide(speed.[call back])
Hide all matched elements using a graceful animation and firing an optional call-back after completion.
Show()
Displays each of the set of matched elements if they are hidden.
show(speed,[call back])
Show all matched elements using a graceful animation and firing an optional callback after completion.
slideDown(speed,[callback])
Reveal all matched elements by adjusting their height and firing an optional call back after completion.
slideToggle(speed,[call back])
Toggle the visibility of all matched elements by adjusting their height  and firing an optional call-back after completion.
slideUp(speed,[call-back])
Hide all matched elements by adjusting their height and firing an optional call back after completion.
stop([clearQueue,gotoEnd])
Stops all the currently running animations on all the specified elements.
toggle()
Toggle displaying each of the set of matched elements.

toggle(speed,[callback])
Toggle displaying each of the set of matched elements using a graceful animation and firing an optional call back after completion.
toggle(switch)
Toggle displaying each of the set of matched elements based upon the switch(true shows all elements , false hides all elements)
jQuery.fx.off
Globally disable all animations.
jQuery – Ajax
Ajax is an acronym standing for Asynchronous JavaScript and XML and this technology help us to load data from the server without a browser page refresh.
jQuery is a great tool which provides a rich set of AJAX methods to develop next generation web application.

jQuery AJAX Methods

You have seen basic concept of AJAX using jQuery. Following table lists down all important jQuery AJAX methods which you can based your programming need:
Methods and Description
jQuery.ajax{options}
load a remote page using an HTTP request.
jQuery.ajaxSetup{options}
Set up global settings for AJAX requests.
jQuery.ger{url,[data],[callback],[type]}
Load a remote page using an HTTP GET request.
jQuert.getJson{url,[data],[callback]}
Load JSON data using an HTTP GET request.
jQuery.getScript{url,{callback}]
Loads and executes aJava Script file using anHTTP GET request.
jQuery.post{url,[data].[callback],[type]}
Load  a  remote page using anHTTP POST request.
Load{url,[data][callback]}
Load a HTML from a remote file and inject it inot the DOM.
Serialize{}
Serializes a set of input elements into a string of data.
SerializeArray{}
Serializes all forms and form elements like the .serialize{} method but returns a JSON data structure for you to work with.

jQuery AJAX Events

You can call various jQuery methods during the life cycle of AJAX call progress. Based on different events/stages following methods are available:
You can go through all the AJAX Events

Methods and Description

ajaxComplete{callback}
Attach a function to be executed whenever an AJAX request completes.
ajaxStart{call back}
Attach a function to be executed whenever an AJAX request begins and there is none alreadyactive.
Ajax Error{callback}
Attach afunction to be executed whenever an AJAX request fails.
ajaxSend{callback}
Attach a function to be executed before an AJAX request is sent.
ajaxStop{callback}
Attach a function to be executed whenver all AJAX requests have ended.
ajaxSucess{call-back}
Attach a function to be executed whenever an AJAX request completes successfully.




No comments:

Post a Comment