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

Differentiate between $() vs. querySelectorAll() in jQuery

The $() function is similar to the Document method querySelectorAll(): both take a CSS selector as their argument and return an array-like object that holds the elements that match the selector.

The jQuery implementation uses querySelectorAll() in browsers that support it, but there are good reasons to use $() instead of querySelectorAll() in your own code:
  • querySelectorAll() has only recently been implemented by browser vendors, whereas $() works in older browsers as well as new ones.
  • Because jQuery can perform selections “by hand”, the CSS3 selectors supported by $() work in all browsers, not just those browsers that support CSS3.
  • The array-like object returned by $() (a jQuery object) is much more useful than the array-like object (a NodeList) returned by querySelectorAll().

Callback and Functions in jQuery

Unlike many other programming languages, JavaScript enables you to freely pass functions around to be executed at a later time. A callback is a function that is passed as an argument to another function and is executed after its parent function has completed.

Callbacks are special because they patiently wait to execute until their parent finishes. Meanwhile, the browser can be executing other functions or doing all sorts of other work.

Callbacks without Arguments

If a callback has no arguments, you can pass it as given below:

$.get( "myhtmlpage.html", myCallBack );
When $.get() finishes getting the page myhtmlpage.html, it executes the myCallBack() function.
Note: The second parameter the function name (but not as a string, and without parentheses).

Callback with Arguments
Executing callbacks with arguments can be slightly tricky as shown below:

WRONG Code

$.get( "myhtmlpage.html", myCallBack( param1, param2 ) );

This code will not work because the code executes myCallBack( param1, param2 ) immediately and then passes myCallBack()'s return value as the second parameter to $.get().
Our intention is to pass the function myCallBack(), not myCallBack( param1, param2 )'s return value (which might or might not be a function).

RIGHT Code

An anonymous function can be used as a wrapper to defer executing myCallBack() with its parameters.
Notice the use of function() {.
The anonymous function does exactly one thing: calls myCallBack(), with the values of param1 and param2.

$.get( "myhtmlpage.html", function() {
    myCallBack( param1, param2 );
});

When $.get() finishes getting the page myhtmlpage.html, it executes the anonymous function, which executes myCallBack( param1, param2 ).

Basics of jQuery

Create an HTML page:

<!doctype html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Demo</title>
</head>
<body>
    <a href="http://dotnetinterviewcracker.blogspot.com/">Dot Net Interview Cracker</a>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <script>
 
    $( document ).ready(function() {
        $( "a" ).click(function( event ) {
            alert( "Thanks for visiting!" );
        });
    });
 
    </script>
</body>
</html>
 
The src attribute in the <script> element must point to a copy of jQuery. You can download a copy of jQuery from the Downloading jQuery page and store the jquery.js file in the same directory as your HTML file.
OR
You can use jQuery's CDN from MediaTemple:

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
Launching Code on Document Ready

To run code as soon as the document is ready to be manipulated, jQuery has a statement known as the ready event:

$( document ).ready(function() {
    // Your code here.
}); 
 
For example, inside the ready event, you can add a click handler to the link: 
 
$( document ).ready(function() {
    $( "a" ).click(function( event ) {
        alert( "Thanks for visiting!" );
    });
});

Save your HTML file and reload the test page in your browser. Clicking the link should now first display an alert pop-up, then continue with the default behavior of navigating to http://dotnetinterviewcracker.blogspot.com.
For click and most other events, the default behavior can be prevented by calling event.preventDefault() in the event handler:
 
$( document ).ready(function() {
    $( "a" ).click(function( event ) {
        alert( "As you can see, the link no longer took you to dotnetinterviewcracker.blogspot.com" );
        event.preventDefault();
    });
});

Complete Example:

The following example illustrates the click handling code discussed above, embedded directly in the HTML <body>.

Note: It is usually better approach to place your code in a separate JS file and load it on the page with a <script> element's src attribute.

<!doctype html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Demo</title>
</head>
<body>
    <a href="http://dotnetinterviewcracker.blogspot.com/">Dot Net Interview Cracker</a>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <script>
 
    $( document ).ready(function() {
        $( "a" ).click(function( event ) {
            alert( "As you can see, the link no longer took you to dotnetinterviewcracker.blogspot.com" );
            event.preventDefault();
        });
    });
 
    </script>
</body>
</html> 
 
Adding and Removing an HTML class
 
Note: You must place the remaining jQuery examples inside the ready event so that your code executes when the document is ready to be worked on.
 
Step 1: Add some style information into the <head> of the document:
 
<style>
    a.test {
        font-weight: bold;
    }
</style>

Step 2: Add the .addClass() call to the script: 

$( "a" ).addClass( "test" );
All <a> elements are now bold.

Step 3: To remove an existing class, use .removeClass():
$( "a" ).removeClass( "test" );

Introducing Special Effects

jQuery provides some handy special effects to help you make your web sites stand out. Ex.

$( "a" ).click(function( event ) {
    event.preventDefault();
    $( this ).hide( "slow" );
});

This effect slowly disappears the link when clicked. 

What are the various techniques to execute jQuery code?

There are two ways to execute the jQuery code:
  1. As and when the page loads:
    <script language="javascript" type="text/javascript">
$(function () {
$("#div1").css("border", "2px solid green");
});
</script>

OR

<script language="javascript" type="text/javascript">
$("#div1").css("border", "2px solid green");
</script>
Advantage: It doesn’t wait for the whole page to load completely, so in case you want the user to see the effects as soon as the corresponding elements are loaded, you can use this.

Disadvantage: If the element on which jQuery has to execute has not loaded yet, then it will throw an error (or you may not get the desired result). So, you will have to make sure that the element on which you want to work with jQuery is loaded first (you can place your jQuery code right after your HTML element).
  1. After the complete page has loaded: You can wrap your code in .ready function to execute jQuery only when the complete DOM objects (the complete page has been loaded) has loaded.
    <script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#div1").css("border", "2px solid green");
});
</script>
    This is a better and safer way to execute jQuery. This makes sure that jQuery code will execute only if complete page has been loaded in the browser. This eliminates the possibility of any undesired behavior on the page.

