Functions Utility in jQuery

Introduction: In this article we are going to discuss about the utility of functions in jQuery and  how they are used to invoke the jQuery features. We will see what will be the execution of the functions and what will be the output whatever the code which is written inside the functions of jQuery. As we will see the definition of the $ variable is the largest point of argument and will look as a conflict when using other libraries on the same page as jQuery. As we know, the $ sign being used as an alias for the jQuery name, which is used for every feature that jQuery exhibits. But other libraries, most notably Prototype, use the $ name as well. Now it will be solved by providing the $.noConflict() utility function by jQuery to relinquish control of the $ name to whatever other library might wish to use it and will discuss about the other functions also. Let see the syntax and the steps of function is as follows:

Step 1: Firstly we have to take a web Application to run the following functions given below.

  • Go to Visual Studio 2010
  • Open the web Application
  • Click Ok.
Web Application

Step 2: Secondly you have to add a new page to the website

  • Go to the Solution Explorer.
  • Right Click o Project name.
  • Select add new item.
  • Add new web page and give it a name.
  • Click OK
Add New Item

New web Page

Step 3: In this step we will discuss about the functions in jQuery one by one.

1. $.noConflict(): This utility function is used to restores control of the $ name back to another library, which will allowing mixed library use on pages using jQuery. Once this function is executed, jQuery features will need to be invoked using the jQuery name rather than the $ name. Which have none  parameters and will returns unddefined. As we know that because $ is an alias for jQuery, all of jQuery's functionality is still available after the application of $.noConflict(), further we can define our own shorter, but non-conflicting, alias for jQuery, such as given below
var $j = jQuery;

Let we will look to the idiom is as follows:

(function($) { /* function body here */ })(jQuery) : If it is difficult to notice that makes your head spin, It's pretty straightforward if odd-looking to those encountering it for the first time.

Part 1: First see by separating the first part of this idiom:

(function($) { /* function body here */ }) : The above code line part declares a function and encloses it in parentheses to make an expression out of it, resulting in a reference to the anonymous function being returned as the value of the expression. We will see that function expects a single parameter, having names $; whatever we will passed to this function can be referenced by the $ identifier within the body of the function.

Part 2: Second part of the idiom is given below let see it

(jQuery): It is used to performs a function call on the anonymous function passing the jQuery object as the argument. As a result, the $ name refers to the jQuery object within the body of the function regardless of whether it's already defined by Prototype or some other library outside of the function. Further we will discuss about the another idioms or the syntax to declare the ready handler that we all know that the syntax given below.

<script type="text/javascript">
   jQuery(function($) {
     alert("Hi to all!");
   });
</script
>

Description: In this we will descibe about the ready handler in this script by passing a function as the parameter to the jQuery function, we declare it as a ready handler. In this above example, here is a single parameter to be passed to the ready handler using the $ identifier. That why because jQuery always passes a reference to jQuery to a ready handler as its first and only parameter, which will guarantees that the $ name refers to jQuery inside the ready handler regardless of the definition $ might have outside the body of the handler.

Example test: In this example we will see that how a In this document, we will import jQuery, which defines the global names jQuery and its alias $. We then redefine the global $ name to a string value "Welcome Friends", which is overriding the jQuery definition. We replace $ with a simple string value for simplicity within this example, but it could be redefined by including another library such as Prototype. We then define the ready handler whose only action is to display an alert showing the value of $.

Code:

<html xmlns="http://www.w3.org/1999/xhtml">
 <head runat="server">
    <title>Hello</title>
 <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
 <script type="text/javascript">
   var $="Welcome Friends"
   jQuery(function () {
     alert("$="+$);
   });
 </script>
 </head>
 <body>
    <form id="form1" runat="server">
    <div>
    </div>
    </form>
 </body>
</
html
>

Output 1:

Output Window

Code: if we pass the $ identifier inside the ready function then the output will be

var $="Welcome Friends"
   jQuery(function ($) {
     alert("$="+$);
   });

Output 2:

output2

