Friday, September 5, 2014

Iframe image upload php

You can download the source code

Index.php

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <title>Uploader</title>
   <link href="style/style.css" rel="stylesheet" type="text/css" />

<script language="javascript" type="text/javascript">
<!--
function startUpload(){
      document.getElementById('f1_upload_process').style.visibility = 'visible';
      document.getElementById('f1_upload_form').style.visibility = 'hidden';
      return true;
}

function stopUpload(success){
      var result = '';
      if (success == 1){
         result = '<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
      }
      else {
         result = '<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
      }
      document.getElementById('f1_upload_process').style.visibility = 'hidden';
      document.getElementById('f1_upload_form').innerHTML = result;
      document.getElementById('f1_upload_form').style.visibility = 'visible';      
      return true;   
}
//-->
</script>   
</head>
<body>
       <div id="container">
            <div id="header"><div id="header_left"></div>
            <div id="header_right"></div></div>
            <div id="content">
                <form action="upload.php" method="post" enctype="multipart/form-data" target="upload_target" onSubmit="startUpload();" >
                     <p id="f1_upload_process" style="visibility:hidden;">Loading...<br/><img src="loading.gif" /><br/></p>
                     <p id="f1_upload_form" align="center"><br/>
                         <label>File:  
                              <input name="myfile" type="file" size="30" />
                         </label>
                         <label>
                             <input type="submit" name="submitBtn" class="sbtn" value="Upload" />
                         </label>
                     </p>
                     <iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe>
                 </form>
             </div>             
         </div>

</body>   

</html>
---------------------------

Upload.php

<?php
   // Edit upload location here
   $destination_path = getcwd().DIRECTORY_SEPARATOR;

   $result = 0;

   $target_path = $destination_path . basename( $_FILES['myfile']['name']);

   if(@move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
      $result = 1;
   }

   sleep(1);
?>

<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>);</script>   

Thursday, September 4, 2014

Extracting ZIP file directories in PHP

Here is the code.

<?php  $toDir= getcwd();
$fromFile = "joomlacomponent.zip";
if (!file_exists($toDir))
mkdir($toDir, 0777);
if (class_exists('ZipArchive', false))
{
$zip = new ZipArchive();
if ($zip->open($fromFile) === true AND $zip->extractTo($toDir) AND $zip->close())
return true;
return false;
}
die();
?>

Deleting all files from a folder using php

Here is the code to this.
<?php
function deleteDirectory($dirPath) {
    if (is_dir($dirPath)) {
        $objects = scandir($dirPath);
        foreach ($objects as $object) {
            if ($object != "." && $object !="..") {
                if (filetype($dirPath . DIRECTORY_SEPARATOR . $object) == "dir") {
                    deleteDirectory($dirPath . DIRECTORY_SEPARATOR . $object);
                } else {
                    unlink($dirPath . DIRECTORY_SEPARATOR . $object);
                }
            }
        }
    reset($objects);
    rmdir($dirPath);
    }
}

echo deleteDirectory("old");

?>

Creating a zip file with PHP

I recently had a requirement to create a zip file from a number of files created within my application.

Code Is bellow.

<?php
//include "class.recursivezip.php";
class recursiveZip
{
    /**
     * Recursively reads a directory and compress files 
     * 
     * @param file $src source directory
     * @param file $zip recursively adds file
     * @param file $path the file path
     */
    private function recursive_zip($src,&$zip,$path) {
        // open file/directory
        $dir = opendir($src);
        // loop through the directory 
        while(false !== ( $file = readdir($dir)) ) {
            // skip parent (..) and root (.) directory
            if (( $file != '.' ) && ( $file != '..' )) {
                    // if directory found again, call recursive_zip() function again
                    if ( is_dir($src . '/' . $file) ) {
                            $this->recursive_zip($src . '/' . $file,$zip,$path);
                    }
                    else {
                            // add files to zip
                            $zip->addFile($src . '/' . $file,substr($src . '/' . $file,$path));
                    }
            }
        }
        closedir($dir);
    }

