Skip to content

Instantly share code, notes, and snippets.

@tachymetre
Last active July 27, 2016 18:12
Show Gist options
  • Save tachymetre/0a04fed9ed30f79f60ef to your computer and use it in GitHub Desktop.
Save tachymetre/0a04fed9ed30f79f60ef to your computer and use it in GitHub Desktop.
UI-101 (jQuery)
  1. What is jQuery? - A Javascript library that make things like DOM selection/manipulation, AJAX, and animation, easier

  2. What programming language does jQuery use? - Javascript

  3. Is jQuery code executed on the client side, or server side? - Client side

  4. How do you install/use jQuery in a project? What is the minimum setup needed to start using jQuery? - script tag, linked to a jquery CDN or locally hosted file

  5. How do you select all elements with the class of “selected” in jQuery? javascript $('.selected');

  6. Can jQuery be used to make an AJAX request? - Yes

  7. Is there any difference between body onload() and document.ready() function? - document.ready() function is different from body onload() function for 2 reasons. First, we can have more than one document.ready()function in a page where we can have only onebody onloadfunction. Second,document.ready()function is called as soon as DOM is loaded wherebody.onload()` function is called when everything gets loaded on the page that includes DOM, images and all associated resources of the page

  8. What is a CDN? - 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

  9. Difference between $(this) and this in jQuery? - 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

  10. What is the difference between jquery.size() and jquery.length? - 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

  11. What is the difference between $('div') and $('<div/>') in jQuery? - $('<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

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

  13. What is the difference between eq() and get() methods in jQuery? - 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

  14. How do you implement animation functionality? - 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 - The syntax for a sample animated effect is the following: ```javascript $('#selector').animate({styles}, speed, easing, callback)

- styles: specifies one or more CSS properties/values to animate
- speed: 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
```
  1. How to disable jQuery animation? - 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

  2. How do you stop the currently-running animation? - Using jQuery .stop() method

  3. What is the difference between .empty(), .remove() and .detach() methods in jQuery? - 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

  4. Explain .bind() vs .live() vs .delegate() vs .on() - 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

  5. What is wrong with this code line? javascript $('#myid.3').text('blah blah!!!'); - 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: javascript $('#myid\\.3').text('blah blah!!!');

  6. How to create clone of any object using jQuery? - 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 javascript // Sample clone function $(document).ready(function() { $('#btnClone').click(function() { $('#dvText').clone().appendTo('body'); return false; }); });

  7. Does events are also copied when you clone any element in jQuery? - 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 javascript // Sample code $(document).ready(function() { $('#btnClone').bind('click', function() { $('#dvClickMe').clone(true).appendTo('body'); }); });

  8. What is difference between .prop() and .attr()? - .attr(): Get the value of an attribute for the first element in the set of matched elements - .prop(): 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

  9. What is event.PreventDefault()? - The event.preventDefault() method stops the default action of an element from happening. For example, prevents a link from following the URL

  10. What is the difference between event.PreventDefault() and event.stopPropagation()? - 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

  11. What is the difference between event.PreventDefault() and return false? - e.preventDefault() will prevent the default event from occurring, e.stopPropagation() will prevent the event from bubbling up and return false will do both

  12. What is the difference between event.stopPropagation() and event.stopImmediatePropagation()? - event.stopPropagation() allows other handlers on the same element to be executed - event.stopImmediatePropagation() prevents every event from running. Example for this method is as followed javascript $('p').click(function(event) { event.stopImmediatePropagation(); }); $('p').click(function(event) { // This function won't be executed $(this).css("background", "red"); }); - 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

  13. How to check if number is numeric while using jQuery? - Using isNumeric() function

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

  15. How do you attach a event to element which should be executed only once? - 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 javascript // Sample code $(document).ready(function() { $('#btnDummy').one('click', function() { alert('This will be displayed only onece'); }); });

  16. Is it possible to hold or delay document.ready execution for sometime? - Yes, it's possible. A new method jQuery.holdReady(hold) was introduced to do this. 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 javascript // Sample code $.holdReady(true); $.getScript("myplugin.js", function() { $.holdReady(false); });

  17. What is chaining in jQuery? - 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 ```javascript // Sample code /* BEFORE CHAINING */ $(document).ready(function() { $('#dvContent').addClass('dummy');     $('#dvContent').css('color',  'red'); $('#dvContent').fadeIn('slow'); });​

/* 			AFTER CHAINING			*/
$(document).ready(function() {    
    $('#dvContent').addClass('dummy').css('color','red').fadeIn('slow');    
});​    
```
  1. How does caching helps and how to use caching in jQuery? - 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 javascript // WITHOUT CACHING $("#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 javascript // WITH CACHING 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

  2. What are various methods to make ajax request in jQuery? - 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

  3. Is there any advantage of using $.ajax() for ajax call against $.get() or $.post()? - By using jQuery post() or 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 reasons 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)

  4. What are deferred and promise object in jQuery? - Deferred and promise help in handling asynchronous functions like Ajax

  5. Can we execute/run multiple Ajax request simultaneously in jQuery? If yes, then how? - 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

  6. What are source maps in jQuery? - 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

  7. Is it possible to get value of multiple CSS properties in single statement? - Yes, it is posiible to do so by using the .css() multi-property getter javascript // Sample code $('#sample').css({ 'width': '100px', 'height': '200px', 'backgroundColor': 'yellow' });

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

  9. What is finish method in jQuery? - The .finish() method stops all queued animations and places the element(s) in their final state

  10. What is the difference between calling .stop(true,true) and .finish()? - 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

  11. What is jQuery no conflict? - The noConflict() method releases the hold on the $ shortcut identifier, so that other scripts can use it. You can also create your own shortcut very easily javascript var XYZ = $.noConflict();

  12. What is $ in jQuery? - The $ represents the jQuery Function, and is actually a shorthand alias for jQuery. It is typically used as a selector (i.e. a function that returns a set of elements found in the DOM)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment