Top 50 J Query Interview Questions You Must Prepare 24.May.2024

The plugin can be considered to be simply a new method that can be used by a user to extend the prototype object of a jquery. A plugin performs some actions on a collection of elements. Each method that comes with the jquery core can be considered to be a plugin.

The code for creating a plugin that would add and remove a class on hover would be as follows:

  (function($){  $.fn.hoverClass = function(c) {  return this.hover(  function() { $(this).toggleClass(c); }  );  };  })(jQuery);  // using the plugin  $('li').hoverClass('hover');

  • By using jQuery.holdReady() function we can hold or release the execution of jQuery’s ready event.
  • This method should be call before we run ready event.
  • To delay the ready event, we have to call jQuery.holdReady(true);
  • When we want to release the ready event then we have to call jQuery.holdReady(false);
  • This function is helpful when we want to load any jQuery plugins before the execution of ready event.

For example

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

 

The .animate() method is used to create animations with other shorthands using it. The queue() method can be used to link together multiple animation methods to create an unique effect. These methods are effective when all the data is available locally and all the methods are executed on as single system only. In case the user wants to use the animation methods on a data that resides on the server and wants to handle at a single go the user can make used of the .deferred method.

For example:

  var my$ = $.sub();  my$.fn.animate=function(props,speed,easing,callback){
var options=speed && typeof speed==="object"?
jQuery.extend({}, speed) : {
complete: callback || !callback && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: callback && easing || easing &&
!jQuery.isFunction(easing) && easing
};
var dfd = my$.Deferred(),
complete = options.complete,
count = this.length;
options.complete = function() {
complete && complete.call( this );
if ( !--count ) {
dfd.resolve();
}
};

The Jquery ajax() method is used to perform an AJAX (asynchronous HTTP) request.

// Returns jQuery UI version or undefined $.ui.version

We can add more than one document.ready() function in a page.

we can have only one onload function.

Document.ready() function is called as soon as DOM is loaded.

body.onload() function is called when everything (DOM, images)gets loaded on the page.

  • In jQuery we have three methods to give the fade effect to elements: fadeIn, fadeOut and fadeTo
  • This methods change the opacity of element with animation.

Syntax:

  $(selector).fadeIn(speed,callback)  $(selector).fadeOut(speed,callback)  $(selector).fadeTo(speed,opacity,callback)
  • “speed” can be one of following values : “slow”, “fast”, “normal” or milliseconds
  • “opacity” specify the value that allows the fading to given opacity.
  • “callback” is the function which we want to run once the fading effect is complete.

For example

  $("clickme").click(function(){
$("mydiv").fadeTo("slow",0.50); });
$("clickme").click(function(){
$("mydiv").fadeOut(3000); });.

Attribute values are values written in HTML text file But property value are values found in HTML DOM tree. Thus property values can change as per user interaction but Attribute values never changes.

  • jQuery.data() is used to set/return arbitrary data to/from an element.
  • Syntax: jQuery.data(element, key, value)
  • “element” is the DOM element to which the data is associated.
  • “key” is an arbitrary name of the piece of data.
  • “value” is value of the specified key.
  • Suppose we want to set the data for a span element:

jQuery.data(span, “item”, { val1: 10, val2: "myitem" });

If we want to retrieve the data related to div element and set it to label’s data:

$("label:val1").text(jQuery.data(div, "item").val1);
$("label:val2").text(jQuery.data(div, "item").val2);

jQuery-1.4.4.js file size is 178 KB as against its minified version jQuery-1.4.4-min.js that is only 76.7 KB in size. So when your page loads in the client's browser if you are not using minified version, it loads 178 KB file that takes more time to load than 76.7 KB.

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.

document.ready() function is different from body onload() function due to 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.

Below are the generalised version of js and css file we need to reference while developing Jquery Mobile application. jquery.mobile-x.x.x.min.css jquery-x.x.x.min.js jquery.mobile-x.x.x.min.js

The object literal does not provide any privacy for the methods or properties. The module pattern allows the user to offer privacy to functions and variables. It can be used to set to expose limited API.

For example: The module pattern code:

    var feature =(function() {  var privateThing = 'secret',  publicThing = 'not secret',  changePrivateThing = function() {  privateThing = 'super secret';  },  sayPrivateThing = function() {  console.log(privateThing);  changePrivateThing();  };  return {  publicThing : publicThing,  sayPrivateThing : sayPrivateThing  }  })();  feature.publicThing; // 'not secret'  feature.sayPrivateThing();

document.ready() function can be inlcuded multiple times whereas onload() method can be called only once in a page.

document.ready() is called as soon as DOM is loaded while onload is called when everything is loaded on page i.e. images, DOM and other resources associated with the page.

  1. keypress
  2. keydown
  3. keyup

To start with jQuery, one need to make reference of it's library. The latest version of jQuery can be downloaded from jQuery.com.

In terms of functionality, there is no difference between the jQuery-x.x.x.js and jQuery-x.x.x-min.js (also called minified version). However this can play a vital role in the performance of the web page.

The hover() method takes two functions and is a combination of the mouseenter() and mouseleave() methods. The first function is executed when the mouse enters the HTML element, and the second function is executed when the mouse leaves the HTML element:

Example:

$("#p1").hover(function(){ alert("You entered p1!"); }, function(){ alert("Bye! You now leave p1!"); });

The resize() function is called whenever the browser size is changed. This event can be only used with $(window).

Syntax: .resize([event_data], handler(event_object))

  • The “event_data” is the data to be sent to the handler.
  • The “handler(event_object)” is a function to be called each time when the window is resized.

For example

$(window).resize(function() {
$('#message).text('window is resized to'+$(window).width()+
‘x’ + $(window).height());
});

Below are the advantages of using j Qery over JavaScript

  1. Jquery is well written optimised javascript code so it will be faster in execution unless we write same standard optimised javascript code.
  2. Jquery is concise java script code ,me minimal ammount of code is to be written for the same functionality than the javascript.
  3. Javascript related Development is fast using Jquery because most of the functionality is already written in the library and we just need to use that.
  4. Jquery has cross browser support ,so we save time for supporting all the browsers.

 

min.js is basically the minified version of .js file. Both the files are same as far as functionality is concerned.

.min.js is used to increase the page performance as it is small in size compare to .js and takes less time to load.

The animate function is used to apply the custom animation effect to elements.

Syntax:

$(selector).animate({params}, [duration], [easing], [callback])

  • “param” defines the CSS properties on which you want to apply the animation.
  • “duration” specify how long the animation will run. It can be one of following values : “slow”, “fast”, “normal” or milliseconds
  • “easing” is the string which specify the function for the trition.
  • “callback” is the function which we want to run once the animation effect is complete.

For example

  <div id id="clickToAnimate">  Click Me  </div>  <div id ="mydiv" style=”width:200px; height:300px;   position: relative; right: 20px;">  </div>

Following is the jQuery to animate opacity, left offset, and height of the mydiv element

  $('# clickToAnimate’).click(function() {  $('#book').animate({  opacity: 0.30,  left: '+=20',  height: 'toggle'  }, 3000, function() {  // run after the animation complete.  });  });

We can use all selector to select all elements on page.

example : $('*')

You can create your own shortcut very easily. The noConflict() method returns a reference to jQuery, that you can save in a variable, for later use.

To use jQuery in ASP.NET web application follow the below steps:

  1. Go to http://jquery.com/(The official jQuery WebSite)
  2. Download latest .js jQuery file from the website.
  3. Put it the script(or other folder) in the root of your web application
  4. Add the below tag on the page where you want to use Jquery

Refer the following example

  $(document).ready(function(){  $(‘#clickme’).click(function(){  alert($(this).text());  alert(this.innerText);  });  });
  • this and $(this) references the same element but the difference is that “this” is used in traditional way but when “this” is used with $() then it becomes a jQuery object on which we can use the functions of jQuery.
  • In the example given, when only “this” keyword is used then we can use the jQuery text() function to get the text of the element, because it is not jQuery object. Once the “this” keyword is wrapped in $() then we can use the jQuery function text() to get the text of the element.

JQuery min .js file is actully a minified version of Actual JQuery .js. The min files have less size but same content so this improves the performance.so You should prefer to use min files.

It returns the number of elements in the object. This method helps in finding the count of elements in the object.

Some of the common methods are :

  1. Show()
  2. Hide()
  3. Toggle()
  4. FadeIn()
  5. FadeOut()

jQuery was founded by John Resig in January 2006.

detach method is same as remove method , but detach keeps the jQuery data associated with the removed elements.

detach method is more powerful when you have to reinsert the removed data.

class selectors are the slow compare to ID and element.

In plain java scripts the information about an element can be stored by adding a domain object model property to the element. This results in memory leak problems in certain browsers. In jquery the user does not has to worry about memory management issues.

For example: storing and retrieving data related to an element:

  $('#myDiv').data('keyName', { foo : 'bar' });  $('#myDiv').data('keyName'); // { foo : 'bar' }

Jquery allows the user to store any kind of information on an element. The $.fn.data is used the most to store data related to an element.

For ex. storing of relationship between elements with the use of $.fn.data :

  $('#myList li').each(function() {  var $li = $(this), $div = $li.find('div.content');  $li.data('contentDiv', $div);  });  // later, the user is not required to look for the div again;  // the data can simply be read from the list items data;  var $firstLi = $('#myList li:first');  $firstLi.data('contentDiv').html('new content');

All the div element with tutoriz class.

The mousedown() method attaches an event handler function to an HTML element. The function is executed, when the left mouse button is pressed down, while the mouse is over the HTML element:

Example: $("#p1").mousedown(function(){ alert("Mouse down over p1!"); });

All the visitors actions that a web page can respond to are called events. An event represents the precise moment when something happens.

Examples: .moving a mouse over an element .selecting a radio button The term "fires" is often used with events.

Example: "The click event fires the moment if you click the mouse".

Selectors are used in jQuery to find and select DOM elements via id, class or element selector. There are many new selectors introduced in jQuery. Using jQuery selectors DOM elements can be selected and manipulated.

The RequireJS is a dependency management tool that can be used by the user to manage script modules. It can be used to load scripts once a page has been loaded. This helps in evenly distributing the downloads.

For example: RequireJS module with dependencies defined:

  require.def("my/shirt",
["my/cart", "my/inventory"],
function(cart, inventory) {
//return an object to define the "my/shirt" module.
return {
color: "blue",
size: "large"
addToCart: function() {
inventory.decrement(this);
cart.add(this);
}
}
}
);

In the above example the my.shirt module is created. This module depends on the my/cart and my/inventory.

Code for second last div : $("div.questions > div::nth-last-child(2)").css("color", "red");

Jquery provides the user with the ability to change the attributes of a property dynamically. The jquery slide method can be used to change the height of elements gradually. This can be used to give the scroll effect of an image over image.

The jquery comprises of the following slide methods:

  • $(selector).slideDown(speed,callback)
  • $(selector).slideUp(speed,callback)
  • $(selector).slideToggle(speed,callback)

The speed parameter is used to effect the speed of change of the jquery. The parameters for it can be slow, fast , normal and time in milliseconds. The parameter of callback is used to refer to the name of the function to be executed once the completion of function occurs.

CDN - It stands for Content Distribution Network or Content Delivery Network. Generally, a group of systems at various places connected to trfer data files between them to increase its bandwidth while accessing data. The typical architecture is designed in such a way that a client access a file copy from its nearest client rather than accessing it from a centralized server. So we can load this jQuery file from that CDN so that the efficiency of all the clients working under that network will be increased.

using css() method we can apply css in div element.

example:$(“div”).css(“border”,”1px solid green”);

The jQuery load() method is powerful AJAX method.

The load() method loads data from a server and puts the returned data into the selected element without reload the complete page.