How to use jquery.cookies.js

Without jQuery

If jQuery is not available in your page, the core cookies library is available to you under the jaaulde.utils namespace:

Get a cookie

/**
 * get - get one, several, or all cookies
 *
 * @access public
 * @paramater Mixed cookieName - String:name of single cookie; Array:list of multiple cookie names; Void (no param):if you want all cookies
 * @return Mixed - Value of cookie as set; Null:if only one cookie is requested and is not found; Object:hash of multiple or all cookies (if multiple or all requested);
 */
get = function(cookieName)

Example:

  • jaaulde.utils.cookies.get('myCookie');
    • returns value of myCookie if it is present, null if not
  • jaaulde.utils.cookies.get(['myCookie', 'myOtherCookie']);
    • returns array containing value of each requested cookie if it is present, null if not
  • jaaulde.utils.cookies.get();
    • returns array of all cookies from your site

Get Filtered list of cookies

/**
 * filter - get array of cookies whose names match the provided RegExp
 *
 * @access public
 * @paramater Object RegExp - The regular expression to match against cookie names
 * @return Mixed - Object:hash of cookies whose names match the RegExp
 */
filter = function( cookieNameRegExp )

Example:

  • jaaulde.utils.cookies.filter( /^site/ );
    • returns list of cookies whose names start with “site”

Set a cookie

/**
 * set - set or delete a cookie with desired options
 *
 * @access public
 * @paramater String cookieName - name of cookie to set
 * @paramater Mixed value - Any JS value. If not a string, will be JSON encoded (http://code.google.com/p/cookies/wiki/JSON); NULL to delete
 * @paramater Object options - optional list of cookie options to specify
 * @return void
 */
set = function(cookieName, value, options)

Example:

  • jaaulde.utils.cookies.set('myCookie', 'myValue');
    • sets cookie by the name of ‘myCookie’ to value of ‘myValue’ with default options
  • jaaulde.utils.cookies.set('myCookie', 'myValue', {path: '/somedir'});
    • sets cookie by the name of ‘myCookie’ to value of ‘myValue’ with path of ‘/somedir’
  • See information on options object below

Delete a cookie

/**
 * del - delete a cookie (domain and path options must match those with which the cookie was set; this is really an alias for set() with parameters simplified for this use)
 *
 * @access public
 * @paramater MIxed cookieName - String name of cookie to delete, or Bool true to delete all
 * @paramater Object options - optional list of cookie options to specify ( path, domain )
 * @return void
 */
del = function(cookieName, options)

Example:

  • jaaulde.utils.cookies.del('myCookie');
    • deletes a cookie, ‘myCookie’, with default options
  • jaaulde.utils.cookies.del('myCookie', {path: '/somedir'});
    • deletes a cookie by the name of ‘myCookie’ which had been set with a path of ‘/somedir’
  • jaaulde.utils.cookies.del(true);
    • deletes all cookies
  • A cookie can only be deleted using the same options with which it was set
  • See information on options object below

Test if browser is accepting cookies

/**
 * test - test whether the browser is accepting cookies
 *
 * @access public
 * @return Boolean
 */
test = function()

Example:

  • jaaulde.utils.cookies.test();
    • attempts to set a cookie and returns true or false upon success or failure

Set default options to use when none are specified

/**
 * setOptions - set default options for calls to cookie methods
 *
 * @access public
 * @param Object options - list of cookie options to specify
 * @return void
 */
setOptions = function(options)

Example:

  • jaaulde.utils.cookies.setOptions({path: '/somedir'});
    • all cookies will be set or deleted with the path , ‘/somedir’, unless it is explicitly provided in a passed options object
  • See information on options object below

With jQuery

If jQuery is available, then all of the above methods are available to you under the jQuery.cookies (or $.cookies ) namespace:

  • $.cookies.get()
  • $.cookies.filter()
  • $.cookies.set()
  • $.cookies.del()
  • $.cookies.test()
  • $.cookies.setOptions()

In addition, there are some jQuery function additions for helping automate some cookie tasks:

  • Set the value of a form field or the HTML of an element to a cookie named after the field’s/element’s name or id attribute
    • $('#username').cookify();
      • The value of the field, or HTML of the element, with id “username” is set to a cookie named after the name or id attribute of that field/element. If a radio or checkbox and it’s checked, the value will be set.
  • Fill a field’s value, or an element’s innerHTML with the value of a cookie
    • $('#username').cookieFill();
      • Set the value of the input, or HTML of the element, with id, ‘username’, to the value of a cookie by the same name. If a radio or checkbox and it is checked, the cookie will be set. If not checked, the cookie will be deleted.
  • Bind an input to the cookies library
    • $('#username').cookieBind();
      • Fills the field or element with id, ‘username’, with the cookie named the same and sets the field’s/element’s change event to fire cookify() to update the cookie when the input value changes

Options object

Using the options object, cookies can be set with several options such as the domain and or path for which the cookie should be available, expiration date for the cookie, and whether the cookie should be sent over HTTPS only.

The options object has four properties:

  • domain
    • STRING
    • For which domain should the cookie be available
  • path
    • STRING
    • For which path should the cookie be available
  • hoursToLive (DEPRECATED for expiresAt)
    • NUMBER
    • For how many hours should the cookie be valid? (Passing 0 means to delete the cookie at the end of the browser session–this is default. Negative values will delete the cookie, but you should use the del() method instead.)
  • expiresAt
    • Date OBJECT
    • Date object representing expiration date/time of cookie
  • secure
    • BOOL
    • Should cookie be sent to server via HTTPS only?

The structure of the object is as follows:

  var newOptions = {
    domain: '*.mydomain.com',
    path: '/somedir',
    expiresAt: new Date( 2011, 1, 1 ),
    secure: true
  }

You need only set those options which you desire to override.

The default options when not overridden are:

  • domain
    • no value – will cause current domain of current page to be used
  • path
    • /
  • expiration
    • no value–causes cookie to be deleted at end of browser session
  • secure (send over HTTPS only)
    • false

An options object can be passed with set(), del(), cookify(), and cookieBind() to override the defaults on a case by case basis. You can also pass an options object to setOptions() to override the defaults for all calls.

IMPORTANT NOTE: Cookies must be deleted using the same domain and path options with which they were set. Else the cookie will not delete. This is just how cookies work.

RESTful Web Service with jQuery