    /**
     * Perform compression
     * 
     * @param file $source source file/direcctory for compress
     * @param file $dst destination directory where zip file will be created
     * @return zip file / folder
     */        
    public function compress($src,$dst=''){
        
        // check zip extension loaded or not 
        // and
        // check soure file/directory exists or not
        if (!extension_loaded('zip') || !file_exists($src)) {
            return false;
        }        
        
        // remove last slash (/) from source directory / destination directory
        if(substr($src,-1)==='/'){
            $src=substr($src,0,-1);        
        }
        if(substr($dst,-1)==='/'){
            $dst=substr($dst,0,-1);           
        }
        $path=strlen(dirname($src).'/');
        //$filename=substr($src,strrpos($src,'/')+1).'.zip';
        $filename=substr($src,strrpos($src,'/')).'.zip';
        $dst=empty($dst)? $filename : $dst.'/'.$filename;
        @unlink($dst);

        // create zip     
        $zip = new ZipArchive;
        $res = $zip->open($dst, ZipArchive::CREATE);
        if($res !== TRUE){
            echo 'Error: Unable to create zip file';
            exit;
        }
        if(is_file($src)){
                $zip->addFile($src,substr($src,$path));
        }
        else{
            if(!is_dir($src)){
                $zip->close();
                @unlink($dst);
                echo 'Error: File not found';
                exit;
            }
            $this->recursive_zip($src,$zip,$path);
        }
        $zip->close();
        return $dst;
    }
} // end class file
 
 
 
//------- for mac ------------------
    // Always use absolute path
$src=$_SERVER['DOCUMENT_ROOT']."/";
    $dst=$_SERVER['DOCUMENT_ROOT'];
$z= new recursiveZip();
echo $z->compress($src,$dst);

?>

Sunday, May 18, 2014

Latest jQuery interview questions and answers

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.
1
$(document).ready(function(){
2
});
Over here $ sign can be replaced with "jQuery" keyword.
1
jQuery(document).ready(function(){
2
});
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().
1
jQuery.noConflict();
2
// Use jQuery via jQuery(...)
3
jQuery(document).ready(function(){
4
   jQuery("div").hide();
5
});
You can also use your own specific character in the place of $ sign in jQuery.
1
var $j = jQuery.noConflict();
2
// Use jQuery via jQuery(...)
3
$j(document).ready(function(){
4
   $j("div").hide();
5
});
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.
We can have more than one document.ready() function in a page where we can have only one body onload function.
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.
Production
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. Google.
2. Microsoft
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
1
<script type="text/javascript"
2
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
3
</script>
Code to load jQuery Framework from Microsoft CDN
1
<script type="text/javascript"
2
    src="http://ajax.microsoft.com/ajax/jquery/jquery-1.9.1.min.js">
3
</script>
Code to load jQuery Framework from jQuery Site(EdgeCast CDN)
1
<script type="text/javascript"
2
    src="http://code.jquery.com/jquery-1.9.1.min.js">
