J Query Interview Question Answers
1. jQuery Core concept?
Answer: jQuery accepts a string enclosed with double quote (“”) that can contain a CSS selector which is used to match a set of elements on the web page. jQuery code can start with either “jQuery” word or a “$” (dollar symbol). Take a look at below code snippet <script language="javascript" type="text/javascript"> $(function () { jQuery("#div1").css("border", "2px solid red"); }); </script> OR <script language="javascript" type="text/javascript"> $(function () { $("#div1").css("border", "2px solid green"); }); </script> Both above code snippets are functionally same and do the same thing. So you can either user jQuery or $ when you are writing jQuery code.
2. How to Find the Dimensions of an Element?
Answer: You want to determine the space occupied by an element. Solution The width and height methods can be applied to any element, and they are useful for determining the computed width or height of an element. However, they fall short if you need to determine the actual real estate that an element is occupying on the screen. In addition to width and height, jQuery provides the following methods for determining more specific dimensions of an element: innerWidth Returns the width excluding the border and including the padding innerHeight Returns the height excluding the border and including the padding outerWidth Returns the width including both the border and the padding outerHeight Returns the height including the border and including the padding Given the following HTML: <div id="results"></div> <div id="myDiv">Some text.</div> and the following CSS: #myDiv { width:100px; height:30px; padding:10px; border:1px; } you could expect the following: jQuery(document).ready(function() { var $myDiv = jQuery('#myDiv'); var $results = jQuery('#results'); jQuery('<p>Computed width: ' + $myDiv.width() + '</p>') .appendTo($results); // 100 jQuery('<p>Computed height: ' + $myDiv.height() + '</p>') .appendTo($results); // 30 jQuery('<p>Inner width: ' + $myDiv.innerWidth() + '</p>') .appendTo($results); // 120 jQuery('<p>Inner height: ' + $myDiv.innerHeight() + '</p>') .appendTo($results); // 50 jQuery('<p>Outer width: ' + $myDiv.outerWidth() + '</p>') .appendTo($results); // 122 jQuery('<p>Outer height: ' + $myDiv.outerHeight() + '</p>') .appendTo($results); // 52 jQuery('<p>Document outer height: ' + jQuery(document).outerHeight() + '</p>') .appendTo($results); // NaN jQuery('<p>Document inner height: ' + jQuery(document).innerHeight() + '</p>') .appendTo($results); // NaN jQuery('<p>Window outer height: ' + jQuery(window).outerHeight() + '</p>') .appendTo($results); // NaN jQuery('<p>Window inner height: ' + jQuery(window).innerHeight() + '</p>') .appendTo($results); // NaN }); Discussion The innerWidth/innerHeight and outerWidth/outerHeight methods are useful tools for determining the actual dimension that you’re after—the basic width and height methods are of limited use when you are trying to measure the actual real estate that an element with border and padding occupies on the screen. Note that using innerWidth, innerHeight, outerWidth, or outerHeight methods on jQuery(document) or jQuery(window) objects will return NaN
3. How to Attach a Handler to Many Events?
Answer: In many common situations, one needs to bind the same handler function to more than one event (on the same element, that is). You could always do something like this: jQuery('div').click(function(e){ alert('event'); }) .keydown(function(e){ alert('event'); }); That is not such a problem if the function is short, but for longer blocks of code, repeating them over and over won’t be that trivial and is definitely not the best approach. Solution There’s more than a single solution to this simple but recurrent problem. One way to solve it without repeating yourself too much would be as follows: function handler(e){ alert('event'); } jQuery('div').click(handler) .keydown(handler); Defining a function once and then referring to it multiple times is not a bad approach, but there’s an even simpler one provided by jQuery. bind() accepts a list of events separated by spaces. That means you can solve the previous problem like this: jQuery('div').bind'click keydown', function(e){ alert('event'); }); Discussion You can also apply this behavior to unbind() and one(). To unbind a certain function, you need to have a reference to it, so even if you are using the multievent feature, you still need to keep a reference to the handler. If you don’t pass the function to unbind(), then any other event handler bound to that event will be removed as well: function handler(e){ alert('event'); } jQuery('div').bind('click keydown', handler); // ... jQuery('div').unbind('click keydown', handler);
4. What is the difference between jquery.size() and jquery.length ?
Answer: jquery.size() and jquery.length both returns the number of element found in the object. But, jquery.length is faster than jquery.size() because size() is a method but length is a property . So, there is always an overhead in calling a function.
5. What does .size() method of jquery return ?
Answer: .size() method of jquery returns number of element in the object. That means that you can count the number of elements within an object. For example :- $(document).ready(function(){ var Count = $("div").size(); alert(Count); });
6. How to give alert message in jQuery on a Button Click ?
Answer: First, include jQuery in your application. Drop a textbox in your .aspx page:- <input id="inputField" type="text" size="12"/> include a button also:- <asp:Button ID="Button1" runat="server" Text="get"/> Now, here's the script:- <script type="text/javascript"> $(document).ready(function () { $('#Button1').click(function () { alert($('#inputField').attr("value")); }); }); </script> On the click of the button, an alert will be given containing the text in the text box.
7. What is CDN and how jQuery is related to it?
Answer: CDN - It stands for Content Distribution Network or Content Delivery Network. Generally, a group of systems at various places connected to transfer 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. Example : We can load jQuery from Google libraries API <script type="text/javascript" language="Javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"> </script>
8. how to use jQuery for Progressive Enhancement?
Answer: You want to build a site that allows simple task management with a great user experience using animations and Ajax, but you also want to support users who have JavaScript disabled. Solution You can build the site to work without all the flashiness and then unobtrusively add the JavaScript functionality: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="Content-Language" content="en-us" /> <title>Task List</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"> </script> <script type="text/javascript"> $(document).ready( function() { var url = $('form').attr('action'); $(':checkbox').click(function() { $.post(url, this.name + '=1'); $(this).parent().slideUp(function() { $(this).remove(); }); }); $(':submit').hide(); }); </script> </head> <body> <form method="post" action="tasklist.html"> <ul> <li> <input type="checkbox" name="task1" id="task1" /> <label for="task1">Learn jQuery</label> </li> <li> <input type="checkbox" name="task2" id="task2" /> <label for="task2">Learn Progressive Enhancement</label> </li> <li> <input type="checkbox" name="task3" id="task3" /> <label for="task3">Build Great Websites</label> </li> </ul> <input type="submit" value="Mark Complete" /> </form> </body> </html> The input form in this page doesn’t require JavaScript. The user checks off the tasks he has completed and submits the form, and then it would be up to the server to load a new page with the completed tasks removed from the list. Now, we can progressively enhance the page using jQuery: we bind an event handler to the checkboxes that mimics a standard form submit, by getting the submit URL for the form and generating POST data showing that the checkbox was checked. Then we animate the removal of the task to provide feedback to the user. We also hide the submit button because marking tasks complete has become an instantaneous process. Discussion Although few people browse without JavaScript these days, it’s still a good practice when possible to build your pages so they work fine without JavaScript and then use jQuery and JavaScript to enhance them.
9. JQuery is JavaScript Library or JSON Library?
Answer: JQuery is a javascript library not JSON Library. Jquery library is single JavaScript file that contains Common DOM, event effects and Ajax functions. "JQuery is a library of javascript function." For more Info: http://jquery.com/
10. Would it be even faster to use a while loop or a do...while loop?
Answer: You could rewrite the previous loop as follows: var i = −1, n = array.length; while( ++i < n ) { var item = array[i]; // do stuff with item } or: var i = 0, n = array.length; if( i < n ) do { var item = array[i]; // do stuff with item } while( ++i < n ); But neither one is any faster than the more readable for loop. To iterate over an object (not an array), you can use a for..in loop: for( var key in object ) { var item = object[key]; // do stuff with item }
11. How to Position an Element at Its Current Position Absolutely?
Answer: You want to turn a static or relatively positioned element into being absolutely positioned. Solution To accomplish this, we simply get the position of the element and then use it to set the element’s CSS properties accordingly: var $myElement = jQuery('#foo p').eq(0), elPosition = $myElement.position(); $myElement.css({ position : 'absolute', top : elPosition.top, left : elPosition.left }); We can also easily reposition an element relative to its current position: var $myElement = jQuery('#foo p').eq(1), elPosition = $myElement.position(); $myElement.css({ position : 'absolute', top : elPosition.top + 20, left : elPosition.left + 20 });
12. How to disabe All Effects?
Answer: Your user or web application may require that all animations are disabled, but the effect of revealing information or scrolling (or whichever animation type) may still be required. This may be a personal preference, the user may be using a low-resolution device, or it may be because the user finds the animations problematic in their browsing. jQuery has a way to disable all animations from one access point but still supports the animate method and its final value. Solution $.fx.off = true; $(document).ready(function () { $('#animate').click(function () { $('.box').animate({ width: '+=100', height: '+=100' }); }); }); Discussion By setting fx to off using the following line, all animation calls have the same effect as calling css() directly: $.fx.off = true; This can be set at any point and it will disable the animations, which means it can be offered as a user preference. To enable animations again, you simply set the flag to false: $.fx.off = false;
13. How to Position an Element Relative to Another Element?
Answer: You want to position a new element relative to an existing element. Solution: Get the width, height, and offset of the existing element, and use the values to position the new element accordingly. Given the following HTML: <style> #foo { width: 300px; height: 100px; border: 1px solid red; padding: 5px; } #tooltip { border: 1px solid black; padding: 5px; background-color: #fff; </style> <div id="foo">An existing element</div> the following code would add an element as a sibling to the existing element but positioned “inside” the element, 10 pixels from the top and 10 pixels from the left of the existing element’s top-left corner, and with a width 20 pixels less than that of the existing element: jQuery(document).ready(function() { var $foo = jQuery('#foo'), fooPosition = $foo.position(), $tooltip = $('<div id="tooltip">A new element</div>').insertAfter($foo); $tooltip.css({ position : 'absolute', top : fooPosition.top + 10, left : fooPosition.left + 10, width : $foo.width() - 20 }); }); If you wanted to add the new element somewhere else in the page—that is, if you didn’t want it to be a sibling of the existing element—you could adjust your code to look at the offset of the original element rather than the position: jQuery(document).ready(function() { var $foo = jQuery('#foo'), fooOffset = $foo.offset(), $tooltip = $('<div id="tooltip">A new element</div>').appendTo('body'); $tooltip.css({ position : 'absolute', top : fooOffset.top + 10, left : fooOffset.left + ($foo.width() / 2), width : $foo.width() - 20 }); });
14. What are Selectors in jQuery mean ?
Answer: Generally in HTML, if we need to work with any control on a web page we need to find the control. For that we use document.getElementByID or document.getElementByName. But in jquery we do it using Selectors. Using this selectors we can select all the controls as well using a symbol (* ) A sample code snippet can be of this form <script language="javascript" type="text/javascript"> $("*").css("border", "10px red"); </script> This will make all the borders in the web page with a width of 10 pixel and color as red.
15. Do we need to add the JQuery file both at the Master page and Content page as well?
Answer: No, if the Jquery file has been added to the master page then we can access the content page directly without adding any reference to it. This can be done using this simple example <script type="text/javascript" src="jQuery-1.4.1-min.js"></script>
16. How to Make Your Pages Accessible?
Answer: You’re building a web application with complex widgets and lots of Ajax functionality, but you want to accommodate visitors with disabilities. Solution Add keyboard accessibility and Accessible Rich Internet Applications (ARIA) semantics to your widgets. In the following code, the changes to support these features are indicated in bold: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="Content-Language" content="en-us" /> <title>Dialog Demo</title> <style type="text/css"> table { border-collapse: collapse; width: 500px; } th, td { border: 1px solid #000; padding: 2px 5px; } .dialog { position: absolute; background-color: #fff; border: 1px solid #000; width: 400px; padding: 10px; } .dialog h1 { margin: 0 0 10px; } .dialog .close { position: absolute; top: 10px; right: 10px; } </style> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"> </script> <script type="text/javascript"> $(document).ready( function() { function close() { dialog.hide(); $('#add-user').focus(); } var title = $('<h1>Add User</h1>') .attr('id', 'add-user-title'), closeButton = $('<button>close</button>') .addClass('close') .click(close) .appendTo(title), content = $('<div/>') .load('add.html'), dialog = $('<div/>') .attr({ role: 'dialog', 'aria-labelledby': 'add-user-title' }) .addClass('dialog') .keypress(function(event) { if (event.keyCode == 27) { close(); } }) .append(title) .append(content) .hide() .appendTo('body'); $('#add-user').click(function() { var height = dialog.height(), width = dialog.width(); dialog .css({ top: ($(window).height() - height) / 2 + $(document).scrollTop(), left: ($(window).width() - width) / 2 + $(document).scrollLeft() }) .show(); dialog.find('#username').focus(); return false; }); }); </script></head><body> <h1>Users</h1> <a id="add-user" href="add.html">add a user</a> <table><thead> <tr><th>User</th> <th>First Name</th> <th>Last Name</th></tr> </thead> <tbody> <tr><td>jsmith</td> <td>John</td> <td>Smith</td></tr> <tr><td>mrobertson</td> <td>Mike</td> <td>Robertson</td></tr> <tr><td>arodriguez</td> <td>Angela</td> <td>Rodriguez</td></tr><tr> <td>lsamseil</td> <td>Lee</td> <td>Samseil</td> </tr><tr> <td>lweick</td> <td>Lauren</td> <td>Weick</td></tr> </tbody></table></body></html> We’ve added several useful features with just a small amount of additional code: • We added ARIA semantics (role and aria-labelledby) so that assistive technology devices such as screen readers know that our <div> is a dialog and not just additional content on the page. • We placed the keyboard focus in the dialog’s first input field when it opens. This is helpful for all your visitors, sighted and nonsighted alike. • We moved the keyboard focus back to the Add Users link when the dialog closes. • We allowed the dialog to be canceled with the Escape key. Discussion ARIA is a work in progress, so browser and screen reader support for it is still limited. But by adding it now, you’ll be better prepared for those visitors who can use it. And improved keyboard access benefits all your visitors.
17. What is the use of Delegate() Method in jQuery?
Answer: The delegate() method can be used in two ways. 1) If you have a parent element, and you want to attach an event to each one of its child elements, this delegate() method is used. Ex:Un-ordered List Instead of attaching an event to each <li> element, you can attach a single event to <ul> element. Example: $("ul").delegate("li", "click", function(){ $(this).hide(); }); 2) When an element is not available on the current page, this method is used. .live() method is also used for the same purpose but, delegate() method is a bit faster. Example: $("ul").delegate("li", "click", function(){ $(this).hide(); }); This will hide any list items that are not currently available on the page. They may be loaded via an Ajax request and then append to it. Using .bind() or .click() methods, you would have to manually attach events to these new list items once they are added.
18. How to Slide and Fade Elements in and out of View?
Answer: We want to reveal or toggle a block of content into view. This can be triggered by the user clicking some element or can be fired by some other event. Rather than just showing and hiding, which could be jarring visually, we want to create a gradual effect to reveal the content into view. For these solutions, I’ve assumed we want to allow the user to toggle the effect. Solution For reference, if we were just to show the element, our code would be as follows: $(document).ready(function () { $('#animate').click(function () { $('.box').show(); }); ); If we were to toggle the box but just toggle from visible and hidden, we would use the following instead of .show(): $('.box').toggle(); However, our solution wants to be a little more visually engaging than just toggling the display property. So, let’s look at using the slide and fade methods: Slide $(document).ready(function () { $('#animate').click(function () { $('.box').slideToggle('slow'); }); }); Fade Because there’s no opacity toggle function, either we can use a combination of fadeIn and fadeOut: $(document).ready(function () { $('#animate').click(function () { var $box = $('.box'); if ($box.is(':visible')) { $box.fadeOut('slow'); } else { $box.fadeIn('slow'); } }); }); or we can create our own fade toggle animation, using the fadeTo method: $(document).ready(function () { $('#animate').click(function () { $('.box').fadeTo('slow', 'toggle'); }); }); However, I’m of the opinion that it reads better for future maintenance if we use the animate method: $(document).ready(function () { $('#animate').click(function () { $('.box').animate({ opacity : 'toggle' }, 'slow'); }); }); Both If we want to toggle the height and opacity together, we can reuse the previous solution and add the height to toggle at the same time. This would cause the box to fade out and slide up at the same time: $(document).ready(function () { $('#animate').click(function () { $('.box').animate({ opacity : 'toggle', height: 'toggle' }, 'slow'); }); }); Discussion As we can see from the previous solutions, the slide and fade methods are the next step up from the straight show (and hide) and toggle methods. The slide methods come in the following flavors: • slideUp • slideDown • slideToggle The fade methods don’t have an explicit toggle feature, but it can be achieved. Fading has the following methods: • fadeIn • fadeOut • fadeTo With the exception of fadeTo, all these methods take speed as the first parameter and a callback function as the second—both of which are optional. The callback function is executed once the animation is complete, and the context is set to the element the animation ran against; i.e., the this variable is the current element. The reason I would choose to use animate over fadeTo to toggle opacity is that the fadeTo parameters read the wrong way around. If a new developer were coming to the code, using the animate function almost reads as plain English, therefore making it easier to skim and understand what is happening in the code.
19. How to apply Sequential Effects?
Answer: You want an effect to occur on one set of elements after another effect occurs on a different set of elements. This is simple to solve if you just have one other effect to execute, but if you want to apply the effect one-by-one to any number of elements, the code could become difficult to maintain. Solution This solution uses the standard template outlined at the beginning of this chapter, except that we have multiple copies of the div.box element on the page. This solution is designed as such that we can be dealing with any number of div.box elements, from just one single element to many, because the automatic sequence solution can handle them all. Manual callback The basic approach to applying sequential effects would be to use the callback. This would also be used if the next effect is different from the first: $(document).ready(function () { var $boxes = $('.box').hide(); $('#animate').click(function () { $boxes.eq(0).fadeIn('slow', function () { $boxes.eq(1).slideDown('slow'); }); }); }); Automatic sequence This alternative method, based on Dave Methvin’s solution, will repeat in sequence the effect on any number of elements: $(document).ready(function () { var $boxes = $('.box').hide(), div = 0; $('#animate').click(function () { $($boxes[div++] || []).fadeIn('slow', arguments.callee); }); }); Discussion The simple solution uses the callback feature to then step in to the next animation in the sequence. The selector we use targets the first div.box; however, this doesn’t scale because it is expecting there to be two and only two animated elements. Any less and the code breaks. Any more, and some elements will be missed. If we have many more, or even an unknown number of elements we need to animate in sequence, then Dave Methvin’s solution is perfect. There are two tricks to the code. The first is the failover to an empty array: $($boxes[div++] || []) This code increments the index counter, and if the element doesn’t exist, it passes an empty array to jQuery. When the jQuery result set is empty, running an animation doesn’t do anything. Since the result is empty, jQuery doesn’t pass any DOM elements to the chained call, and therefore any callbacks given to the chained method won’t be called either. For example, if we ran the following code, the alert box would never appear—which is a key ingredient to making this recipe work: $('made-up-element').show(function () { alert('will never appear'); }); The second trick to this recipe is the callback argument: arguments.callee arguments is a keyword in JavaScript referring to a local variable that all functions have access to. The arguments object is similar to any array but does not have any of the array methods (such as slice) or properties except length. arguments also contains a reference to the currently executing function in the arguments.callee property. This is useful for recursive function calls, which is exactly how we are using the property in this solution. This solution says to keep incrementing through the $boxes jQuery collection and, on completion of the animation, recursively execute the function. This continues until the <div> index goes beyond the length of the $boxes jQuery collection ($boxes.length), at which point an empty array is used as the jQuery collection, and thus the callback is not executed, causing the code to finish running.
20. How to Slide and Fade Elements Simultaneously?
Answer: When some part of the web page is hidden and is shown to the user only on a specific action, sometimes a simple show/hide isn’t enough. We want to create more pleasing effects for our visitors. Depending on the layout of the page, an instant show/hide effect may not make it entirely clear to the visitor what content was revealed. This is another advantage of sliding an element into view because it gives a visual cue to the visitor where the page layout is changing. Solution Use the animation function to toggle both the height and the opacity at the same time: $(document).ready(function () { $('#animate').click(function () { $('.box').animate({ opacity: 'toggle', height: 'toggle' }); return false; }); }); Discussion Using the animate method allows us to specify exactly which CSS properties we want to animate for the effect. We are also using toggle as the end point value. This way, the animate method takes the current height in the initial state and toggles it to either zero or 100 percent of the initial state. In our example, the initial state of the box is visible. If we want it to slide and fade into view, then we only need to set the display property to none in the stylesheet. Warning: there is no need to set the height to zero in the style; in fact, doing so will mean the animate won’t expand to the correct height because it will toggle back and forth between zero height (from the CSS) and zero height and display none (the final point of slideUp).
21. How to Switch Stylesheets Based on Browser Width?
Answer: You want to change the document’s CSS based on the width of the browser Solutions: There are a few solutions to this problem. One changes the class attribute of the body element, another changes the href attribute of the stylesheet you want to change, and the third includes all size-related stylesheets on the page but enables only one of them at a time. In each case, we’ll create a function that checks the width of the browser and bind that function to the document’s ready event and to the window’s resize event. The checkWidth function will then call the setSize function, which we’ll define based on the approach we’re taking: var checkWidth = function() { var browserWidth = $(window).width(); if (browserWidth < 960) { setSize('small'); } else { setSize('large'); } }; jQuery(document).ready(function() { checkWidth(); $(window).resize(checkWidth); }); The definition of the setSize function depends on how you want to switch styles. Solution 1: Changing the Class on the Body Element var setSize = function(size) { var $body = jQuery('body'); jQuery('body').removeClass('large small').addClass(size); }; Solution 2: Changing the href Attribute of the Stylesheet That’s Responsible for Size-Related Styling Let’s assume you have the following size-related stylesheet in your document: <link rel="stylesheet" type="text/css" id="css_size" href="size-small.css" /> In this case, you would define the setSize function as follows: var setSize = function(size) { var $css = jQuery('#css_size'); $css.attr('href', 'size-' + size + '.css'); }; Note that in this case, the new CSS file is requested from the server, which is likely to cause a brief delay in the style change occurring. For this reason, this is perhaps the least-preferable method. Solution 3: Include All Size-Related Stylesheets in the Page, but Enable Only One at a Time <link rel="stylesheet" type="text/css" class="css_size small" href="size-small.css" /> <link rel="alternate stylesheet" type="text/css" class="css_size large" href="size-large.css" disabled=true/> In this case, you would define the setSize function as follows: var setSize = function(size) { jQuery('link.css_size').each(function() { var $this = $(this); if ($this.hasClass(size)) { $this .removeAttr('disabled') .attr('rel', 'stylesheet'); } else { $this .attr('disabled', true) .attr('rel', 'alternate stylesheet'); } }); }; In this approach, all stylesheets are loaded at page load, and nothing new is fetched when switching from one stylesheet to another. This eliminates the delay caused by solution 2 but it also results in potentially unnecessary HTTP requests if your user is unlikely to need the alternate stylesheets. Discussion There is no definitive answer to which of the three style-switching methods is the best. When choosing a method, you’ll want to consider how likely your users are to need a different stylesheet, how big your size-related stylesheets are, and how you prefer to manage your size-related styles. In many cases, the method from the first solution will be both sufficient and preferable.
22. How to Make Elements Visible by Sliding Them Up?
Answer: You want to slide the content block into view, but the UI design dictates that the content must slide upward when being revealed. The slideUp method would hide the element, reducing the height from the top position. To slide upward, we need to use CSS to position the element and then consider the content that we are revealing. Solution HTML We need to absolutely position the element we are animating to get it to stick to the bottom position so it can animate upward when revealing. To achieve this, we need to wrap the animating element in another <div> (or the element that suits your design) and give it a position: relative style. (This may also be position: absolute. We just need a defined position to trigger the position: abso lute on #revealUp to position relatively to; however, since we want the document to flow normally, we’ve used position: relative.) <div class="box"> <div id="revealUp"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p> </div> </div> CSS Now we need to give the box element a relative position so that we can absolutely position #revealUp relative to it: .box { position: relative; } #revealUp { position: absolute; overflow: hidden; display: none; bottom: 0; background-color: #c00; height: 0; } jQuery We can toggle the #revealUp based on the element’s height. We’re going to longer lengths to animate the height upward (by checking the current height) rather than just using slideToggle()—but we’ll look at why in the discussion: $(document).ready(function () { $('#animate').click(function () { var $box = $('#revealUp'); if ($box.height() > 0) { $box.animate({ height : 0 }); } else { $box.animate({ height : '100%' }); } }); }); Discussion This solution requires that we check the height of the box to then determine how we proceed. Notice how we don’t use slideToggle, which behind the scenes is very similar, if not the same as, using .animate({ height: 'toggle' }). The reason we’re not using the toggle is that for the toggle to work correctly, it needs to capture the real height from somewhere. As the element starts with a height of zero, jQuery has no way to work out what the full height is. If we used slideToggle, the #revealUp element appears briefly as a 1-pixel slither and then disappears again. This is because there’s no real height to animate to. Instead, we determine whether the height is great than zero and then animate the height accordingly. Since the element is nested within another element with position: relative, we can give it a height of 100 percent, and it will grow to fill the space.
23. Is it good to load jquery from CDN(Content delivery network) ?
Answer: Yes, it is always good to load your jquery from content delivery network. It provides some benefits like :- (1) Caching - It means that if any previously visited site by user is using jQuery from Google CDN then the cached version will be used. It will not be downloaded again. (2) Reduces load - It reduces the load on your web server as it downloads from Google server's. Example :- <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"> </script>
24. Caching Your jQuery Objects?
Answer: You’re logging the various properties of the event object for a mousemove event, and the code lags behind because it uses $('.classname') selectors to find and update table cells with the event data. Your page contains this HTML code for the log: <table id="log"> <tr><td>Client X:</td><td class="clientX"></td></tr> <tr><td>Client Y:</td><td class="clientY"></td></tr> <tr><td>Page X:</td><td class="pageX"></td></tr> <tr><td>Page Y:</td><td class="pageY"></td></tr> <tr><td>Screen X:</td><td class="screenX"></td></tr> <tr><td>Screen Y:</td><td class="screenY"></td></tr> </table> and this JavaScript code: $('html').mousemove( function( event ) { $('.clientX').html( event.clientX ); $('.clientY').html( event.clientY ); $('.pageX').html( event.pageX ); $('.pageY').html( event.pageY ); $('.screenX').html( event.screenX ); $('.screenY').html( event.screenY ); }); The page also contains a large number (thousands!) of other DOM elements. In a simpler test page, the code performs fine, but in this complex page it is too slow. Solution Cache the jQuery objects returned by the $(...) calls, so the DOM queries only have to be run once: var $clientX = $('.clientX'), $clientY = $('.clientY'), $pageX = $('.pageX'), $pageY = $('.pageY'), $screenX = $('.screenX'), $screenY = $('.screenY'); $('html').mousemove( function( event ) { $clientX.html( event.clientX ); $clientY.html( event.clientY ); $pageX.html( event.pageX ); $pageY.html( event.pageY ); $screenX.html( event.screenX ); $screenY.html( event.screenY ); }); You may also be able to speed up those selectors considerably; see the next recipe for ways to do that. But simply calling them once each instead of over and over again may be enough of an improvement right there. Discussion One of the classic ways to optimize code is to “hoist” repeated calculations out of a loop so you have to do them only once. Any values that don’t change inside the loop should be calculated one time, before the loop starts. If those are expensive calculations, the loop will then be much faster. This works just as well when the “loop” is a series of frequently fired events such as mousemove and the “calculation” is a jQuery selector. Hoisting the selector out of the event handler makes the event handler respond faster. Of course, if you’re calling multiple selectors inside a loop, that will also benefit from moving them outside the loop in the same manner.
25. How will you Encode/Decode URL in jQuery ?
Answer: In jquery, you can use the following functions to encode and decode url :- encodeURIComponent(url) and decodeURIComponent(url) You have to pass the complete url with parameterized value in the function and in return it will encode/decode you url for you !
26. Why do $clientX and the other variable names begin with the $character?
Answer: a letter of the alphabet. It’s simply a popular convention in jQuery code to use the $ prefix as a reminder that the variable contains a reference to a jQuery object and not, say, a DOM element, because a variable name of $foobar has a visual resemblance to the jQuery operation $('#foobar'). This is especially helpful when you need to use both a jQuery object and its underlying DOM element, e.g.: var $foo = $('#foo'), foo = $foo[0]; // Now you can use the jQuery object: $foo.show(); // or the DOM element: var id = foo.id;
27. How to use jQuery and Ajax togeher?
Answer: You want to make a request to the server for some additional data without leaving the page the visitor is currently on. Solution Here’s a simple Ajax request: (function($) { $(document).ready(function() { $('#update').click(function() { $.ajax({ type: 'GET', url: 'hello-ajax.html', dataType: 'html', success: function(html, textStatus) { $('body').append(html); }, error: function(xhr, textStatus, errorThrown) { alert('An error occurred! ' + ( errorThrown ? errorThrown : xhr.status ); } }); }); }); })(jQuery); Discussion At the core of jQuery’s Ajax architecture is the jQuery.ajax() method. This provides the basis of all browsers to server requests and responses. So, let’s look at this in a little more detail. To initiate a request to the server, a settings object that contains parameters for the request is passed to the $.ajax method. A vast number of options are available, with the most common options of a request being type, url, complete, dataType, error, and success: var options = { type: 'GET' }; The first option that needs to be addressed when starting an Ajax request is the type of HTTP request you’re going to make to the server, which in the majority of cases will be either a GET or POST type: var options = { type: 'GET', url: 'hello-ajax.html', dataType: 'html' }; Next we’ll look at the URL and dataType options. URL is fairly self-explanatory with the following interactions worth noting. When setting the cache option to false, jQuery will append a get variable of _=<random number> (for example /server-ajax-gateway? _=6273551235126), which is used to prevent the browser, proxies, and servers from sending a cached response. Finally, the dataType option specifies the data format that is the expected response from the server. For example, if you’re expecting the server to return XML, then a value of xml would be appropriate: var options = { type: 'GET', url: 'hello-ajax.html', dataType: 'html', error: function(xhr, textStatus, errorThrown) { alert('An error occurred! ' + errorThrown); }, success: function(data, textStatus) { $('body').append( data ); } }; The next two options that we define are two callback methods, one called error and the other called success. They function as they are appropriately titled, with error being called when there is an error with the request and success being called with a successful response (determined if a server response type of 200 is returned). The other common option mentioned is the complete option, which defines a callback to execute upon after either success or error of the response: var options = { type: 'GET', url: 'hello-ajax.html', dataType: 'html', complete: function(xhr, textStatus) { // Code to process response } }; Once the settings have been defined, we can go ahead and execute our request: var options = { type: 'GET', url: 'hello-ajax.html', dataType: 'html', complete: function(xhr, textStatus) { // Code to process response } }; $.ajax( options ); We can also set our options inline: $.ajax({ type: 'GET', url: 'hello-ajax.html', dataType: 'html', complete: function(xhr, textStatus) { // Code to process response } }); Our final solution requests the file hello-ajax.html and appends the contents (html) to the <body> element upon the return of a successful request. If the request fails, the error method is triggered instead, alerting the user with a message: (function($) { $(document).ready(function() { $('#update').click(function() { $.ajax({ type: 'GET', url: 'hello-ajax.html', dataType: 'html', success: function(html, textStatus) { $('body').append(html); }, error: function(xhr, textStatus, errorThrown) { alert('An error occurred! ' + errorThrown); } }); });
28. How to Include All Size-Related Stylesheets in the Page, but Enable Only One at a Time?
Answer: <link rel="stylesheet" type="text/css" class="css_size small" href="size-small.css" /> <link rel="alternate stylesheet" type="text/css" class="css_size large" href="size-large.css" disabled=true/> In this case, you would define the setSize function as follows: var setSize = function(size) { jQuery('link.css_size').each(function() { var $this = $(this); if ($this.hasClass(size)) { $this .removeAttr('disabled') .attr('rel', 'stylesheet'); } else { $this .attr('disabled', true) .attr('rel', 'alternate stylesheet'); } }); }; In this approach, all stylesheets are loaded at page load, and nothing new is fetched when switching from one stylesheet to another. This eliminates the delay caused by solution 2 but it also results in potentially unnecessary HTTP requests if your user is unlikely to need the alternate stylesheets. Discussion There is no definitive answer to which of the three style-switching methods is the best. When choosing a method, you’ll want to consider how likely your users are to need a different stylesheet, how big your size-related stylesheets are, and how you prefer to manage your size-related styles. In many cases, the method from the first solution will be both sufficient and preferable.
29. Can we select a element having a specific class in jQuery ?
Answer: Yes, we can select an element with a specific class, we use the class selector.The class name must contain the prefix as "." (dot). <script language="javascript" type="text/javascript"> $(".class1").css("border", "2px solid red"); </script> Above code will select all the elements of the webpage containing the class as "class1" and apply the css style border width as 2 Pixel, style as solid and color as red.
30. How to Use Object's Methods as Event Listeners?
Answer: You have objects with methods and attributes, and you want to pass those methods (functions) as event handlers. The problem is that once you do this, the method will “lose the reference” to the object, and you have no way of referencing the object within the event handlers. Solution This used to be quite complicated to achieve. It required you to generate closures that would encapsulate the object and then pass them to bind(). Since jQuery 1.3.3, a new parameter has been added to bind(). It allows you to specify an object as the scope or this of the event handler without using function closures. This makes the required code both shorter and faster. You can now pass the object’s method as the function and the object itself as the scope. Discussion Where did the node go? You will surely wonder this sooner or later. I said before that when you pass a scope object to bind(), the this of the event handler will be overridden. This means we can’t retrieve the node as we always do...but the node is not lost. When you pass a scope object to the bind() method, events will be delivered with the this of the event handler set to the scope object. You can still determine the element being delivered to the event by using the event.currentTarget property, which contains a reference to the DOM element. It’s usually not needed because using the this is shorter, but in situations like this, it’s the only way around. The example I’ll create a small example that should illustrate how to use the scope parameter and also show you a situation where it is useful. For the example, we’ll need two objects. Each will have a method that we want to bind as an event handler. These are the objects: function Person(name){ this.name = name; this.married = false; } jQuery.extend( Person.prototype, { whatIsYourName: function(){ alert(this.name); }, updateMarriedState: function(e){ var checkbox = e.currentTarget; this.married = checkbox.checked; } }); var peter = new Person('Peter'); var susan = new Person('Susan'); Let’s suppose we have some sort of form and it has two checkboxes (#c1 and #c2). Each will manipulate the married state of one of our previous objects. jQuery('#c1').bind('change', peter.updateMarriedState, peter); jQuery('#c2').bind('change', susan.updateMarriedState, susan); Thanks to the scope attribute, we don’t need to create new functions for each binding; we can use the objects’ methods instead. The methods don’t even need to be attached to the objects in the first place. You could do something like this: function updatePersonMarriedState(e){ var checkbox = e.currentTarget; this.married = checkbox.checked; } jQuery('#c1').bind('change', updatePersonMarriedState, peter); jQuery('#c2').bind('change', updatePersonMarriedState, susan); As you can see, you’re not really forced to put those functions into the objects’ prototype, and it could actually make more sense to keep them separated. Why should a method belonging to Person know about checkboxes and the node? It’s probably nicer to keep all the specific DOM manipulation apart from the data. In some cases, the object’s method won’t need to know about the node or the event object at all. When this happens, we can bind a method directly, and we won’t be mixing DOM and data at all. If we had to have make two buttons (#b1 and #b2) to display the name of one person when clicked, then it’d be as simple as this: jQuery('#b1').bind('click', peter.whatIsYourName, peter); jQuery('#b2').bind('click', susan.whatIsYourName, susan); It’s worth mentioning that both methods are actually the same: peter.whatIsYourName == susan.whatIsYourName; // true The function is created only once and saved into Person.prototype.
31. How to Create, Operate, and Insert DOM Elements?
Answer: You want to create new DOM elements (or a single element) that are immediately selected, operated on, and then injected into the DOM. Solution If you haven’t figured it out yet, the jQuery function is multifaceted in that this one function performs differently depending upon the makeup of the parameter(s) you send it. If you provide the function with a text string of raw HTML, it will create these elements for you on the fly. For example, the following statement will create an <a> element wrapped inside of a <p> element with a text node encapsulated inside of the <p> and <a> elements: jQuery('<p><a>jQuery</a></p>'); Now, with an element created, you can use jQuery methods to further operate on the elements you just created. It’s as if you had selected the <p> element from the get-go in an existing HTML document. For example, we could operate on the <a> by using the .find() method to select the <a> element and then set one of its attributes. In the case of the following code, we are setting the href attribute with a value of http:// www.jquery.com: jQuery('<p><a>jQuery</a></p>').find('a').attr('href','http://www.jquery.com'); This is great, right? Well, it’s about to get better because all we have done so far is create elements on the fly and manipulate those elements in code. We have yet to actually change the currently loaded DOM, so to speak. To do this, we’ll have to use the manipulation methods provided by jQuery. The following is our code in the context of an HTML document. Here we are creating elements, operating on those elements, and then inserting those elements into the DOM using the appendTo() manipulation method: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/JavaScript"> jQuery('<p><a>jQuery</a></p>').find('a').attr('href','http://www.jquery.com') .end().appendTo('body'); </script> </body> </html> Notice how I am using the end() method here to undo the find() method so that when I call the appendTo() method, it appends what was originally contained in the initial wrapper set. Discussion In this recipe we’ve passed the jQuery function a string of raw HTML that is taken and used to create DOM elements on the fly. It’s also possible to simply pass the jQuery function a DOM object created by the DOM method createElement(): jQuery(document.createElement('p')).appendTo('body'); //adds an empty p element to the page Of course, this could be rather laborious depending upon the specifics of the usage when a string of HTML containing multiple elements will work just fine. It’s also worth mentioning here that we’ve only scratched the surface of the manipulation methods by using the appendTo() method. In addition to the appendTo() method, there are also the following manipulation methods: • append() • prepend() • prependTo() • after() • before() • insertAfter() • insertBefore() • wrap() • wrapAll() • wrapInner()
32. How to upload Files in the Background?
Answer: File upload is part of many web applications but badly supported by browsers. The biggest problem is the lack of feedback of the upload status, while any action of the users disrupts the upload. A simple progress bar could improve the feedback but requires quite some work on the server side, while the problem of disruptive actions remains. Solution To improve the situation, file uploads should be performed in the background. This allows the application to continue accepting other user input. The jQuery form plugin makes it trivial to switch from the native browser upload to Ajax background uploading. With this form: <form id="uploadform"> <input type="file" id="fileupload" name="fileupload" /> <input type="submit" value="Upload!" /> </form> all you need to add is a call to ajaxForm: $("#uploadform").ajaxForm(); However, just doing the upload in the background without any feedback of the completed upload isn’t enough, so we use the success option to display an alert about the successful upload: $("#uploadform").ajaxForm({ success: function() { alert("Upload completed!"); } }); Discussion The ajaxForm method binds itself to the submit event of the form, which allows it to also include the button used to submit the form in the Ajax request. The latter isn’t available when using ajaxSubmit. The ajaxSubmit method is useful on its own when the form submit is handled elsewhere, for example, by the validation plugin. To integrate validation and Ajax submit, ajaxSubmit should be used in the submitHandler option: $("#commentform").validate({ submitHandler: function(form) { $(form).ajaxSubmit({ success: function() { $(form).clearForm(); alert("Thanks for your comment!"); } }); } }); In addition to the alert, the clearForm method, also provided by the form plugin, removes all values from the form. This makes it easy for the user to upload another file.
33. How to set Page Title using jQuery ?
Answer: $(function(){ $(document).attr("title", "Dotnet Funda"); });
34. What is the advantage of using the minified version of JQuery rather than using the conventional one?
Answer: The advantage of using a minified version of JQuery file is Efficiency of the web page increases. The normal version jQuery-x.x.x.js has a file size of 178KB but the minified version jQuery.x.x.x-min.js has 76.7 KB. The reduction in size makes the page to load more faster than you use a conventional jQuery file with 178KB
35. What?s Wrong with $(this)?
Answer: Solution: Save this in a variable before calling setTimeout(): $(document).ready( function() { $('.clicky').click( function() { var element = this; $(element).addClass('clicked'); setTimeout( function() { $(element).removeClass('clicked'); }, 1000 );