2. $.trim(value): This function is used to removes any leading whitespace characters from the passed string and which will return the result.Whitespace characters are defined by this function, if there is any character matching with the JavaScript regular expression \s, which matches not only the space character but also the form feed but also new line, return, tab, and vertical tab characters, as well as the Unicode characters. which have the value name parameter and will be a string parameter and the return value of the function is trimmed string. Let see the small example of using this function to trim the value of a text field in-place which is given below

$("#field").val($.trim($("#field").val()));

3. $.each(container,callback): This is the another function which is used to Iterates over the items in the passed container, invoking the passed callback function for each. Parameters container is an array whose items or an object whose properties are to be iterated over. Further callback is a function which will invoke for each element in the container. If the container is an array, this callback is invoked for each array item if it's an object, the callback is invoked for each object property. The first parameter to this callback is the index of the array element or the name of the object property. The second parameter is the item or property value. The function context (this) of the invocation is also set to the value passed as the second parameter. At last the function will return the container object and the example is given below.

Example:

var arr = ['Hi', 'Hello', 'Welcome'];
   $.each(arr, function (n, value) {
     // write the code what to do.
 });

4. $.grep(array,callback,invert): This is also an utility function used to filter some thing based on pattern then we will use it. Furthrt we might wish to filter through the data looking for items that fall above or below a particular threshold or, perhaps, that match a certain pattern. To perform such type of filtering operation , jQuery provides the $.grep() utility function. In this function we will see that there are the three paarmeters passing in it in which the first parameter name is array which is a traversed array whose data values are examined for collection. The second one name is callback which is a  function whose return value determines if the current datavalue is to be collected. Further we can use a string to be passed as this parameter that's converted into thecallback function. The third one is invert is a boolean type which is specified as true, it inverts the normal operation of the function. At last the function will return the array of collected value.

Example: Let see the example given below.

var bg = $.grep(parry,
function (value) {
    return value.match(/^\d{5}(-\d{4})?$/) != null;
},
true);

5. $.map(array,callback): This is another function utility is used to translating the arrays from one set to another set because data may not be the right format as we all want so to accomplish such type of task  jQuery provide us a $.map() function which will Iterates through the passed array, invoking the callback function for each array item and collecting the return values of the function invocations in a new array. there are two function parameter the first one is array  whose values are to be transformed to values in the new array. The second one is the callback which is also a function whose return values are collected in the new array which will be returned as the result of a call to the $.map() function. And the return type of such type of function is wrapped set. let's see the example given below

Example:

var
str = ['10', '20', '30', '40', 'Str', '60'];
var val = $.map(str, function (value) {
    var res = new Number(value);
    return isNaN(res) ? null : res;
});

6. $.getScript(url,callback): This is also a utility function which is used to load the script dynamically Mostly, perhaps, almost always we will load the external scripts to our page needs from script files when the page loads via <script> tags in the <head> of the page. But every now and again, we might want to load some script after the fact under script control. By keep it in mind regarding of why we might want to dynamically load new script into the page, jQuery provides the $.getScript() utility function to make it easy. In this script function there are two parameters first one is url which is used to fetch the script file and the second one is callback wich is being able to invoke an optional function after the script resource has been loaded and evaluated and it will used the XHR instance to fetch the script as returning point. Let consider the script given below and give it a name.

Script:

<script type="text/javascript">
       alert(" Hi I'm inline!");
       var val = 'Value of variable';
       function fname(value) {
           alert(value);
       }
</script
>

Complete Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!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">
 <head runat="server">
    <title>Hello</title>
<
script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
 <script type="text/javascript">
     $(function () {
         $('#b_load').click(function () {
             $.getScript(
'new.stuff.js');
         });
         $('#b_inspect').click(function () {
             fname(val);
         });
     });
</script>
 </head>
 <body>
    <form id="form1" runat="server">
    <div>
    <button type="button" id="b_load">Load</button>
    <button type="button" id="b_inspect">Inspect</button>
    </div>
    </form>
 </body>
</
html
>

Output 1:

6_1output.gif

Output 2: This one show the variable value on which is inside the external script.

6_2output.gif