Showing posts with label jQuery Interview Question. Show all posts
Showing posts with label jQuery Interview Question. Show all posts

Thursday, July 25, 2013

Difference Between jQuery().each() and jQuery.each()

jQuery has 2 different methods jQuery().each() (Also written as "$.each()") and jQuery.each(). Both the methods are similar in nature used for iteration or looping but the differ only at the level where they are used.

jQuery.each(): is used to iterate, exclusively, over a jQuery object. When called it iterates over the DOM elements that are part of the jQuery object.

$.each(): function can be used to iterate over any collection, whether it is an object or an array.

Related Post:
First, let see how jQuery.each() works. To work with this function, you always need to pass a selector on which iteration needs to be performed. Consider the following HTML,
<ul>
    <li>foo</li>
    <li>bar</li>
</ul>
Now below jQuery code, will select all "li" elements and loop through each of the item and logs its index and text.
$( "li" ).each(function( index ) {
  console.log( index + ": " + $(this).text() );
});
On the other side, $.each() is used to iterate through an object or array collection. See below jQuery code.
var obj = { one:1, two:2, three:3, four:4, five:5 };
$.each( obj, function( key, value ) {
  alert( key + ": " + value );
});
Got the idea about the difference. But you can also make $.each() function to make it similar to jQuery.each(). All you need to do is to instead of object or array, you can pass DOM collection to achieve the same result. See below jQuery code.
$.each($( "li" ), function( index, value ) {
  console.log( index + ": " + $(this).text() );
});
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Monday, July 15, 2013

Download jQuery Interview Questions free eBook

Free eBook to download jQuery interview question and answers in PDF format. These are the question which You'll Most Likely Be Asked in an interview. This is a same list which few days ago, I had posted about Latest jQuery interview questions and answers and the response was quite good. So now you can also download the questionnaire in PDF format.

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, July 9, 2013

Latest jQuery interview questions and answers

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, 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. Does jQuery follow W3C recommendations?
Ans: No.

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
  }
});
And the second way is using the "$.trim()" method.
$(document).ready(function(){
     if($.trim($('#element').html())=='') {
       //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.

Note: If you have any questions to add to this list then please put it comments. We will be glad to add them in this list. We will be keep on updating this list with new questions and share the updates on our Facebook or Twitter channel. If you are not following us then request you to please follow and stay updated.
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Thursday, April 4, 2013

Difference between $('div') and $('<div/>') in jQuery

One of my colleague who is learning jQuery asked me what is the difference between $('div') and $('<div/>') , if used as selector. To explain more, take a look at below code.
$('<div/>').addClass('test');
$('div').addClass('test');
It is indeed quite confusing for someone who just started learning jQuery. So I went ahead and explained him about how they are different.

Related Post:

$('<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.

So, the code $('<div/>').addClass('test') will create a new div element and adds css class called "test". And $('div').addClass('test') will select all the div element present on the page and adds css class "test" to them.

As mentioned earlier that while using $('<div/>'), only new element gets created but it is still not added to DOM. One have to append it to any other element. For example, to append this newly created div to body, use below jQuery code.
$('<div/>').addClass('test').appendTo('body')

Hope you find this useful!!!!

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, April 2, 2013

jQuery: Difference between eq() and get()

In this post, find out what is the difference between jQuery  eq() and  get() method. Both the methods are used to find and select single element from set of elements and they both return single "element". And they both accept single int type parameter, which denotes index.

Related Post:

For example, take a look at below HTML. There is a <ul> element with 5 <li> elements.
<ul>
    <li>list item 1</li>
    <li>list item 2</li>
    <li>list item 3</li>
    <li>list item 4</li>
    <li>list item 5</li>
</ul>
And to select 3rd <li> element, use either get() or eq() and pass 2 as index. Keep in mind that index is zero-based.
$('li').get(2);
$('li').eq(2);
In the above code, both will return the 3rd <li> element. But then what is the difference between 2.

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.
$(document).ready(function () {
  $('li').eq(2).css('background-color', 'red'); //Works
  $('li').get(1).css('background-color', 'red'); // Error. Object #<HTMLLIElement> has no method 'css' 
});
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Thursday, November 29, 2012

Some Short and Quick Random jQuery Tips

Tips and tricks are always useful as they save time and useful as well. So, today's post is collection of some random, short and quick jQuery tips. These tips are quite useful and can drastically improve performance of your webpage if you are not following them.

Be Smart while using selectors


There are many ways to select element using selectors but that doesn't mean that all are equal. Always try to use ID and Element as selector as they are very fast. Even the class selectors are slower than ID selector.

When IDs are used as selector then jQuery internally makes a call to getElementById() method of Java script which directly maps to the element. When Classes are used as selector then jQuery has to do DOM traversal. So when DOM traversal is performed via jQuery takes more time to select elements.

Use Compressed version of jQuery


Always use the compressed version of jQuery for production or final release as its size is 5 times smaller than Uncompressed version. jQuery library comes in 2 version Compressed and Uncompressed.

1. Production (Compressed Version)
2. Development (Uncompressed Version)

For development purpose, you can choose the development version of .js file as if you want to make some changes then that can be easily done. But ensure that when your software or product goes on production, always use the production version of .js file as its size is 5 times lesser than the development version. This can save some amount of bandwidth.

Don't Repeat Yourself


In software engineering, Don't Repeat Yourself (DRY) is a principle of software development aimed at reducing repetition of information. Duplication (inadvertent or purposeful duplication) can lead to maintenance nightmares, poor factoring, and performance issues. Just for the sake of completing the task, don't repeat your code as it increases the lines of code and reduces performance.

Use Latest Version


Use the latest version of jQuery as your website will be benefited from performance improvement done by the jQuery team in latest release. But Be SMART while referencing as you need to make sure it doesn't break existing code. Learn "How to always reference latest version of jQuery".

Don't Use jQuery Blindly


Don't use jQuery unless it is not necessary. If things can be achieved without jQuery then don't use it. There are so many things which can be achieved using CSS but people use jQuery for them. If you are as well, then think twice.

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Monday, August 27, 2012

jQuery Frequently Asked Questions (FAQ)

In this post, You will find most common questions asked by those developers who are using jQuery for the first time or learning jQuery.


1. What is jQuery?


2. What does dollar Sign ($) means in JQuery?


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(){
});

3. How do I select an element using ID?


To select element using ID, use (#) sign and the ID of the element.
$('#ElementID')

4. How do I select element(s) using CSS Class?


To select element(s) using CSS, use (.) sign and the css class name. All the elements which are assigned this class will be selected.
$('.CssClassName')

5. How do I select element(s) using tag name?


To select element(s) using their HTML tag name, then use below syntax. Below code selects all div element(s) exists on the page.
$('div')
To select div elements with any particular CSS class then,
$('div .CssClassName')

6. How to Check element exists or not in jQuery?


jQuery provides length property for every element which returns 0 if element doesn't exists else length of the element.
if ($('#dvText').length) {  
    // your code  
}

7. How to Enable/Disable element(s)?


8. How to get HTML of any control?


9. How to set HTML of any control?


10. How to check if element is empty?


11. How to check if Checkbox is checked ?


12. How to check if radio button is checked ?


13. Dropdown and jQuery


14. How to detect Browsers using jQuery?


15. Array and jQuery


Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Thursday, May 17, 2012

How to execute jQuery code only after WebPage is loaded completely

One of the advantage of jQuery document.ready() is that it doesn't wait for complete page loading, it starts executing as soon as DOM is loaded. "DOM loading" and "Page Loading" are 2 different terms and don't get confused between these. There is a fundamental difference between these two terms.

"DOM loading" means all the DOM elements are completely loaded but it is quite possible that some of the elements like images are not loaded completely. $(document).ready() gets called when DOM is loaded.

And "Page loading" means that along with all the DOM elements, other elements like images are also loaded completely. window.onload() is traditional Java script code which gets called when the page is loaded.

Read "Is window.onload is different from document.ready()"

But sometimes you may encounter a situation where you need to run the jQuery code once your page is loaded completely. So how do you achieve that? Well, the solutions is combination of jQuery and JavaScript. The solution is to bind the window.onload event in document.ready().
//Code Starts
$(window).bind("load", function() {
   // code here
});
//Code Ends
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, May 15, 2012

.empty() vs .remove() vs .detach() - jQuery

Do you know that jQuery provides various methods to remove elements from DOM? These methods are .empty(), .remove() and .detach(). And in this post, I will show you how these methods (.empty vs .remove vs .detach) are different from each other.

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

.remove(): This method takes elements out of the DOM. 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.

I had already posted about .empty() vs .remove(). So please read the below post first, before going further.
Okay, so got the difference between .empty() and .remove(). So now you might be wondering what is .detach()?

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

Let see the differences with an example. I have created a div element with some text and assigned hover event to this element. This hover event basically add/remove CSS class to the div.
//Code Starts
$("#dvjQuery").hover(function() {
    $(this).addClass('highlight');
}, function() {
   $(this).removeClass('highlight');
});
//Code Ends
Now, remove the div element using jQuery and add it again in the page.
//Code Starts
var dvjQuery = null;
dvjQuery = $("#dvjQuery").remove();
$("#dvParent").html(dvjQuery);
//Code Ends
See result below.

First, take mouse of div and see that hover event is working. Then remove the div and add it again. And you will find that hover event is not working.



Okay, now let's do the same thing but this time using .detach() method.
//Code Starts
var dvjQuery = null;
dvjQuery = $("#dvjQuery").detach();
$("#dvParent").html(dvjQuery);
//Code Ends
See result below.

Again, take mouse of div and see that hover event is working. Then detach the div and attach it again. And you will find that hover event is working.



So to summarize, there are 3 differences between .remove() and .detach()
  • remove() method would erase data associated with the element(data that had been set using the data() method).
  • remove() method would also erase the event associated with the element.
  • If you are not concerned about the data and event then use remove() as it is faster than detach(). There is a performance test created at jsPerf.com for remove() and detach() and below is the result.


Check out this test yourself here

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, January 17, 2012

Difference between sorting string array and numerical array in jQuery

To sort any array, there is a predefined method called "sort" which sorts the array. sort() method sorts the string array in alphabetical order. This method sorts on the basis of the Unicode code points, so it is better to have all uniform names. That is, they must begin with either uppercase or lowercase, but not mixed case. So to sort any string array use the sort method.

Earlier I had posted about jQuery solution to remove item from array, split an array, combine/join arrays, remove duplicate items from array and Find index of element in array, And In this post, find Difference between sorting string array and numerical array in jQuery.

Below jQuery code sort the string array.
$(document).ready(function() {
  var list= [ "jQuery", "Dojo", "JavaScript", "Ajax"];
  $('#alltech').html(list.join(""));
  list = list.sort();
  $('#sorted').html(list.join(""));
})
See result below.


See Complete Code
Now, declare any numerical array and try to use the sort method on this. Just try the below code to check the output.
$(document).ready(function() {
  var list= [ 45, 32, 98, 24, 16, 9, 3];
  $('#allnumber').html(list.join(""));
  list = list.sort();
  $('#sorted').html(list.join(""));
})
See result below.



Surprised!!!!!!!

Well, the numerical values are not sorted correctly with the sort() method because as mentioned earlier that it considers the Unicode code points value of the first numerical digit of all numerical values for sorting purposes. To sort numerical values correctly, we must define a comparison function with sort().

If we define a comparison function, then a pair of values from the array will be repeatedly sent to the function until all elements of the array are processed. In the comparison function, we thus write a statement considering the pair of values passed to it so that the function returns any of the following three values: <0, =0, or >0.
  • When the function returns value <0, the second value (of the pair of array values sent to the function) is larger than the first value and hence must be pushed down the sorting order. 
  • When the function returns value >0, the first value is larger than the second value, so it must be pushed down the sorting order.
  • When the function returns value =0, it means there is no need to change the sort order since the two values are same.
$(document).ready(function() {
  var list= [ 45, 32, 98, 24, 16, 9, 3];
  $('#allnumber').html(list.join(""));
  list = list.sort(function(a,b){
        return a-b;
    });
  $('#sorted').html(list.join(""));
})
See result below.


See Complete Code
Hope you find this post useful.

Feel free to contact me for any help related to jQuery, I will gladly help you.

Credit : jQuery Recipes
Read more...

Wednesday, November 30, 2011

Avoid jQuery.Post(), use jQuery.ajax()

Well, as you are aware that there are many ways to make an ajax call. If you don't know then do read "How to Make jQuery AJAX calls". Okay, hope you have gone through the article. So 2 very common ways are jQuery.Post() and jQuery.get().jQuery post() is for to make a post request and jQuery get() is to make a get request. That's the only difference between jQuery Post() and jQuery get().

Related Post:

These methods are very popular for ajax call because they are simple to write and easy to remember the syntax as well. But you are making a mistake over here. 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. Okay, why do I say this? Let's take a look at the signature of jQuery post().
$.post({
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

The parameters are,
url (String): The URL of the page to load.
data (Map): Key/value pairs that will be sent to the server.
success (Function): A callback function that is executed if the request succeeds.
dataType: The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).

Looking at above parameters, there only a single callback function that will be executed when the request is complete (and only if the response has a successful response code). What if your request fails? There is no error handling. oh... So what should be done?

Well, jQuery provides another method to perform an ajax call which is jQuery.ajax(). This is jQuery's low-level AJAX implementation. See $.get, $.post etc. for higher-level abstractions that are often easier to understand and use, but don't offer as much functionality (such as error callbacks).
jQuery.ajax(url [, settings] )
There are various settings options available for this method. For complete list visit http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings

This method provides callback for success, error and complete. So which means that we can handle error, success and also perform any operation when the ajax request is complete.
$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  error : error,
  complete : complete,
  dataType: dataType
});
I strongly recommned that it is always better to use jQuery.ajax() over $.post() and $.get(). Having said that, does not mean that $.post() and $.get() are outdatted. If you are using jQuery 1.5 or above, you can still handle the error with $.post() and $.get().

From jQuery official documentation

The Promise interface in jQuery 1.5 also allows jQuery's Ajax methods, including $.post(), to chain multiple .success(), .complete(), and .error() callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.
// Assign handlers immediately after making the request,
    // and remember the jqxhr object for this request
    var jqxhr = $.post("example.php", function() {
      alert("success");
    })
    .success(function() { alert("second success"); })
    .error(function() { alert("error"); })
    .complete(function() { alert("complete"); });

    // perform other work here ...

    // Set another completion function for the request above
    jqxhr.complete(function(){ alert("second complete"); });
So that means that we can still handle the errors using $.post() as well.

But I still recommened $.ajax() method as it gives these options straight away where on the other side, using $.post() one is handling using deferred object.

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Monday, November 28, 2011

Tips to use jQuery selectors efficiently

It is pretty important to understand how to write efficient element selection statement. One has to be very careful while jquery selector statement. Below are some tips on how to use your jQuery selectors efficiently.

1. Always try to use ID as selector

You can use ID as selector in jQuery. See below jQuery code.
$("#elmID");
When IDs are used as selector then jQuery internally makes a call to getElementById() method of Java script which directly maps to the element.

When Classes are used as selector then jQuery has to do DOM traversal.So when DOM traversal is performed via jQuery takes more time to select elements. In terms of speed and performance, it is best practice to use IDs as selector.

2. Use class selector with tags

You can use CSS classes as selector. For example, to select elements with "myCSSClass" following jQuery code can be used.
$(".myCSSClass");
As said earlier, when classes are used DOM traversal happens. But there could be a situation where you need to use classes as selector. For better performance, you can use tag name with the class name. See below
$("div.myCSSClass");
Above jQuery code, restricts the search element specific to DIV elements only.

3. Keep your selector simple, don't make it complex

Avoid complex selectors. You should use make your selectors simple, unless required.
$("body .main p#myID em");
Instead of using such a complex selector, we can simplify it. See below.
$("p#myID em");

4. Don't use your selector repeatedly.

See below jQuery code. The selectors are used thrice for 3 different operation.
$("#myID").css("color", "red");
$("#myID").css("font", "Arial");
$("#myID").text("Error occurred!");
The problem with above code is, jQuery has to traverse 3 times as there are 3 different statements.But this can be combined into a single statement.
$("p").css({ "color": "red", "font": "Arial"}).text("Error occurred!");  

5. Know how your selectors are executed

Do you know how the selectors are executed? 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"); 

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Thursday, October 6, 2011

jQuery Performance tips & tricks from jQuery By Example


  • Always use the latest version of jQuery as your website will be benefited from performance improvement done by the jQuery team in latest release. Learn "How to always reference latest version of jQuery
  • Be smart while using selectors. As there are many ways to select element using selectors but that doesn't mean that all are equal. Always try to use ID and Element as selector as they are very fast. Even the class selectors are slower than ID selector. Read more about jQuery selector.
  • Use IDs instead of Classes as selector. Read here why?
  • Always Minimize or Minify your JavaScript Code
  • Always use the compressed version of jQuery. Read "Why to use compressed version of jQuery".
  • Use CACHING to store selection so that it can be used later on. This will improve the performance.
  • Just for the sake of completing the task, don't repeat your code as it increases the lines of code and reduces performance.
  • Don't use jQuery unless it is not necessary.

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Monday, September 26, 2011

Run JavaScript only after page is completely loaded

Before we got into the actual problem it is important to know and understand the fundamental difference between DOM loading and Page Loading. When we say DOM loading that means all the DOM elements are completely loaded but it is quite possible that some of the elements like images are not loaded completely. When we say "Page loading" which means that along with all the DOM elements, other elements like images are also loaded completely.

jQuery document.ready() gets called immediately after DOM elements are loaded but window.onload() which is Javascript event gets called when page is completely loaded. Read "Is window.onload is different from document.ready()"

So sometimes you may encounter a situation where you need to run the Javascript code once your page is loaded completely. So how do you achieve that? Well, the solutions is combination of jQuery and JavaScript. The solution is to bind the window.onload event in document.ready().
$(window).bind("load", function() {
   // code here
});

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, August 2, 2011

Mostly asked jQuery interview questions list

jQuery is rocking and it has become so popular that it is used almost by every developer. As it has already become more popular, interviewers tend to ask jQuery questions in interview. Below is the list of questions which are asked in almost every jQuery interview. Before you go further, please read my previous article published already about jQuery interview question.


Related Post:
Okay, so I assume that you have read the above article. Let's see some more jQuery interview questions.
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Monday, March 7, 2011

Is window.onload is different from document.ready()

window.onload() is traditional Java script code which is used by developers from many years. This event is gets called when the page is loaded. But how this is different from jQuery document.ready() event?

Well, the main difference is that document.ready() event gets called as soon as your DOM is loaded. It does not wait for the contents to get loaded fully. For example, there are very heavy images on any web page and takes time to load. If you have used window.onload then it will wait until all your images are loaded fully, hence it slows down the execution. On the other side, document.ready() does not wait for elements to get loaded.

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Thursday, February 24, 2011

jQuery empty() vs remove()

jQuery provides 2 methods empty() and remove() to remove the elements from DOM. I have seen the programmers getting confused between both the methods.

empty() method removes all the child element of the matched element where remove() method removes set of matched elements from DOM. Confused? Let me explain you with an example.
There are 2 div elements "dvParent" and "dvChild".
<div id="dvParent">
     Parent Div
    <div id="dvChild">
    <p> jQuery By Example: Demo of empty() vs remove() method.
    </div>
</div>
Now when we call empty() method on "dvChild", then it will remove all the child element of div.
 $('#dvChild').empty();
Result will be:
<div id="dvParent">
     Parent Div
    <div id="dvChild">
    </div>
</div>
See live Demo and Code.
Now when remove() method is called on "dvChild" element then it will not only remove the child element but it will also remove the "dvChild" element from DOM.
 $('#dvChild').remove();
Result will be:
<div id="dvParent">
     Parent Div
</div>
See live Demo and Code.
So the difference between both the method is that empty() remove only the child element of the element on which the method is called where remove() method removes not only the child but also the element on which it is called.

Feel free to contact me for any help related to jQuery. I will gladly help you.
Read more...

Friday, September 3, 2010

What is jQuery.noConflict()

What is jQuery.noConflict()? Well, jQuery is popular because there are plenty of useful, simple and easy to use plugins. But while using jQuery plugins, sometimes we include other libraries like prototype, mootools, YUI etc. The problem comes when one or more other libraries are used with jQuery as 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().

How to use it?

<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
     jQuery.noConflict();
     // Use jQuery via jQuery(...)
     jQuery(document).ready(function(){
       jQuery("div").hide();
     });  
     // Use Prototype with $(...), etc.
     $('someid').hide();
</script>
When .noConflict() is called then jQuery returns $() to its previous owner and you will need to use jQuery() instead of shorthand $() function. In this case, "jQuery" will be used in rest of the code. You won't be able to take advantage of shorthand.

There is another option if you want to take advantage of shorthand.
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
     var $j = jQuery.noConflict();
     // Use jQuery via jQuery(...)
     $j(document).ready(function(){
       $j("div").hide();
     });  
     // Use Prototype with $(...), etc.
     $('someid').hide();
</script>
But you still love $() and don't want to lose it. So what to do? But there is a solution for this also.
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
     jQuery.noConflict();
     // Put all your code in your document ready area
     jQuery(document).ready(function($){
       // Do jQuery stuff using $
       $("div").hide();
     });
     // Use Prototype with $(...), etc.
     $('someid').hide();
</script>
What you need to do is in jQuery(document).ready() put function($) and now you use $ for your jQuery code.

Note: All the above examples are taken from here.

Feel free to contact me for any help related to jQuery. I will gladly help you.
Read more...

Tuesday, August 31, 2010

jQuery Tip - How to check if element is empty

In this post, I will show you a simple tip to check or verify that the element that you are accessing in jQuery is empty or not. jQuery provides a method to get and set html of any control. Check these articles for more details.


Earlier I had posted about How to check element visible or hidden using jQuery, Difference between empty() vs remove() and Don't use jQuery.size() to count number of element. And in this post, find jQuery way to check if element is empty.

We will use the same html() attribute to determine whether the element is empty or not.
$(document).ready(function() {
  if ($('#dvText').html()) {
    alert('Proceed as element is not empty.');
  }
  else
  {
    alert('Element is empty');
  }
});
Declare a div element "dvText" with no content like this.
<div id="dvText"></div>
See live Demo and Code.
But there is a problem here. If you declare your div like below given code, above jQuery code will not work because your div is no more empty. By default some spaces gets added.
<div id="dvText">
</div>
See live Demo and Code.
So what's the solution? Well, I had posted about "How to remove space from begin and end of string using jQuery", so we will use the trim function to trim the spaces from the begin and end of the html() attribute.
$(document).ready(function() {
  if ($('#dvText').html().trim()) {
    alert('Proceed as element is not empty.');
  }
  else
  {
    alert('Element is empty');
  }
});
See live Demo and Code.
Hope this helps!!!!

Feel free to contact me for any help related to jQuery. I will gladly help you.
Read more...

Saturday, August 28, 2010

Difference between $(this) and 'this' in jQuery

Before writing this post, I was also confused about '$(this)' and 'this' in jQuery. I did some R&D and found out the difference between both of them. Let's first see how do we use them.
$(document).ready(function(){
    $('#spnValue').mouseover(function(){
       alert($(this).text());
  });
});
$(document).ready(function(){
    $('#spnValue').mouseover(function(){
       alert(this.innerText);
  });
});
Got any idea about the difference?

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.

In the second example, I have to use innerText() to show the text of the span element as this keyword is not a jQuery object yet. So I have to use the native JavaScript to get the value of span element. But once it is wrapped in $() then jQuery method text() is used to get the text of Span.

So the summary is $(this) is a jQuery object and you can use the power and beauty of jQuery, but with 'this' keyword, one need to use native JavaScript.

Feel free to contact me for any help related to jQuery. I will gladly help you.
Read more...