This guide walks you through writing a simple jQuery client that consumes a Spring MVC-based RESTful web service.

What you will build

You will build a jQuery client that consumes a Spring-based RESTful web service. Specifically, the client will consume the service created in Building a RESTful Web Service with CORS.

The jQuery client will be accessed by opening the index.html file in your browser, and will consume the service accepting requests at:

http://rest-service.guides.spring.io/greeting

The service will respond with a JSON representation of a greeting:

{"id":1,"content":"Hello, World!"}

The jQuery client will render the ID and content into the DOM.

What you will need

  • About 15 minutes
  • A favorite text editor
  • A modern web browser
  • An internet connection

Create a jQuery Controller

First, you will create the jQuery controller module that will consume the REST service:

public/hello.js

$(document).ready(function() {
    $.ajax({
        url: "http://rest-service.guides.spring.io/greeting"
    }).then(function(data) {
       $('.greeting-id').append(data.id);
       $('.greeting-content').append(data.content);
    });
});

This controller module is represented as a simple JavaScript function. It uses jQuery’s $.ajax() method to consume the REST service at http://rest-service.guides.spring.io/greeting. If successful, it will assign the JSON received to data, effectively making it a Greeting model object. The id and content are then appended to the greeting-id and greeting-content DOM elements respectively.

Note the use of the jQuery promise .then(). This directs jQuery to execute the anonymous function when the $.ajax() method completes, passing the data result from the completed AJAX request.

Create the Application Page

Now that you have a jQuery controller, you will create the HTML page that will load the client into the user’s web browser:

public/index.html

<!DOCTYPE html>
<html>
    <head>
        <title>Hello jQuery</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="hello.js"></script>
    </head>

    <body>
        <div>
            <p class="greeting-id">The ID is </p>
            <p class="greeting-content">The content is </p>
        </div>
    </body>
</html>

Note the following two script tags within the <head> section.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="hello.js"></script>

The first script tag loads the minified jQuery library (jquery.min.js) from a content delivery network (CDN) so that you don’t have to download jQuery and place it in your project. It also loads the controller code (hello.js) from the application’s path.

Also note that the <p> tags include class attributes.

<p class="greeting-id">The ID is </p>
<p class="greeting-content">The content is </p>

These class attributes help jQuery to reference the HTML elements and update the text with the values from the id and content properties of the JSON received from the REST service.

Run the client

To run the client, you’ll need to serve it from a web server to your browser. The Spring Boot CLI (Command Line Interface) includes an embedded Tomcat server, which offers a simple approach to serving web content. See Building an Application with Spring Boot for more information about installing and using the CLI.

In order to serve static content from Spring Boot’s embedded Tomcat server, you’ll also need to create a minimal amount of web application code so that Spring Boot knows to start Tomcat. The following app.groovy script is sufficient for letting Spring Boot know that you want to run Tomcat:

app.groovy

@Controller class JsApp { }

You can now run the app using the Spring Boot CLI:

spring run app.groovy

Once the app starts, open http://localhost:8080 in your browser, where you see:

Model data retrieved from the REST service is rendered into the DOM.

The ID value will increment each time you refresh the page.

Summary

Congratulations! You’ve just developed a jQuery client that consumes a Spring-based RESTful web service.

JavaScript Patterns Collection

JS Patterns

A JavaScript pattern and antipattern collection that covers function patterns, jQuery patterns, jQuery plugin patterns, design patterns, general patterns, literals and constructor patterns, object creation patterns, code reuse patterns, DOM and browser patterns (upcoming).

General Patterns

jQuery Patterns

  • requery – avoid requery by using jQuery chaining
  • append – use string concatenate and set innerHTML
  • data – pattern and antipattern of using data
  • context and find – use find over context
  • detach – take element off the DOM while manipulating them
  • event delegation – event delegation pattern and antipattern
  • selector cache – using selector cache to avoid requery
  • window scroll event – avoid attaching handlers to the window scroll event

Selector

Publish–subscribe

  • Method 1 – custom events using .on() and .off()
  • Method 2 – using jQuery 1.7’s $.Callbacks() feature
  • Method 3 – using jQuery UI $.Observable
  • Method 4 – third-party plugins

jQuery Plugin Patterns

Literals and Constructors Patterns

  • Object literal – use the simpler and reliable object literal instead of new Object();
  • Enforcing new – when you forget `new`, `this` inside the constructor will point to the global object
  • Array literal – use array literal notation to avoid potential errors when creating dynamic arrays at runtime
  • Working with JSON – use library from JSON.org, YUI, jQuery instead of eval for parsing
  • Primitive wrappers – try to use the primitive without wrapper
  • Regular expression literal – try to use the shorter literal notation

Function Patterns

API Patterns

  • Callback patterns – when you pass function A to function B as a parameter, function A is a callback function
  • Configuration objects – keep control of function arguments and makes it easily configurable
  • Returning functions – one function returns another function or create another function on-demand
  • Currying – used to create new functions dynamically by partially applying a set of arguments
  • Partial application – the process of fixing a number of arguments to a function, producing another function of smaller arity

Initialization patterns

Performance patterns

  • Memoization – use function properties to avoid repeated computation
  • Self-defining functions – self-overwrite with new bodies to do less work from the second invocation and after

Object Creation Patterns

  • Namespace – namespaces help reduce the number of globals required and avoid naming collisions or excessive name prefixing
  • Declaring Dependencies – it’s good to declare the modules your code relies on at the top
  • Private Properties and Methods – JavaScript doesn’t have special syntax for private members, you can implement them using a closure
  • Revelation Pattern – it is about having private methods, which you also expose as public methods
  • Module Pattern – all the methods are kept private and you only expose those that you decide at the end
  • Sandbox – it provides an environment for the modules to work without affecting other modules and their personal sandboxes
  • Static Members – public and private static members
  • Object Constants – an implementation of a contant object provides set, inDefined and get methods
  • Chaining Pattern – it enables you to call methods on an object one after the other
  • method() Method – adding convenient funcationality to a language

Code Reuse Patterns

Classical Patterns (patterns that should generally be avoided)

  • The default pattern – create an object using the Parent() constructor and assign this object to the Child()’s prototype
  • Rent a constructor – it borrows the parent constructor, passing the child object to be bound to this and also forwarding any arguments
  • Rent and Set Prototype – restricts object creation for a class to only one instance
  • Share the Prototype – restricts object creation for a class to only one instance
  • A Temporary Constructor – first borrow the constructor and then also set the child’s prototype to point to a new instance of the constructor
  • Klass – generally a pattern that should be avoided unless one is more comfortable with class than prototype