3
</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.
1
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
2
<script type="text/javascript">
3
if (typeof jQuery == 'undefined')
4
{
5
  document.write(unescape("%3Cscript src='Scripts/jquery.1.9.1.min.js' type='text/javascript'%3E%3C/script%3E"));
6
}
7
</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,
1
$('#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".
1
$("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.
1
$(document).ready(function(){
2
    $('#spnValue').mouseover(function(){
3
       alert($(this).text());
4
  });
5
});
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.
1
$(document).ready(function(){
2
    $('#spnValue').mouseover(function(){
3
       alert(this.innerText);
4
  });
5
});
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.
1
$(document).ready(function(){
2
    if ($('#element').is(':empty')){
3
       //Element is empty
4
  }
5
});
And the second way is using the "$.trim()" method.
1
$(document).ready(function(){
2
     if($.trim($('#element').html())=='') {
3
       //Element is empty
4
  }
5
});
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.
1
$(document).ready(function(){
2
    if ($('#element').length > 0){
3
       //Element exists
4
  });
5
});
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:
1
(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,
1
$("btnClick").click(function(){
2
  $("#dvBox").animate({height:"100px"});
3
});
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,
1
$('#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.
1
$(document).ready(function(){
2
  $('#btnClone').click(function(){
3
     $('#dvText').clone().appendTo('body');
4
     return false;
5
  });
6
});
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.
1
$(document).ready(function(){
2
   $("#btnClone").bind('click', function(){
3
     $('#dvClickme').clone(true).appendTo('body');
4
  });
​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.
1
$("p").click(function(event){
2
  event.stopImmediatePropagation();
3
});
4
$("p").click(function(event){
5
  // This function won't be executed
6
  $(this).css("background-color", "#f00");
7
});
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.
1
$(document).ready(function() {
2
    $("#btnDummy").one("click", function() {
3
        alert("This will be displayed only once.");
4
    });
5
});​
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.
1
<script type='text/javascript' src='js/jquery_1.9.1.min.js'></script>
2

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

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

2
$.holdReady(true);
3
$.getScript("myplugin.js", function() {
4
     $.holdReady(false);
5
});
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.
1
​$(document).ready(function(){
2
    $('#dvContent').addClass('dummy');
3
    $('#dvContent').css('color', 'red');
4
    $('#dvContent').fadeIn('slow');
5
});​
The above jQuery code sample can be re-written using chaining. See below.
1
​$(document).ready(function(){
2
    $('#dvContent').addClass('dummy')
3
          .css('color', 'red')
4
          .fadeIn('slow');  
5
});​
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.
1
$("#myID").css("color", "red");
2
//Doing some other stuff......
3
$("#myID").text("Error occurred!");
4

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,
1
var $myElement = $("#myID").css("color", "red");
2
//Doing some other stuff......
3
$myElement.text("Error occurred!");
4

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.
1
var propCollection = $("#dvBox").css([ "width", "height", "backgroundColor" ]);
In this case, the propCollection will be an array and it will look something like this.
1
{
2
  width: "100px",
3
  height: "200px",
4
  backgroundColor: "#FF00FF"
5
}
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.
1
<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.

UI Developer Interview Questions and Answers

What is a Cookie?
A cookie is a variable that is stored on the visitor’s computer. Each time the same computer requests a page with a browser, it will send the cookie too. With JavaScript, you can both create and retrieve cookie values.

Examples of cookies:

Name cookie – The first time a visitor arrives to your web page, he or she must fill in her/his name. The name is then stored in a cookie. Next time the visitor arrives at your page, he or she could get a welcome message like “Welcome John Doe!” The name is retrieved from the stored cookie
Date cookie – The first time a visitor arrives to your web page, the current date is stored in a cookie. Next time the visitor arrives at your page, he or she could get a message like “Your last visit was on Tuesday August 11, 2005!” The date is retrieved from the stored cookie
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}
<!DOCTYPE html>
<html>
<head>
<script>
function getCookie(c_name)
{
var c_value = document.cookie;
var c_start = c_value.indexOf(” ” + c_name + “=”);
if (c_start == -1)
{
c_start = c_value.indexOf(c_name + “=”);
}
if (c_start == -1)
{
c_value = null;
}
else
{
c_start = c_value.indexOf(“=”, c_start) + 1;
var c_end = c_value.indexOf(“;”, c_start);
if (c_end == -1)
{
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? “” : “; expires=”+exdate.toUTCString());
document.cookie=c_name + “=” + c_value;
}

function checkCookie()
{
var username=getCookie(“username”);
if (username!=null && username!=””)
{
alert(“Welcome again ” + username);
}
else
{
username=prompt(“Please enter your name:”,””);
if (username!=null && username!=””)
{
setCookie(“username”,username,365);
}
}
}
</script>
</head>
<body onload=”checkCookie()”>
</body>
</html>

1. What is JavaScript?
A2:JavaScript is a platform-independent,event-driven, interpreted client-side scripting and programming language developed by Netscape Communications Corp. and Sun Microsystems.

2. How is JavaScript different from Java?
JavaScript was developed by Brendan Eich of Netscape; Java was developed at Sun Microsystems. While the two languages share some common syntax, they were developed independently of each other and for different audiences. Java is a full-fledged programming language tailored for network computing; it includes hundreds of its own objects, including objects for creating user interfaces that appear in Java applets (in Web browsers) or standalone Java applications. In contrast, JavaScript relies on whatever environment it’s operating in for the user interface, such as a Web document’s form elements.

7. How to detect the operating system on the client machine?
In order to detect the operating system on the client machine, the navigator.appVersion
string (property) should be used.

10. What are JavaScript types?
Number, String, Boolean, Function, Object, Null, Undefined.

11. How do you convert numbers between different bases in JavaScript?
Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt (“3F”, 16);

12. How to create arrays in JavaScript?
We can declare an array like this
var scripts = new Array();

14. What is a fixed-width table and its advantages?
Fixed width tables are rendered by the browser based on the widths of the columns in the first row, resulting in a faster display in case of large tables. Use the CSS style table-layout:fixed to specify a fixed width table.
If the table is not specified to be of fixed width, the browser has to wait till all data is downloaded and then infer the best width for each of the columns. This process can be very slow for large tables.

17. Where are cookies actually stored on the hard disk?
This depends on the user’s browser and OS.
In the case of Netscape with Windows OS,all the cookies are stored in a single file called

cookies.txt
c:Program FilesNetscapeUsersusernamecookies.txt
In the case of IE,each cookie is stored in a separate file namely username@website.txt.
c:WindowsCookiesusername@Website.txt
23. What is negative infinity?
It’s a number in JavaScript, derived by dividing negative number by zero.

25. What is the data type of variables of in JavaScript?
All variables are of object type in JavaScript.

26. Methods GET and POST in HTML forms – what’s the difference?.
GET: Parameters are passed in the querystring. Maximum amount of data that can be sent via the GET method is limited to about 2kb.
POST: Parameters are passed in the request body. There is no limit to the amount of data that can be transferred using POST. However, there are limits on the maximum amount of data that can be transferred in one name/value pair.

31. Are Java and JavaScript the Same?
No.java and javascript are two different languages.
Java is a powerful object – oriented programming language like C++,C whereas Javascript is a
client-side scripting language with some limitations.

49. How about 2+5+”8″?
Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, it’s concatenation, so 78 is the result.

36. What does “1″+2+4 evaluate to?
Since 1 is a string, everything is a string, so the result is 124.

68. What is the difference between undefined value and null value?
(i)Undefined value cannot be explicitly stated that is there is no keyword called undefined whereas null value has keyword called null
(ii)typeof undefined variable or property returns undefined whereas typeof null value returns object

113. decodeURI(), encodeURI()
Many characters cannot be sent in a URL, but must be converted to their hex encoding. These functions are used to convert an entire URI (a superset of URL) to and from a format that can be sent via a URI.

var uri = “http://www.google.com/search?q=sonofusion Taleyarkhan”
document.write(“Original uri: “+uri);
document.write(“
encoded: “+encodeURI(uri));

44. What is the difference between an alert box and a confirmation box?
An alert box displays only one button which is the OK button whereas the Confirm box
displays two buttons namely OK and cancel.

Still others modify entire elements (or groups of elements) themselves—inserting, copying, removing, and so on. All of these methods are referred to as “setters,” as they change the values of properties.
A few of these methods—such as .attr(), .html(), and .val()—also act as “getters,” retrieving information from DOM elements for later use.

DOM = Document Object Model

The DOM defines a standard for accessing HTML and XML documents:

“The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.”

Get Content – text(), html(), and val()
Three simple, but useful, jQuery methods for DOM manipulation is:
• text() – Sets or returns the text content of selected elements
• html() – Sets or returns the content of selected elements (including HTML markup)
• val() – Sets or returns the value of form fields
$(“#btn1″).click(function(){
$(“#test1″).text(function(i,origText){
return “Old text: ” + origText + ” New text: Hello world!
(index: ” + i + “)”;
});
});

$(“button”).click(function(){
$(“#w3s”).attr({
“href” : “http://www.w3schools.com/jquery&#8221;,
“title” : “W3Schools jQuery Tutorial”
});
});

• append() – Inserts content at the end of the selected elements
• prepend() – Inserts content at the beginning of the selected elements
• after() – Inserts content after the selected elements
• before() – Inserts content before the selected elements
function appendText()
{
var txt1=”

Text.

“; // Create element with HTML
var txt2=$(“

“).text(“Text.”); // Create with jQuery
var txt3=document.createElement(“p”); // Create with DOM
txt3.innerHTML=”Text.”;
$(“p”).append(txt1,txt2,txt3); // Append the new elements
}

• width() sets or returns the width of an element (includes NO padding, border, or margin).
• height()
• innerWidth() returns the width of an element (includes padding).
• innerHeight()
• outerWidth() returns the width of an element (includes padding and border).
• outerHeight()
• outerWidth(true) returns the width of an element (includes padding and border & margin).
The jQuery load() method is a simple, but powerful AJAX method.

Code:
var myValue = $(‘#MyId’).val();
// get the value in var Myvalue by id
Or for set the value in selected item
Code:
$(‘#MyId’).val(“print me”);
// set the value of a form input

5- How to get the server response from an AJAX request using Jquery?
When invoking functions that have asynchronous behavior We must provide a callback function to capture the desired result. This is especially important with AJAX in the browser because when a remote request is made, it is indeterminate when the response will be received.
Below an example of making an AJAX call and alerting the response (or error):
Code:
$.ajax({
url: ‘pcdsEmpRecords.php’,
success: function(response) {
alert(response);
},
error: function(xhr) {
alert(‘Error! Status = ‘ + xhr.status);
}
});

6- How do you update ajax response with id ” resilts”?
By using below code we can update div content where id ‘results’ with ajax response
Code:
function updateStatus() {
$.ajax({
url: ‘pcdsEmpRecords.php’,
success: function(response) {
// update div id Results
$(‘#results’).html(response);
}
});
}

7- How do You disable or enable a form element?
There are two ways to disable or enable form elements.
Set the ‘disabled’ attribute to true or false:
Code:
// Disable #pcds
$(‘#pcds’).attr(‘disabled’, true);
// Enable #pcds
$(‘#pcds’).attr(‘disabled’, false);
Add or remove the ‘disabled’ attribute:
// Disable #pcds
$(“#pcds”).attr(‘disabled’, ‘disabled’);
// Enable #x
$(“#pcds”).removeAttr(‘disabled’);

8- How do you check or uncheck a checkbox input or radio button?
There are two ways to check or uncheck a checkbox or radio button.
Set the ‘checked’ attribute to true or false.
Code:
// Check #pcds
$(‘#pcds’).attr(‘checked’, true);
// Uncheck #pcds
$(‘#pcds’).attr(‘checked’, false);
Add or remove the ‘checked’ attribute:
// Check #pcds
$(“#pcds”).attr(‘checked’, ‘checked’);
// Uncheck #pcds
$(“#pcds”).removeAttr(‘checked’);

9- How do you get the text value of a selected option?
Select elements typically have two values that you want to access. First there’s the value to be sent to the server, which is easy:
Code:
$(“#pcdsselect”).val();
// => 1
The second is the text value of the select. For example, using the following select box:
Code:

Mr
Mrs
Ms
Dr
Prof

If you wanted to get the string “Mr” if the first option was selected (instead of just “1″), you would do that in the following way:
Code:
$(“#mpcdsselect option:selected”).text();
// => “Mr”

• Is jQuery a library for client scripting or server scripting?
Ans: Client scripting
• Is jQuery a W3C standard?
Ans: No
• What are jQuery Selectors?
Ans: Selectors are used in jQuery to find out DOM elements. Selectors can find the elements via ID, CSS, Element name and hierarchical position of the element.
• The jQuery html() method works for both HTML and XML documents?
Ans: It only works for HTML.
• Which sign does jQuery use as a shortcut for jQuery?
Ans: $(dollar) sign.
• What does $(“div”) will select?
Ans: It will select all the div element in the page.
• What does $(“div.parent”) will select?
Ans: All the div element with parent class.
• What is the name of jQuery method used for an asynchronous HTTP request?
Ans: jQuery.ajax()
jQuery Tip : Always load your jQuery framework from CDN
Here is a quick tip for the day. Always load your jQuery framework from Google, Microsoft or jQuery CDN(Content Delivery Network). As it provides several advantages.

1. You always use the latest jQuery framework.
2. It reduces the load from your server.
3. It saves bandwidth. jQuery framework will load faster from these CDN.
4. 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.

Code to load jQuery Framework from Google CDN
1

3
Code to load jQuery Framework from Microsoft CDN
1

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

3

How to load jQuery locally when CDN fails
There are couple of advantage if you load your jQuery from any CDN. Read my post about “jQuery Tip : Always load your jQuery framework from CDN”. 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. So if you have loaded your jQuery from any CDN and it went down then your jQuery code will stop working and your client will start shouting.

Hang on, there is a solution for this as well. 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.
1
2
3 if (typeof jQuery == ‘undefined’)
4 {
5 document.write(unescape(“%3Cscript src=’Scripts/jquery.1.5.1.min.js’ type=’text/javascript’%3E%3C/script%3E”));
6 }
7
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.

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?
01
02
03
04 jQuery.noConflict();
05 // Use jQuery via jQuery(…)
06 jQuery(document).ready(function(){
07 jQuery(“div”).hide();
08 });
09 // Use Prototype with $(…), etc.
10 $(‘someid’).hide();
11
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.
01
02
03
04 var $j = jQuery.noConflict();
05 // Use jQuery via jQuery(…)
06 $j(document).ready(function(){
07 $j(“div”).hide();
08 });
09 // Use Prototype with $(…), etc.
10 $(‘someid’).hide();
11
But you still love $() and don’t want to lose it. So what to do? But there is a solution for this also.
01
02
03
04 jQuery.noConflict();
05 // Put all your code in your document ready area
06 jQuery(document).ready(function($){
07 // Do jQuery stuff using $
08 $(“div”).hide();
09 });
10 // Use Prototype with $(…), etc.
11 $(‘someid’).hide();
12
What you need to do is in jQuery(document).ready() put function($) and now you use $ for your jQuery code.

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.
1 $(document).ready(function(){
2 $(‘#spnValue’).mouseover(function(){
3 alert($(this).text());
4 });
5 });
1 $(document).ready(function(){
2 $(‘#spnValue’).mouseover(function(){
3 alert(this.innerText);
4 });
5 });
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.

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

Parent Div
jQuery By Example: Demo of empty() vs remove() method.

Now when we call empty() method on “dvChild”, then it will remove all the child element of div.

$(‘#dvChild’).empty();

Result will be:

Parent Div

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:

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

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.

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.

$(function(){

// jQuery methods go here…

});
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.
• Get HTML of any control using jQuery
• Set HTML of any control using jQuery
We will use the same html() attribute to determine whether the element is empty or not.
1 $(document).ready(function() {
2 if ($(‘#dvText’).html()) {
3 alert(‘Proceed as element is not empty.’);
4 }
5 else
6 {
7 alert(‘Element is empty’);
8 }
9 });
Declare a div element “dvText” with no content like this.
1

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

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

1 $(document).ready(function() {
2 if ($(‘#dvText’).html().trim()) {
3 alert(‘Proceed as element is not empty.’);
4 }
5 else
6 {
7 alert(‘Element is empty’);
8 }
9 });

width() vs css(‘width’) and height() vs css(‘height’)
jQuery provides two ways to set width and height of any element. You can set using css or you can use jQuery provided methods. If you want to set width to 100px then
1 $(‘#dvText1′).css(‘width’,’100px’);
1 $(‘#dvText2′).width(100);
Then what is the difference?

The difference lies in datatype. As its clear in code that with css method you need to append ‘px’ to the width value and with width you don’t need to specify.

When you want to read width of any element then css method will return you string value like ’100px’ while width will return an integer value.
1 alert($(‘#dvText1′).css(‘width’));
This return ’100px’.
1 alert($(‘#dvText2′).width());
This returns 100.

So if you want to do any kind of manipulation then width function is the best option.

How to Check element exists or not in jQuery
Have you ever thought that what will happen if you try to access an element using jQuery which does not exist in your DOM? For example, I am accessing “dvText” element in below code and that element does not exists in my DOM.
1 var obj = $(“#dvText”);
2 alert(obj.text());
What will happen?

There could be 2 possibilities. Either an error will be thrown and rest of the code will not get executed OR Nothing will happen.

If you think that error will be thrown then you are wrong. In jQuery, you don’t need to be worried about checking the existence of any element. If element does not exists, jQuery will do nothing.

Then what is this post all about? As post title says “How to Check element exists or not in jQuery”, where you are not worried about element existence as jQuery handles it quite well. Well, Let say there is some long code related to the element you want to execute and you are not sure that element exists or not. jQuery doesn’t throw error but that doesn’t mean that you don’t check the existence. So it’s always better to check the existence. So how do we check it? See below code
1 if ($(‘#dvText’).length) {
2 // your code
3 }
jQuery provides length property for every element which returns 0 if element doesn’t exists else length of the element.

/* The .bind() method attaches the event handler directly to the DOM
element in question ( “#members li a” ). The .click() method is
just a shorthand way to write the .bind() method. */

$( “#members li a” ).bind( “click”, function( e ) {} );
$( “#members li a” ).click( function( e ) {} );

/* The .live() method attaches the event handler to the root level
document along with the associated selector and event information
( “#members li a” & “click” ) */

$( “#members li a” ).live( “click”, function( e ) {} );

/* The .delegate() method behaves in a similar fashion to the .live()
method, but instead of attaching the event handler to the document,
you can choose where it is anchored ( “#members” ). The selector
and event information ( “li a” & “click” ) will be attached to the
“#members” element. */

$( “#members” ).delegate( “li a”, “click”, function( e ) {} );

Bind attaches an event handler only to the elements that match a particular selector. This, expectedly, excludes any dynamically generated elements.

1. $(“#items li”).click(function() {
2. $(this).parent().append(“

New Element
“);
3. });
Live allows for the binding of event handlers to all elements that match a selector, including those created in the future. It does this by attaching the handler to the document. Unfortunately, it does not work well with chaining.
4. // children().next()…etc.
5. $(“li”).live(“click”, function() {
6. $(this).parent().append(“

New Element
“);
7. });
Delegate is a complete replacement for Live(). However, that obviously would have broken a lot of code! Nonetheless, delegate remedies many of the short-comings found in live(). It attaches the event handler directly to the context, rather than the document. It also doesn’t suffer from the chaining issues that live does. There are many performance benefits
8. // to using this method over live().
9. $(‘#items’).delegate(‘li’, ‘click’, function() {
10. $(this).parent().append(‘

New Element
‘);
11. });
12. // By passing a DOM element as the context of our selector, we can make
13. // Live() behave (almost) the same way that delegate()
14. // does. It attaches the handler to the context, not
15. // the document – which is the default context.
16. // The code below is equivalent to the delegate() version
17. // shown above.
18. $(“li”, $(“#items”)[0]).live(“click”, function() {
19. $(this).parent().append(“

New Element
“);
20. });

More Examples of jQuery Selectors
Syntax Description Example
$(“*”) Selects all elements Try it

$(this) Selects the current HTML element Try it

$(“p.intro”) Selects all

elements with class=”intro” Try it

$(“p:first”) Selects the first

element Try it

$(“ul li:first”) Selects the first

element of the first
Try it
$(“ul li:first-child”) Selects the first

element of every
Try it
$(“[href]“) Selects all elements with an href attribute Try it

$(“a[target='_blank']“) Selects all elements with a target attribute value equal to “_blank” Try it

$(“a[target!='_blank']“) Selects all elements with a target attribute value NOT equal to “_blank” Try it

$(“:button”) Selects all elements and elements of type=”button” Try it

$(“tr:even”) Selects all even
elements Try it

$(“tr:odd”) Selects all odd
elements $(“p”).click(function(){ // action goes here!! });

$(document).ready(function(){
$(“#hide”).click(function(){
$(“p”).hide();
});
});
• fadeIn()fade in a hidden element.
• fadeOut()fade out a visible element.
• fadeToggle()faded out, fadeToggle() will fade them in.& faded in, fadeToggle() will fade them out
• fadeTo()fading to a given opacity
$(“button”).click(function(){
$(“#div1″).fadeTo(“slow”,0.15);
$(“#div2″).fadeTo(“slow”,0.4);
$(“#div3″).fadeTo(“slow”,0.7);
});
$(“button”).click(function(){
$(“#div1″).fadeIn();
$(“#div2″).fadeIn(“slow”);
$(“#div3″).fadeIn(3000);
});

• slideDown()
• slideUp()
• slideToggle()
The jQuery animate() method is used to create custom animations.
$(selector).animate({params},speed,callback);

$(“button”).click(function(){
$(“div”).animate({
left:’250px’,
opacity:’0.5′,
height:’150px’,
width:’150px’
});
});
$(“button”).click(function(){
$(“p”).hide(“slow”,function(){
alert(“The paragraph is now hidden”);
});
});
jQuery Method Chaining
$(“#p1″).css(“color”,”red”).slideUp(2000).slideDown(2000);

Empty, Remove, Detach
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.
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.
Difference between body onload() function document.ready() function used in jQuery?

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.
The .bind() method attaches the event handler directly to the DOM element The .click() method is just a shorthand way to write the .bind() method.

$( “#members li a” ).bind( “click”, function( e ) {} );
$( “#members li a” ).click( function( e ) {} );

The .live() method attaches the event handler to the root level document along with the associated selector and event information

$( “#members li a” ).live( “click”, function( e ) {} );

The .delegate() method behaves in a similar fashion to the .live()
method, but instead of attaching the event handler to the document,

$( “#members” ).delegate( “li a”, “click”, function( e ) {} );

1- What is jQuery ?
It’s very simple but most valuable Question on jQuery means jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, animating, event handling, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript. Jquery is build library for javascript no need to write your own functions or script jquery all ready done for you

2- How you will use Jquery means requirement needed for using jquery?
Nothing more need to do just olny download jquery library(.js file) from any of the jquery site Download jquery and just linked with your html pages like all other javascript file

like below :
Code:

3- what the use of $ symbol in Jquery?
$ Symbol is just replacement of jquery means at the place of $ you may use jquery hence $ symbol is used for indication that this line used for jquery

4- How do you select an item using css class or ID and get the value by use of jquery?
If an element of html like

,or any tag have ID MyId and class used MyClass then we select the element by below jquery code

Code:
$(‘#MyId’) for ID and for classs $(‘.MyClass’)
and for value
Code:
var myValue = $(‘#MyId’).val();
// get the value in var Myvalue by id
Or for set the value in selected item
Code:
$(‘#MyId’).val(“print me”);
// set the value of a form input

5- How to get the server response from an AJAX request using Jquery?
When invoking functions that have asynchronous behavior We must provide a callback function to capture the desired result. This is especially important with AJAX in the browser because when a remote request is made, it is indeterminate when the response will be received.
Below an example of making an AJAX call and alerting the response (or error):
Code:
$.ajax({
url: ‘pcdsEmpRecords.php’,
success: function(response) {
alert(response);
},
error: function(xhr) {
alert(‘Error! Status = ‘ + xhr.status);
}
});

7- How do You disable or enable a form element?
There are two ways to disable or enable form elements.
Set the ‘disabled’ attribute to true or false:
Code:
// Disable #pcds
$(‘#pcds’).attr(‘disabled’, true);
// Enable #pcds
$(‘#pcds’).attr(‘disabled’, false);
Add or remove the ‘disabled’ attribute:
// Disable #pcds
$(“#pcds”).attr(‘disabled’, ‘disabled’);
// Enable #x
$(“#pcds”).removeAttr(‘disabled’);

9- How do you get the text value of a selected option?
Select elements typically have two values that you want to access. First there’s the value to be sent to the server, which is easy:
Code:
$(“#pcdsselect”).val();
// => 1
The second is the text value of the select. For example, using the following select box:
Code:

Mr

If you wanted to get the string “Mr” if the first option was selected (instead of just “1″), you would do that in the following way:
Code:
$(“#mpcdsselect option:selected”).text();
// => “Mr”

Q2. Why jQuery?
Ans: Due to following functionality.
1. Cross-browser support (IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+)
2. AJAX functions
3. CSS functions
4. DOM manipulation
5. DOM transversal
6. Attribute manipulation
7. Event detection and handling
8. JavaScript animation
9. Hundreds of plug-ins for pre-built user interfaces, advanced animations, form validation etc.
10. Expandable functionality using custom plug-ins
Q3. 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.
Q8. What are the different type of selectors in Jquery?
Ans: There are 3 types of selectors in Jquery
1. CSS Selector
2. XPath Selector
3. Custom Selector
Q9. Name some of the methods of JQuery used to provide effects?
Ans: Some of the common methods are :
1. Show()
2. Hide()
3. Toggle()
4. FadeIn()
5. FadeOut()
Q10. What is JQuery UI?
Ans: jQuery UI is a library which is built on top of jQuery library. jQuery UI comes with cool widgets, effects and interaction mechanism.
What are features of JQuery or what can be done using JQuery?
Features of Jquery
1. One can easily provide effects and can do animations.
2. Applying / Changing CSS.
3. Cool plugins.
4. Ajax support
5. DOM selection events
6. Event Handling
Why jQuery?
jQuery is very compact and well written JavaScript code that increases the productivity of the developer by enabling them to achieve critical UI functionality by writing very less amount of code.

It helps to

# Improve the performance of the application
# Develop most browser compatible web page
# Implement UI related critical functionality without writing hundreds of lines of codes
# Fast
# Extensible – jQuery can be extended to implement customized behavior
–>