What is CDN?

CDN is an acronym for Content Distribution Network or also called Content Delivery Network. It is a group of computers placed at various points connected with network containing copies of data files to maximize bandwidth in accessing the data. In CDN, a client accesses a copy of data nearer to the client location rather than all clients accessing from the one particular server. This helps to achieve better performance of data retrieval by client.
There are two leading CDNs available that host jQuery files:

a) Microsoft – A jQuery file can be loaded from Microsoft AJAX CDN using the following tags in your page:
<script type="text/javascript" language="Javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.1.min.js">
</script>
b) Google – A jQuery file can be loaded from Google CDN using the following tag in your page:
<script type="text/javascript" language="Javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</script> 
Benefits of loading jQuery file from CDN:
  1. The page loads faster as the jQuery file need not be downloaded when the web page is requested.
  2. Since the jQuery file is not loaded from your server, it saves the bandwidth.
  3. Scalability - the CDNs generally place the jQuery file on the servers located at different geographical locations so that they load faster. So irrespective of where your user is browsing your page, your application runs well.
How to load jQuery file in case CDN in not available:
It may happen that the CDN (which you have used) in unavailable. This is the case when you should load your local jQuery file that is available on your server so that all jQuery related functionality still works fine on the web page. Given below is the code to do so:

<!-- START - jQuery Reference -->
<script type="text/javascript" language="Javascript" 
        src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.1.min.js"></script>
    <script type='text/javascript'>//<![CDATA[
        if (typeof jQuery == 'undefined') {
            document.write(unescape("%3Cscript 
        src='/Script/jquery-1.4.1.min.js' type='text/javascript' %3E%3C/script%3E"));
}//]]>
</script>
<!-- END - jQuery Reference -->

Replace the above highlighted path with your own jQuery file path on the server.

How can a developer use jQuery?

jQuery can be download from jquery.com. After downloading the jQuery file, include it in the web page using the following mark-up under the <head></head> tag:

<script type="text/javascript" src="jQuery-1.4.1-min.js"></script>

What is jQuery?

jQuery is a well written JavaScript code. As quoted on official jQuery website, "it is a fast and concise JavaScript Library that simplifies traversal and manipulation of HTML document, event handling, animation, and Ajax interactions with an easy-to-use API that works across a multitude of browsers for rapid web development".

It is a free and open source software. Microsoft has integrated jQuery officially into its IDE Visual Studio 2010 (jQuery intellisense is available in Visual Studio 2010).

jQuery is very compact and well written JavaScript code that increases the productivity of the developer.
  • It helps to develop browser compatible web page and improve the performance of an application.
  • It is fast and concise and helps to implement UI related critical functionality without writing hundreds of lines of codes.
  • It is extensible – jQuery can be extended to implement customized behavior.
  • No need to learn fresh new syntax to use jQuery, knowing simple JavaScript syntax is enough.