Preferred Patterns

Design Patterns

Creational

  • Builder – constructs complex objects by separating construction and representation
  • Factory method – creates objects without specifying the exact class to create
  • Singleton – restricts object creation for a class to only one instance

Structural

  • Decorator – dynamically adds/overrides behaviour in an existing method of an object
  • Facade – provides a simplified interface to a large body of code
  • Proxy – provides a placeholder for another object to control access, reduce cost, and reduce complexity

Behavioral

  • Chain of responsibility – delegates commands to a chain of processing objects
  • Command – creates objects which encapsulate actions and parameters
  • Iterator – implements a specialized language
  • Mediator – allows loose coupling between classes by being the only class that has detailed knowledge of their methods
  • Observer – is a publish/subscribe pattern which allows a number of observer objects to see an event
  • Strategy – allows one of a family of algorithms to be selected on-the-fly at runtime

Advantages of using pure JavaScript over JQuery

First off – it’s impossible to use jQuery only, all jQuery does is add a $ object to your global scope, with a bunch of methods in it. Even more manipulative libraries like prototype aren’t an alternative to javascript, they’re a toolbelt to solve common problems.

The main advantages to adding jQuery to your toolbelt would be:

  • browser compatibility – doing something like .attr() is much easier than the native alternatives, and won’t break across browsers.
  • simplification of usually complicated operations – if you’d like to see a well written cross browser compatible version of an XHR method, take a look at the source for $.ajax – for this method alone it’s almost worth the overhead of jQ.
  • DOM selection – simple things like binding events & selecting DOM elements can be complicated and differ per-browser. Without a lot of knowledge, they can also be easily written poorly and slow down your page.
  • Access to future features – things like .indexOf and .bind are native javascript, but not yet supported by many browsers. However, using the jQuery versions of these methods will allow you to support them cross browser.

Javascript is no longer just a client side language, and because jQuery is so DOM dependent, it is a terrible candidate to move to the server. I highly recommend putting some time into understanding why you are using jQuery (asking this question is a great first step!), and evaluating when it is necessary. jQuery can be dangerous, a few of the main dangers are:

  • code quality – jQuery has a huge community and a low learning curve. This is a perfect storm for lots of poorly written open source plugins.
  • inefficiency – jQuery is easy to write inefficiently. For instance, using jQuery’s each instead of for loops is unnecessary and could have a performance impact in some cases. Lots of good info about this stuff at JSPerf
  • bloat – jQuery is a huge library. Much of the time, you’ll use a small subset of it’s features, and grab the whole library. There are some great alternatives that will give you subsets of the features, like zepto.js, and underscore.js – depending on your situation, you can save some bytes by choosing the right library for your needs.

Ultimately, jQuery is an incredibly useful and helpful library, when used properly. However, it is not an alternative to javascript. It is a library, just like zepto.js, YUI, Dojo, MooTools, and Prototype – one of which may be a much better choice for your current project.

Javascript is a misunderstood language, and is only recently being regarded as something more than a scripting language by most people. I really recommend reading up on it more, here’s a few good places to start:

  • Ben Alman’s blog – lots of good best practices here. I don’t agree with all of the, but I learn new things from his blog all the time.
  • Code Academy – basic javascript training. No jQuery here. Sometimes going back to basics helps.
  • Javascript Garden – a post regarding the more tricky or misunderstood features of javascript. Please read this from time to time, until everything makes sense.
  • Bocoup – these are training classes. If you’re near one, go to it. Many of the best JS speakers and teachers teach these.
  • Paul Irish’s blog – not strictly JS, but plenty of best practices are written about here. Him and Ben’s twitter feeds are both great to follow.

I’m sure there’s lots more great resources I’m not thinking of or don’t know about, other answerers should feel free to add to that list.

Difference between event.preventDefault(), event.stopPropagation() and return false in jquery

Let me start by stating the behavior of all three when used in jquery event handling:

event.preventDefault(): Prevents the default action of the event from triggering. Does not stop the event propagation to parent DOM elements.
event.stopPropagation(): Prevents the default action of the event from propagating to parent DOM elements.
return false: Does what both of the above methods can do.

Let’s try to understand with examples:

Example 1:
<div onclick='executeParent()'>
<a href='http://google.com'>Click here to visit google.com</a>
</div>
<script>
$('a').click(function(event) {
$('a').text('Click event is going to execute');
$('a').contents().unwrap();
});
function executeParent() {
alert('here');
}
</script>

If you execute the code above, first you will get the javascript alert as the parent div calls the executeParent() javascript function. Next you will see the hyperlink ‘Click here to visit google.com‘ replaced by the text ‘Click event is going to execute‘ and immediately you will be redirected to google.com.

Example 2:
<div onclick='executeParent()'>
<a href='http://google.com'>Click here to visit google.com</a>
</div>
<script>
$('a').click(function(event) {
event.preventDefault();
$('a').text('Click event prevented');
$('a').contents().unwrap();
});
function executeParent() {
alert('here');
}
</script>

If you execute the code above, first you will get the javascript alert as the parent div calls the executeParent() javascript function. Next you will see the hyperlink ‘Click here to visit google.com‘ replaced by the text ‘Click event prevented‘ and you will not be redirected to google.com. This is due to event.preventDefault() method we used to prevent the default click action to be triggered.

Example 3:
<div onclick='executeParent()'>
<a href='http://google.com'>Click here to visit google.com</a>
</div>
<script>
$('a').click(function(event) {
event.stopPropagation();
$('a').text('Click event is going to be executed');
$('a').contents().unwrap();
});
function executeParent() {
alert('here');
}
</script>

If you execute the code above, the function executeParent() will not be called and you will not get the javascript alert this time. This is due to us having prevented the propagation to the parent div using event.stopPropagation() method. Next you will see the hyperlink ‘Click here to visit google.com‘ replaced by the text ‘Click event is going to be executed‘ and immediately you will be redirected to google.com. This is because we haven’t prevented the default click action from triggering this time using event.preventDefault() method.

Example 4:
<div onclick='executeParent()'>
<a href='http://google.com'>Click here to visit google.com</a>
</div>
<script>
$('a').click(function(event) {
event.preventDefault();
event.stopPropagation();
$('a').text('Click event prevented');
$('a').contents().unwrap();
});
function executeParent() {
alert('here');
}
</script>

If you execute the code above, the function executeParent() will not be called and you will not get the javascript alert. This is due to us having prevented the propagation to the parent div using event.stopPropagation() method. Next you will see the hyperlink ‘Click here to visit google.com‘ replaced by the text ‘Click event prevented‘ and you will not be redirected to google.com. This is because we have prevented the default click action from triggering this time using event.preventDefault() method.

Example 5:
<div onclick='executeParent()'>
<a href='http://google.com'>Click here to visit google.com</a>
</div>
<script>
$('a').click(function(event) {
$('a').text('Click event prevented');
$('a').contents().unwrap();
return false;
});
function executeParent() {
alert('here');
}
</script>

If you execute the code above, you will get the exact same results as example 4. This due to return false statement doing the job of both event.preventDefault() and event.stopPropagation() methods.

Hope these examples are clear. Try executing all these examples in a html file to see how they work.

Reference – Talkora

Javascript Event Bubbling

The concept of “bubbling up” is like if you have a child element with a click event and you don’t want it to trigger the click event of the parent. You could use event.stopPropagation().

event.stopPropagation() basically says only apply this click event to THIS CHILD NODE and don’t tell the parent containers anything because I don’t want them to react.

Event Capturing:

               | |
---------------| |-----------------
| element1     | |                |
|   -----------| |-----------     |
|   |element2  \ /          |     |
|   -------------------------     |
|        Event CAPTURING          |
-----------------------------------

Event Bubbling:

               / \
---------------| |-----------------
| element1     | |                |
|   -----------| |-----------     |
|   |element2  | |          |     |
|   -------------------------     |
|        Event BUBBLING           |
-----------------------------------

If you are using live() or delegate() you will need to return false;, though it may not work.

Some more explanation:

Event Bubbling

In JavaScript, events bubble. This means that an event propagates through the ancestors of the element the event fired on. Lets show what this means using the HTML markup below;

<div>
    <h1>
        <a href="#">
            <span>Hello</span>
        </a>
    </h1>
</div>

Lets assume we click the span, which causes a click event to be fired on the span; nothing revolutionary so far. However, the event then propagates (or bubbles) to the parent of the span (the <a>), and a click event is fired on that. This process repeats for the next parent (or ancestor) up to the document element.

You can see this in action here. Click “Hello” and see the events as they get fired.

That’s all event bubbling is; an event fired on an element bubbles through its ancestor chain (i.e. the event is also fired on those elements). It’s important to note that this isn’t a jQuery feature, nor is it something that a developer must turn on; it’s a fundamental part of JavaScript that has always existed.

Ok, that’s a little bit of a lie… sort of.

By default, not all events bubble. For instance submit does not normally bubble, nor does change. However, jQuery masks this in the event handling code using all sorts of voodoo, so it will seem that they do bubble when using jQuery.

jQuery .end() explanation & examples

jQuery’s .end() method is one of the most rarely used methods that I know of. In this post I would like share remind you what it does and how we can use it to make our jQuery code more readable.

Firstly, what does it do?

Put simply .end() cancels the last filtering action and returns a set like it was before the filtering was applied. It’s best explained with an example. Consider we have this HTML code:

<ul>
  <li>One</li>
  <li>Two</li>
  <li class="special">>Three</li>
</ul>
$('li')  // would have all 3 elements

$('li').filter('.special')  // would have 1 (third) element only

$('li').filter('.special').end()  // would have all 3 elements again

Now, the main question: Why on earth would you need it?! It is actually very useful when you have to apply different methods on several sub-selections in your DOM. The game development fits this case perfectly. I have seen beautiful and easy to understand game code that was made possible by a combination of custom jQuery selectors, extending jQuery and .end() method.

Couple of examples

To give you an idea of what a code of some hypothetical game might look like:

check_mines = function(from, to_coord){  // don't pay attention to this building block
     $("#game-canvas")

          .find("div:ships")
               .moveElements(from, to_coord)
          .end()

          .find("div:mines")
               .killIfClose(to_coord)
          .end()

          .find("div:healthPack")
               .addHealthIfClose(to_coord)
               .markHealthPackUsed(to_coord)
          .end();

};
SomeGame.register(check_mines);  // don't pay attention to this building block

As you can see, .end() helps us group related actions and make the code more readable.

Let’s consider more realistic case. Let’s say we have an article with images, links etc. (eg. Wikipedia articles). We need to add .content-img class to all images, than add .external-link to all external links, and finally apply a tooltip plugin to all the links that have .tooltip class within the article.

<div class="article">
     <p>Text ... </p>
     ...
</div>
$(".article")

    .find("img")
        .addClass("content-image")
    .end()  // back to .article set

    .find("a:external")
        .addClass("external-link")
    .end() // back to .article set

    .find("a.tooltip")
        .tooltip()
    .end(); // don't really need it here, but nice to have for symmetry

The above case is better written in 3 separate lines of codes of course, but it here to help explain the purpose of the .end().

NOTE:
If you do several filtering, you must call .end() several times as well.

$(".article").find("a").filter(".tooltip").end().end();

Hope you will find useful cases for .end() in your projects.

jQAPI-The faster way to browse the jQuery documentation

jqapi

jQAPI – Alternative jQuery Documentation Browser

The faster way to browse the jQuery documentation.

The aim of this project is to get out of the way of your development work. Quickly switch to this docs and find what you are looking for.

Furthermore you can download this documentation and browse it offline. In the future you don’t even need to download it to have it available offline.

Check it for more information – jQAPI

jwerty – Awesome handling of keyboard events

jwerty is a JS lib which allows you to bind, fire and assert key combination strings against elements and events. It normalises the poor std api into something easy to use and clear.

jwerty is a small library, weighing in at around 1.5kb bytes minified and gzipped (~3kb minified). jwerty has no dependencies, but is compatible with jQuery, Zepto or Ender if you include those packages alongside it.

The Short version

Use jwerty.key to bind your callback to a key combo (global shortcuts)

jwerty.key('ctrl+shift+P', function () { [...] });
jwerty.key('⌃+⇧+P', function () { [...] });

Specify optional keys:

jwerty.key('⌃+⇧+P/⌘+⇧+P', function () { [...] });

or key sequences:

jwerty.key('↑,↑,↓,↓,←,→,←,→,B,A,↩', function () { [...] });

You can also (since 0.3) specify regex-like ranges:

jwerty.key('ctrl+[a-c]', function () { [...] }); // fires for ctrl+a,ctrl+b or ctrl+c

Pass in a context to bind your callback:

jwerty.key('⌃+⇧+P/⌘+⇧+P', function () { [...] }, this);

Pass in a selector to bind a shortcut local to that element:

jwerty.key('⌃+⇧+P/⌘+⇧+P', function () { [...] }, this, '#myinput');

Pass in a selector’s context, similar to jQuery’s $(‘selector’, ‘scope’):

jwerty.key('⌃+⇧+P/⌘+⇧+P', function () { [...] }, this, 'input.email', '#myForm');

If you’re binding to a selector and don’t need the context, you can ommit it:

jwerty.key('⌃+⇧+P/⌘+⇧+P', function () { [...] }, 'input.email', '#myForm');

Use jwerty.event as a decorator, to bind events your own way:

$('#myinput').bind('keydown', jwerty.event('⌃+⇧+P/⌘+⇧+P', function () { [...] }));

Use jwerty.is to check a keyCombo against a keyboard event:

function (event) {
    if ( jwerty.is('⌃+⇧+P', event) ) {
        [...]
    }
}

Or use jwerty.fire to send keyboard events to other places:

jwerty.fire('enter', 'input:first-child', '#myForm');

Please visit – J w e r t y v

80 jQuery interview questions and answers

80jQuery

Below is the list of latest and updated jQuery interview questions and their answers for freshers as well as experienced users. These interview question covers latest version of jQuery which is jQuery 2.0. These interview questions will help you to prepare for the interviews, for quick revision and provide strength to your technical skills.

Q1. What is jQuery?
Ans: jQuery is fast, lightweight and feature-rich client side JavaScript Library/Framework which helps in to traverse HTML DOM, make animations, add Ajax interaction, manipulate the page content, change the style and provide cool UI effect. It is one of the most popular client side library and as per a survey it runs on every second website.

Q2. Why do we use jQuery?
Ans: Due to following advantages.

  • Easy to use and learn.
  • Easily expandable.
  • Cross-browser support (IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+)
  • Easy to use for DOM manipulation and traversal.
  • Large pool of built in methods.
  • AJAX Capabilities.
  • Methods for changing or applying CSS, creating animations.
  • Event detection and handling.
  • Tons of plug-ins for all kind of needs.

Q3. How JavaScript and jQuery are different?
Ans: JavaScript is a language While jQuery is a library built in the JavaScript language that helps to use the JavaScript language.

Q4. Is jQuery replacement of Java Script?
Ans: No. jQuery is not a replacement of JavaScript. jQuery is a different library which is written on top of JavaScript. jQuery is a lightweight JavaScript library that emphasizes interaction between JavaScript and HTML.

Q5. Is jQuery a library for client scripting or server scripting?
Ans. Client side scripting.

Q6. Is jQuery a W3C standard?
Ans: No. jQuery is not a W3C standard.

Q7. What is the basic need to start with jQuery?
Ans: To start with jQuery, one need to make reference of it’s library. The latest version of jQuery can be downloaded from jQuery.com.

Q8. Which is the starting point of code execution in jQuery?
Ans: The starting point of jQuery code execution is $(document).ready() function which is executed when DOM is loaded.

Q9. What does dollar sign ($) means in jQuery?
Ans: Dollar Sign is nothing but it’s an alias for JQuery. Take a look at below jQuery code.

$(document).ready(function(){
});

Over here $ sign can be replaced with “jQuery” keyword.

jQuery(document).ready(function(){
});

Q10. Can we have multiple document.ready() function on the same page?
Ans: YES. We can have any number of document.ready() function on the same page.

Q11. Can we use our own specific character in the place of $ sign in jQuery?
Ans: Yes. It is possible using jQuery.noConflict().

Q12. Is it possible to use other client side libraries like MooTools, Prototype along with jQuery?
Ans: Yes.

Q13. What is jQuery.noConflict?
Ans: As other client side libraries like MooTools, Prototype can be used with jQuery and they also use $() as their global function and to define variables. This situation creates conflict as $() is used by jQuery and other library as their global function. To overcome from such situations, jQuery has introduced jQuery.noConflict().

jQuery.noConflict();
// Use jQuery via jQuery(...)
jQuery(document).ready(function(){
   jQuery("div").hide();
});

You can also use your own specific character in the place of $ sign in jQuery.

var $j = jQuery.noConflict();
// Use jQuery via jQuery(...)
$j(document).ready(function(){
   $j("div").hide();
});

Q14. Is there any difference between body onload() and document.ready() function?
Ans: document.ready() function is different from body onload() function for 2 reasons.

  1. We can have more than one document.ready() function in a page where we can have only one body onload function.
  2. document.ready() function is called as soon as DOM is loaded where body.onload() function is called when everything gets loaded on the page that includes DOM, images and all associated resources of the page.

Q15. What is the difference between .js and .min.js?
Ans: jQuery library comes in 2 different versions Production and Deployment. The deployment version is also known as minified version. So .min.js is basically the minified version of jQuery library file. Both the files are same as far as functionality is concerned. but .min.js is quite small in size so it loads quickly and saves bandwidth.

Q16. Why there are two different version of jQuery library?
Ans: jQuery library comes in 2 different versions.

  1. Production
  2. Deployment

The production version is quite useful at development time as jQuery is open source and if you want to change something then you can make those changes in production version. But the deployment version is minified version or compressed version so it is impossible to make changes in it. Because it is compressed, so its size is very less than the production version which affects the page load time.

Q17. What is a CDN?
Ans: A content delivery network or content distribution network (CDN) is a large distributed system of servers deployed in multiple data centers across the Internet. The goal of a CDN is to serve content to end-users with high availability and high performance.

Q18. Which are the popular jQuery CDN? and what is the advantage of using CDN?
Ans: There are 3 popular jQuery CDNs.

  1. 1. Google.
  2. 2. Microsoft
  3. 3. jQuery.

Advantage of using CDN.

  • It reduces the load from your server.
  • It saves bandwidth. jQuery framework will load faster from these CDN.
  • The most important benefit is it will be cached, if the user has visited any site which is using jQuery framework from any of these CDN

Q19. How to load jQuery from CDN?
Ans: Below is the code to load jQuery from all 3 CDNs.
Code to load jQuery Framework from Google CDN

<script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>

Code to load jQuery Framework from Microsoft CDN

<script type="text/javascript"
    src="http://ajax.microsoft.com/ajax/jquery/jquery-1.9.1.min.js">
</script>

Code to load jQuery Framework from jQuery Site(EdgeCast CDN)

<script type="text/javascript"
    src="http://code.jquery.com/jquery-1.9.1.min.js">
</script>

Q20. How to load jQuery locally when CDN fails?
Ans: It is a good approach to always use CDN but sometimes what if the CDN is down (rare possibility though) but you never know in this world as anything can happen.

Below given jQuery code checks whether jQuery is loaded from Google CDN or not, if not then it references the jQuery.js file from your folder.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined')
{
  document.write(unescape("%3Cscript src='Scripts/jquery.1.9.1.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>

It first loads the jQuery from Google CDN and then check the jQuery object. If jQuery is not loaded successfully then it will references the jQuery.js file from hard drive location. In this example, the jQuery.js is loaded from Scripts folder.

Q21. What are selectors in jQuery and how many types of selectors are there?
Ans: 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. There are many types of selectors but basic selectors are:

  • Name: Selects all elements which match with the given element Name.
  • #ID: Selects a single element which matches with the given ID
  • .Class: Selects all elements which match with the given Class.
  • Universal (*): Selects all elements available in a DOM.
  • Multiple Elements E, F, G: Selects the combined results of all the specified selectors E, F or G.
  • Attribute Selector: Select elements based on its attribute value.

Q22. How do you select element by ID in jQuery?
Ans: To select element use ID selector. We need to prefix the id with “#” (hash symbol). For example, to select element with ID “txtName”, then syntax would be,

$('#txtName')

Q23. What does $(“div”) will select?
Ans: This will select all the div elements on page.

Q24. How to select element having a particular class (“.selected”)?
Ans: $(‘.selected’). This selector is known as class selector. We need to prefix the class name with “.” (dot).

Q25. What does $(“div.parent”) will select?
Ans: All the div element with parent class.

Q26. What are the fastest selectors in jQuery?
Ans: ID and element selectors are the fastest selectors in jQuery.

Q27. What are the slow selectors in jQuery?
Ans: class selectors are the slow compare to ID and element.

Q28. How jQuery selectors are executed?
Ans: Your last selectors is always executed first. For example, in below jQuery code, jQuery will first find all the elements with class “.myCssClass” and after that it will reject all the other elements which are not in “p#elmID”.

$("p#elmID .myCssClass");

Q29. Which is fast document.getElementByID(‘txtName’) or $(‘#txtName’).?
Ans: Native JavaScipt is always fast. jQuery method to select txtName “$(‘#txtName’)” will internally makes a call to document.getElementByID(‘

txtName’). As jQuery is written on top of JavaScript and it internally uses JavaScript only So JavaScript is always fast.

Q30. Difference between $(this) and ‘this’ in jQuery?
Ans: this and $(this) refers to the same element. The only difference is the way they are used. ‘this’ is used in traditional sense, when ‘this’ is wrapped in $() then it becomes a jQuery object and you are able to use the power of jQuery.

$(document).ready(function(){
    $('#spnValue').mouseover(function(){
       alert($(this).text());
  });
});

In below example, this is an object but since it is not wrapped in $(), we can’t use jQuery method and use the native JavaScript to get the value of span element.

$(document).ready(function(){
    $('#spnValue').mouseover(function(){
       alert(this.innerText);
  });
});

Q31. How do you check if an element is empty?
Ans: There are 2 ways to check if element is empty or not. We can check using “:empty” selector.

$(document).ready(function(){
    if ($('#element').is(':empty')){
       //Element is empty
  });
});

Q32. How do you check if an element exists or not in jQuery?
Ans: Using jQuery length property, we can ensure whether element exists or not.

$(document).ready(function(){
    if ($('#element').length > 0){
       //Element exists
  });
});

Q33. What is the use of jquery .each() function?
Ans: The $.each() function is used to iterate over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is an object or an array.

Q34. What is the difference between jquery.size() and jquery.length?
Ans: jQuery .size() method returns number of element in the object. But it is not preferred to use the size() method as jQuery provide .length property and which does the same thing. But the .length property is preferred because it does not have the overhead of a function call.

Q35. What is the difference between $(‘div’) and $(‘<div/>’) in jQuery?
Ans: $(‘<div/>’) : This creates a new div element. However this is not added to DOM tree unless you don’t append it to any DOM element.

$(‘div’) : This selects all the div element present on the page.

Q36. What is the difference between parent() and parents() methods in jQuery?
Ans: The basic difference is the parent() function travels only one level in the DOM tree, where parents() function search through the whole DOM tree.

Q37. What is the difference between eq() and get() methods in jQuery?
Ans: eq() returns the element as a jQuery object. This method constructs a new jQuery object from one element within that set and returns it. That means that you can use jQuery functions on it.

get() return a DOM element. The method retrieve the DOM elements matched by the jQuery object. But as it is a DOM element and it is not a jQuery-wrapped object. So jQuery functions can’t be used. Find out more here.

Q38. How do you implement animation functionality?
Ans: The .animate() method allows us to create animation effects on any numeric CSS property. This method changes an element from one state to another with CSS styles. The CSS property value is changed gradually, to create an animated effect.

Syntax is:

(selector).animate({styles},speed,easing,callback)
  • styles: Specifies one or more CSS properties/values to animate.
  • duration: Optional. Specifies the speed of the animation.
  • easing: Optional. Specifies the speed of the element in different points of the animation. Default value is “swing”.
  • callback: Optional. A function to be executed after the animation completes.

Simple use of animate function is,

$("btnClick").click(function(){
  $("#dvBox").animate({height:"100px"});
});

Q39. How to disable jQuery animation?
Ans: Using jQuery property “jQuery.fx.off“, which when set to true, disables all the jQuery animation. When this is done, all animation methods will immediately set elements to their final state when called, rather than displaying an effect.

Q40. How do you stop the currently-running animation?
Ans: Using jQuery “.stop()” method.

Q41. What is the difference between .empty(), .remove() and .detach() methods in jQuery?
Ans: All these methods .empty(), .remove() and .detach() are used for removing elements from DOM but they all are different.

.empty(): This method removes all the child element of the matched element where remove() method removes set of matched elements from DOM.

.remove(): Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

.detach(): This method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.

Find out more here

Q42. Explain .bind() vs .live() vs .delegate() vs .on()
Ans: All these 4 jQuery methods are used for attaching events to selectors or elements. But they all are different from each other.

.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.

.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.

.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.

.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.

Find out more here

Q43. What is wrong with this code line “$(‘#myid.3’).text(‘blah blah!!!’);”
Ans: The problem with above statement is that the selectors is having meta characters and to use any of the meta-characters ( such as !”#$%&'()*+,./:;<=>?@[\]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id=”foo.bar”, can use the selector $(“#foo\\.bar”).
So the correct syntax is,

$('#myid\\.3').text('blah blah!!!');

Q44. How to create clone of any object using jQuery?
Ans: jQuery provides clone() method which performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes.

$(document).ready(function(){
  $('#btnClone').click(function(){
     $('#dvText').clone().appendTo('body');
     return false;
  });
});

Q45. Does events are also copied when you clone any element in jQuery?
Ans: As explained in previous question, using clone() method, we can create clone of any element but the default implementation of the clone() method doesn’t copy events unless you tell the clone() method to copy the events. The clone() method takes a parameter, if you pass true then it will copy the events as well.

$(document).ready(function(){
   $("#btnClone").bind('click', function(){
     $('#dvClickme').clone(true).appendTo('body');
  });

Q46. What is difference between prop and attr?
Ans: attr(): Get the value of an attribute for the first element in the set of matched elements. Whereas,.prop(): (Introduced in jQuery 1.6) Get the value of a property for the first element in the set of matched elements.

Attributes carry additional information about an HTML element and come in name=”value” pairs. Where Property is a representation of an attribute in the HTML DOM tree. once the browser parse your HTML code ,corresponding DOM node will be created which is an object thus having properties.

attr() gives you the value of element as it was defines in the html on page load. It is always recommended to use prop() to get values of elements which is modified via javascript/jquery , as it gives you the original value of an element’s current state. Find out more here.

Q47. What is event.PreventDefault?
Ans: The event.preventDefault() method stops the default action of an element from happening. For example, Prevents a link from following the URL.

Q48. What is the difference between event.PreventDefault and event.stopPropagation?
Ans: event.preventDefault(): Stops the default action of an element from happening.
event.stopPropagation(): Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. For example, if there is a link with a click method attached inside of a DIV or FORM that also has a click method attached, it will prevent the DIV or FORM click method from firing.

Q49. What is the difference between event.PreventDefault and “return false”?
Ans: e.preventDefault() will prevent the default event from occurring, e.stopPropagation() will prevent the event from bubbling up and return false will do both.

Q50. What is the difference between event.stopPropagation and event.stopImmediatePropagation?
Ans: event.stopPropagation() allows other handlers on the same element to be executed, while event.stopImmediatePropagation() prevents every event from running. For example, see below jQuery code block.

$("p").click(function(event){
  event.stopImmediatePropagation();
});
$("p").click(function(event){
  // This function won't be executed
  $(this).css("background-color", "#f00");
});

If event.stopPropagation was used in previous example, then the next click event on p element which changes the css will fire, but in case event.stopImmediatePropagation(), the next p click event will not fire.

Q51. How to check if number is numeric while using jQuery 1.7+?
Ans: Using “isNumeric()” function which was introduced with jQuery 1.7.

Q52. How to check data type of any variable in jQuery?
Ans: Using $.type(Object) which returns the built-in JavaScript type for the object.

Q53. How do you attach a event to element which should be executed only once?
Ans: Using jQuery one() method. This attaches a handler to an event for the element. The handler is executed at most once per element. In simple terms, the attached function will be called only once.

$(document).ready(function() {
    $("#btnDummy").one("click", function() {
        alert("This will be displayed only once.");
    });
});​

Q54. Can you include multiple version of jQuery? If yes, then how they are executed?
Ans: Yes. Multiple versions of jQuery can be included in same page.

Q55. In what situation you would use multiple version of jQuery and how would you include them?
Ans: Well, it is quite possible that the jQuery plugins which are used are dependent on older version but for your own jQuery code, you would like to use newer version. So because of this dependency, multiple version of jQuery may required sometimes on single page.

Below code shows how to include multiple version of jQuery.

<script type='text/javascript' src='js/jquery_1.9.1.min.js'></script>

<script type='text/javascript'>
 var $jq = jQuery.noConflict();
</script>

<script type='text/javascript' src='js/jquery_1.7.2.min.js'></script>

By this way, for your own jQuery code use “$jq”, instead of “$” as “$jq” refers to jQuery 1.9.1, where “$” refers to 1.7.2.

Q56. Is it possible to hold or delay document.ready execution for sometime?
Ans: Yes, its possible. With Release of jQuery 1.6, a new method “jQuery.holdReady(hold)” was introduced. This method allows to delay the execution of document.ready() event. document.ready() event is called as soon as your DOM is ready but sometimes there is a situation when you want to load additional JavaScript or some plugins which you have referenced.

​
$.holdReady(true);
$.getScript("myplugin.js", function() {
     $.holdReady(false);
});

Q57. What is chaining in jQuery?
Ans: Chaining is one of the most powerful feature of jQuery. In jQuery, Chaining means to connect multiple functions, events on selectors. It makes your code short and easy to manage and it gives better performance. The chain starts from left to right. So left most will be called first and so on.

​$(document).ready(function(){
    $('#dvContent').addClass('dummy');
    $('#dvContent').css('color', 'red');
    $('#dvContent').fadeIn('slow');
});​

The above jQuery code sample can be re-written using chaining. See below.

​$(document).ready(function(){
    $('#dvContent').addClass('dummy')
          .css('color', 'red')
          .fadeIn('slow');     
});​

Not only functions or methods, chaining also works with events in jQuery.

Q58. How does caching helps and how to use caching in jQuery?
Ans: Caching is an area which can give you awesome performance, if used properly and at the right place. While using jQuery, you should also think about caching. For example, if you are using any element in jQuery more than one time, then you must cache it. See below code.

$("#myID").css("color", "red");
//Doing some other stuff......
$("#myID").text("Error occurred!");
​

Now in above jQuery code, the element with #myID is used twice but without caching. So both the times jQuery had to traverse through DOM and get the element. But if you have saved this in a variable then you just need to reference the variable. So the better way would be,

var $myElement = $("#myID").css("color", "red");
//Doing some other stuff......
$myElement.text("Error occurred!");
​

So now in this case, jQuery won’t need to traverse through the whole DOM tree when it is used second time. So in jQuery, Caching is like saving the jQuery selector in a variable. And using the variable reference when required instead of searching through DOM again.

Q59. You get “jquery is not defined” or “$ is not defined” error. What could be the reason?
Ans: There could be many reasons for this.

  • You have forgot to include the reference of jQuery library and trying to access jQuery.
  • You have include the reference of the jQuery file, but it is after your jQuery code.
  • The order of the scripts is not correct. For example, if you are using any jQuery plugin and you have placed the reference of the plugin js before the jQuery library then you will face this error.

Q60. How to write browser specific code using jQuery?
Ans: Using jQuery.browser property, we can write browser specific code. This property contains flags for the useragent, read from navigator.userAgent. This property was removed in jQuery 1.9.

Q61. Can we use jQuery to make ajax request?
Ans: Yes. jQuery can be used for making ajax request.

Q62. What are various methods to make ajax request in jQuery?
Ans: Using below jQuery methods, you can make ajax calls.

  • load() : Load a piece of html into a container DOM
  • $.getJSON(): Load JSON with GET method.
  • $.getScript(): Load a JavaScript file.
  • $.get(): Use to make a GET call and play extensively with the response.
  • $.post(): Use to make a POST call and don’t want to load the response to some container DOM.
  • $.ajax(): Use this to do something on XHR failures, or to specify ajax options (e.g. cache: true) on the fly.

Find out more here.

Q63. Is there any advantage of using $.ajax() for ajax call against $.get() or $.post()?
Ans: By using jQuery post()/ jQuery get(), you always trust the response from the server and you believe it is going to be successful all the time. Well, it is certainly not a good idea to trust the response. As there can be n number of reason which may lead to failure of response.

Where jQuery.ajax() is jQuery’s low-level AJAX implementation. $.get and $.post are higher-level abstractions that are often easier to understand and use, but don’t offer as much functionality (such as error callbacks). Find out more here.

Q64. What are deferred and promise object in jQuery?
Ans: Deferred and promise are part of jQuery since version 1.5 and they help in handling asynchronous functions like Ajax. Find out more here.

Q65. Can we execute/run multiple Ajax request simultaneously in jQuery? If yes, then how?
Ans: Yes, it is possible to execute multiple Ajax request simultaneously or in parallel. Instead of waiting for first ajax request to complete and then issue the second request is time consuming. The better approach to speed up things would be to execute multiple ajax request simultaneously.

Using jQuery .when() method which provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. Find out more here.

Q66. Can you call C# code-behind method using jQuery? If yes,then how?
Ans: Yes. We can call C# code-behind function via $.ajax. But for do that it is compulsory to mark the method as WebMethod.

Q67. Which is the latest version of jQuery library?
Ans: 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.

Q68. Does jQuery 2.0 supports IE?
Ans: No. jQuery 2.0 has no support for IE 6, IE 7 and IE 8.

Q69. What are source maps in jQuery?
Ans: In case of jQuery, Source Map is nothing but mapping of minified version of jQuery against the un-minified version. Source map allows to debug minified version of jQuery library. Source map feature was release with jQuery 1.9. Find out more here.

Q70. How to use migrate jQuery plugin?
Ans: with release of 1.9 version of jQuery, many deprecated methods were discarded and they are no longer available. But there are many sites in production which are still using these deprecated features and it’s not possible to replace them overnight. So jQuery team provided with jQuery Migrate plugin that makes code written prior to 1.9 work with it.

So to use old/deprecated features, all you need to do is to provide reference of jQuery Migrate Plugin. Find out more here.

Q71. Is it possible to get value of multiple CSS properties in single statement?
Ans: Well, before jQuery 1.9 release it was not possible but one of the new feature of jQuery 1.9 was .css() multi-property getter.

var propCollection = $("#dvBox").css([ "width", "height", "backgroundColor" ]);

In this case, the propCollection will be an array and it will look something like this.

{ 
  width: "100px", 
  height: "200px", 
  backgroundColor: "#FF00FF" 
}

Q72. How do you stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements?
Ans: It can be done via calling .stop([clearQueue ] [, jumpToEnd ]) method and by passing both the parameters as true.

Q73. What is finish method in jQuery?
Ans: The .finish() method stops all queued animations and places the element(s) in their final state. This method was introduced in jQuery 1.9.

Q74. What is the difference between calling stop(true,true) and finish method?
Ans: The .finish() method is similar to .stop(true, true) in that it clears the queue and the current animation jumps to its end value. It differs, however, in that .finish() also causes the CSS property of all queued animations to jump to their end values, as well.

Q75. Consider a scenario where things can be done easily with javascript, would you still prefer jQuery?
Ans: No. If things can be done easily via CSS or JavaScript then You should not think about jQuery. Remember, jQuery library always comes with xx kilobyte size and there is no point of wasting bandwidth.

Q76. Can we use protocol less URL while referencing jQuery from CDNs?
Ans: Yes. Below code is completely valid.

<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>

Q77. What is the advantage of using protocol less URL while referencing jQuery from CDNs?
Ans: It is quite useful when you are moving from HTTP to HTTPS url. You need to make sure that correct protocol is used for referencing jQuery library as pages served via SSL should contain no references to content served through unencrypted connections.

“protocol-less” URL is the best way to reference third party content that’s available via both HTTP and HTTPS. When a URL’s protocol is omitted, the browser uses the underlying document’s protocol instead. Find out more here.

Q78. What is jQuery plugin and what is the advantage of using plugin?
Ans: A plug-in is piece of code written in a standard JavaScript file. These files provide useful jQuery methods which can be used along with jQuery library methods. jQuery plugins are quite useful as its piece of code which is already written by someone and re-usable, which saves your development time.

Q79. What is jQuery UI?
Ans: jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library that can be used to build interactive web applications.

Q80. What is the difference between jQuery and jQuery UI?
Ans: jQuery is the core library. jQueryUI is built on top of it. If you use jQueryUI, you must also include jQuery.