Header Ads Widget

ad728

Learn JQUERY

    Introduction

    What is jQuery?

    jQuery is a fast and concise JavaScript Library created by John Resig in 2006 with a nice motto: Write less, do more. jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is a JavaScript toolkit designed to simplify various tasks by writing less code. Here is the list of important core features supported by jQuery −

    • DOM manipulation − The jQuery made it easy to select DOM elements, negotiate them and modifying their content by using cross-browser open source selector engine called Sizzle.

    • Event handling − The jQuery offers an elegant way to capture a wide variety of events, such as a user clicking on a link, without the need to clutter the HTML code itself with event handlers.

    • AJAX Support − The jQuery helps you a lot to develop a responsive and featurerich site using AJAX technology.

    • Animations − The jQuery comes with plenty of built-in animation effects which you can use in your websites.

    • Lightweight − The jQuery is very lightweight library - about 19KB in size (Minified and gzipped).

    • Cross Browser Support − The jQuery has cross-browser support, and works well in IE 6.0+, FF 2.0+, Safari 3.0+, Chrome and Opera 9.0+

    • Latest Technology − The jQuery supports CSS3 selectors and basic XPath syntax.

    How to use jQuery?

    There are two ways to use jQuery.

    • Local Installation − You can download jQuery library on your local machine and include it in your HTML code.

    • CDN Based Version − You can include jQuery library into your HTML code directly from Content Delivery Network (CDN).

    Local Installation

    • Go to the https://jquery.com/download/ to download the latest version available.

    • Now put downloaded jquery-2.1.3.min.js file in a directory of your website, e.g. /jquery.

    Example

    Now you can include jquery library in your HTML file as follows −

    <html>
       <head>
          <title>The jQuery Example</title>
          <script type = "text/javascript" src = "/jquery/jquery-2.1.3.min.js">
          </script>
    		
          <script type = "text/javascript">
             $(document).ready(function() {
                document.write("Hello, World!");
             });
          </script>
       </head>
    	
       <body>
          <h1>Hello</h1>
       </body>
    </html>

    This will produce following result −

    CDN Based Version

    You can include jQuery library into your HTML code directly from Content Delivery Network (CDN). Google and Microsoft provides content deliver for the latest version.

    We are using Google CDN version of the library throughout this tutorial.

    Example

    Now let us rewrite above example using jQuery library from Google CDN.

     Live Demo

    <html>
       <head>
          <title>The jQuery Example</title>
          <script type = "text/javascript" 
             src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
          </script>
    		
          <script type = "text/javascript">
             $(document).ready(function() {
                document.write("Hello, World!");
             });
          </script>
       </head>
    	
       <body>
          <h1>Hello</h1>
       </body>
    </html>

    This will produce following result −

    How to Call a jQuery Library Functions?

    As almost everything, we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready.

    If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.

    To do this, we register a ready event for the document as follows −

    $(document).ready(function() {
       // do stuff when DOM is ready
    });
    

    To call upon any jQuery library function, use HTML script tags as shown below −

     Live Demo

    <html>
       <head>
          <title>The jQuery Example</title>
          <script type = "text/javascript" 
             src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
          </script>
    
          <script type = "text/javascript" language = "javascript">
             $(document).ready(function() {
                $("div").click(function() {alert("Hello, world!");});
             });
          </script>
       </head>
    	
       <body>
          <div id = "mydiv">
             Click on this to see a dialogue box.
          </div>
       </body>
    </html>

    This will produce following result −

    How to Use Custom Scripts?

    It is better to write our custom code in the custom JavaScript file : custom.js, as follows −

    /* Filename: custom.js */
    $(document).ready(function() {
    
       $("div").click(function() {
          alert("Hello, world!");
       });
    });

    Now we can include custom.js file in our HTML file as follows −

     Live Demo

    <html>
       <head>
          <title>The jQuery Example</title>
          <script type = "text/javascript" 
             src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
          </script>
    		
          <script type = "text/javascript" src = "/jquery/custom.js">
          </script>
       </head>
    	
       <body>
          <div id = "mydiv">
             Click on this to see a dialogue box.
          </div>
       </body>
    </html>

    This will produce following result −

    Using Multiple Libraries

    You can use multiple libraries all together without conflicting each others. For example, you can use jQuery and MooTool javascript libraries together. You can check jQuery noConflict Method for more detail.

    What is Next ?

    Do not worry too much if you did not understand above examples. You are going to grasp them very soon in subsequent chapters.

    Next chapter would try to cover few basic concepts which are coming from conventional JavaScript.

    Basics

    jQuery is a framework built using JavaScript capabilities. So, you can use all the functions and other capabilities available in JavaScript. This chapter would explain most basic concepts but frequently used in jQuery.

    String

    A string in JavaScript is an immutable object that contains none, one or many characters. Following are the valid examples of a JavaScript String −

    "This is JavaScript String"
    'This is JavaScript String'
    'This is "really" a JavaScript String'
    "This is 'really' a JavaScript String"
    

    Numbers

    Numbers in JavaScript are double-precision 64-bit format IEEE 754 values. They are immutable, just as strings. Following are the valid examples of a JavaScript Numbers −

    5350
    120.27
    0.26
    

    Boolean

    A boolean in JavaScript can be either true or false. If a number is zero, it defaults to false. If an empty string defaults to false.

    Following are the valid examples of a JavaScript Boolean −

    true      // true
    false     // false
    0         // false
    1         // true
    ""        // false
    "hello"   // true
    

    Objects

    JavaScript supports Object concept very well. You can create an object using the object literal as follows −

    var emp = {
       name: "Zara",
       age: 10
    };
    

    You can write and read properties of an object using the dot notation as follows −

    // Getting object properties
    emp.name  // ==> Zara
    emp.age   // ==> 10
    
    // Setting object properties
    emp.name = "Daisy"  // <== Daisy
    emp.age  =  20      // <== 20
    

    Arrays

    You can define arrays using the array literal as follows −

    var x = [];
    var y = [1, 2, 3, 4, 5];
    

    An array has a length property that is useful for iteration −

    var x = [1, 2, 3, 4, 5];
    
    for (var i = 0; i < x.length; i++) {
       // Do something with x[i]
    }

    Functions

    A function in JavaScript can be either named or anonymous. A named function can be defined using function keyword as follows −

    function named(){
       // do some stuff here
    }

    An anonymous function can be defined in similar way as a normal function but it would not have any name.

    A anonymous function can be assigned to a variable or passed to a method as shown below.

    var handler = function (){
       // do some stuff here
    }

    JQuery makes a use of anonymous functions very frequently as follows −

    $(document).ready(function(){
       // do some stuff here
    });

    Arguments

    JavaScript variable arguments is a kind of array which has length property. Following example explains it very well −

    function func(x){
       console.log(typeof x, arguments.length);
    }
    
    func();                //==> "undefined", 0
    func(1);               //==> "number", 1
    func("1", "2", "3");   //==> "string", 3

    The arguments object also has a callee property, which refers to the function you're inside of. For example −

    function func() {
       return arguments.callee; 
    }
    
    func();                // ==> func

    Context

    JavaScript famous keyword this always refers to the current context. Within a function this context can change, depending on how the function is called −

    $(document).ready(function() {
       // this refers to window.document
    });
    
    $("div").click(function() {
       // this refers to a div DOM element
    });

    You can specify the context for a function call using the function-built-in methods call()and apply() methods.

    The difference between them is how they pass arguments. Call passes all arguments through as arguments to the function, while apply accepts an array as the arguments.

    function scope() {
       console.log(this, arguments.length);
    }
    
    scope() // window, 0
    scope.call("foobar", [1,2]);  //==> "foobar", 1
    scope.apply("foobar", [1,2]); //==> "foobar", 2

    Scope

    The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes.

    • Global Variables − A global variable has global scope which means it is defined everywhere in your JavaScript code.

    • Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

    Within the body of a function, a local variable takes precedence over a global variable with the same name −

    var myVar = "global";     // ==> Declare a global variable
    
    function ( ) {
       var myVar = "local";   // ==> Declare a local variable
       document.write(myVar); // ==> local
    }

    Callback

    A callback is a plain JavaScript function passed to some method as an argument or option. Some callbacks are just events, called to give the user a chance to react when a certain state is triggered.

    jQuery's event system uses such callbacks everywhere for example −

    $("body").click(function(event) {
       console.log("clicked: " + event.target);
    });

    Most callbacks provide arguments and a context. In the event-handler example, the callback is called with one argument, an Event.

    Some callbacks are required to return something, others make that return value optional. To prevent a form submission, a submit event handler can return false as follows −

    $("#myform").submit(function() {
       return false;
    });
    

    Closures

    Closures are created whenever a variable that is defined outside the current scope is accessed from within some inner scope.

    Following example shows how the variable counter is visible within the create, increment, and print functions, but not outside of them −

    function create() {
       var counter = 0;
    	
       return {
          increment: function() {
             counter++;
          },
    	   print: function() {
             console.log(counter);
          }
       }
    }
    
    var c = create();
    c.increment();
    c.print();     // ==> 1

    This pattern allows you to create objects with methods that operate on data that isn't visible to the outside world. It should be noted that data hiding is the very basis of object-oriented programming.

    Proxy Pattern

    A proxy is an object that can be used to control access to another object. It implements the same interface as this other object and passes on any method invocations to it. This other object is often called the real subject.

    A proxy can be instantiated in place of this real subject and allow it to be accessed remotely. We can saves jQuery's setArray method in a closure and overwrites it as follows −

    (function() {
       // log all calls to setArray
       var proxied = jQuery.fn.setArray;
    
       jQuery.fn.setArray = function() {
          console.log(this, arguments);
          return proxied.apply(this, arguments);
       };
    	
    })();

    The above wraps its code in a function to hide the proxied variable. The proxy then logs all calls to the method and delegates the call to the original method. Using apply(this, arguments) guarantees that the caller won't be able to notice the difference between the original and the proxied method.

    Built-in Functions

    JavaScript comes along with a useful set of built-in functions. These methods can be used to manipulate Strings, Numbers and Dates.

    Following are important JavaScript functions −

    Sr.No. Method & Description
    1

    charAt()

    Returns the character at the specified index.

    2

    concat()

    Combines the text of two strings and returns a new string.

    3

    forEach()

    Calls a function for each element in the array.

    4

    indexOf()

    Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.

    5

    length()

    Returns the length of the string.

    6

    pop()

    Removes the last element from an array and returns that element.

    7

    push()

    Adds one or more elements to the end of an array and returns the new length of the array.

    8

    reverse()

    Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first.

    9

    sort()

    Sorts the elements of an array.

    10

    substr()

    Returns the characters in a string beginning at the specified location through the specified number of characters.

    11

    toLowerCase()

    Returns the calling string value converted to lower case.

    12

    toString()

    Returns the string representation of the number's value.

    13

    toUpperCase()

    Returns the calling string value converted to uppercase.

    The Document Object Model

    The Document Object Model is a tree structure of various elements of HTML as follows −

     Live Demo

    <html>
       <head>
          <title>The jQuery Example</title>
       </head>
    	
       <body>
          <div>
             <p>This is a paragraph.</p>
             <p>This is second paragraph.</p>
             <p>This is third paragraph.</p>
          </div>
       </body>
    </html>

    This will produce following result −

    Following are the important points about the above tree structure −

    • The <html> is the ancestor of all the other elements; in other words, all the other elements are descendants of <html>.

    • The <head> and <body> elements are not only descendants, but children of <html>, as well.

    • Likewise, in addition to being the ancestor of <head> and <body>, <html> is also their parent.

    • The <p> elements are children (and descendants) of <div>, descendants of <body> and <html>, and siblings of each other <p> elements.

    While learning jQuery concepts, it will be helpful to have understanding on DOM, if you are not aware of DOM then I would suggest to go through our simple tutorial on DOM Tutorial.

    Selectors

    The jQuery library harnesses the power of Cascading Style Sheets (CSS) selectors to let us quickly and easily access elements or groups of elements in the Document Object Model (DOM).

    A jQuery Selector is a function which makes use of expressions to find out matching elements from a DOM based on the given criteria. Simply you can say, selectors are used to select one or more HTML elements using jQuery. Once an element is selected then we can perform various operations on that selected element.

    The $() factory function

    jQuery selectors start with the dollar sign and parentheses − $(). The factory function $()makes use of following three building blocks while selecting elements in a given document −

    Sr.No. Selector & Description
    1

    Tag Name

    Represents a tag name available in the DOM. For example $('p') selects all paragraphs <p> in the document.

    2

    Tag ID

    Represents a tag available with the given ID in the DOM. For example $('#some-id') selects the single element in the document that has an ID of some-id.

    3

    Tag Class

    Represents a tag available with the given class in the DOM. For example $('.some-class') selects all elements in the document that have a class of some-class.

    All the above items can be used either on their own or in combination with other selectors. All the jQuery selectors are based on the same principle except some tweaking.

    NOTE − The factory function $() is a synonym of jQuery() function. So in case you are using any other JavaScript library where $ sign is conflicting with some thing else then you can replace $ sign by jQuery name and you can use function jQuery() instead of $().

    Example

    Following is a simple example which makes use of Tag Selector. This would select all the elements with a tag name p.

     Live Demo

    <html>
       <head>
          <title>The jQuery Example</title>
          <script type = "text/javascript" 
             src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
          </script>
    
          <script type = "text/javascript" language = "javascript">
             $(document).ready(function() {
                $("p").css("background-color", "yellow");
             });
          </script>
       </head>
    	
       <body>
          <div>
             <p class = "myclass">This is a paragraph.</p>
             <p id = "myid">This is second paragraph.</p>
             <p>This is third paragraph.</p>
          </div>
       </body>
    </html>

    This will produce following result −

    How to Use Selectors?

    The selectors are very useful and would be required at every step while using jQuery. They get the exact element that you want from your HTML document.

    Following table lists down few basic selectors and explains them with examples.

    Sr.No. Selector & Description
    1 Name

    Selects all elements which match with the given element Name.

    2 #ID

    Selects a single element which matches with the given ID.

    3 .Class

    Selects all elements which match with the given Class.

    4 Universal (*)

    Selects all elements available in a DOM.

    5 Multiple Elements E, F, G

    Selects the combined results of all the specified selectors E, F or G.

    Selectors Examples

    Similar to above syntax and examples, following examples would give you understanding on using different type of other useful selectors −

    You can use all the above selectors with any HTML/XML element in generic way. For example if selector $("li:first") works for <li> element then $("p:first") would also work for <p> element.

    Attributes

    Some of the most basic components we can manipulate when it comes to DOM elements are the properties and attributes assigned to those elements.

    Most of these attributes are available through JavaScript as DOM node properties. Some of the more common properties are −

    • className
    • tagName
    • id
    • href
    • title
    • rel
    • src

    Consider the following HTML markup for an image element −

    <img id = "imageid" src = "image.gif" alt = "Image" class = "myclass" 
       title = "This is an image"/>
    

    In this element's markup, the tag name is img, and the markup for id, src, alt, class, and title represents the element's attributes, each of which consists of a name and a value.

    jQuery gives us the means to easily manipulate an element's attributes and gives us access to the element so that we can also change its properties.

    Get Attribute Value

    The attr() method can be used to either fetch the value of an attribute from the first element in the matched set or set attribute values onto all matched elements.

    Example

    Following is a simple example which fetches title attribute of <em> tag and set <div id = "divid"> value with the same value −

     Live Demo

    <html>
       <head>
          <title>The jQuery Example</title>
          <script type = "text/javascript" 
             src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
          </script>
    		
          <script type = "text/javascript" language = "javascript">
             $(document).ready(function() {
                var title = $("em").attr("title");
                $("#divid").text(title);
             });
          </script>
       </head>
    	
       <body>
          <div>
             <em title = "Bold and Brave">This is first paragraph.</em>
             <p id = "myid">This is second paragraph.</p>
             <div id = "divid"></div>
          </div>
       </body>
    </html>

    This will produce following result −

    Set Attribute Value

    The attr(name, value) method can be used to set the named attribute onto all elements in the wrapped set using the passed value.

    Example

    Following is a simple example which set src attribute of an image tag to a correct location −

     Live Demo

    <html>
       <head>
          <title>The jQuery Example</title>
          <base href="https://www.tutorialspoint.com" />
          <script type = "text/javascript" 
             src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
          </script>
    		
          <script type = "text/javascript" language = "javascript">
             $(document).ready(function() {
                $("#myimg").attr("src", "/jquery/images/jquery.jpg");
             });
          </script>
       </head>
    	
       <body>
          <div>
             <img id = "myimg" src = "/images/jquery.jpg" alt = "Sample image" />
          </div>
       </body>
    </html>

    This will produce following result −

    Applying Styles

    The addClass( classes ) method can be used to apply defined style sheets onto all the matched elements. You can specify multiple classes separated by space.

    Example

    Following is a simple example which sets class attribute of a para <p> tag −

     Live Demo

    <html>
       <head>
          <title>The jQuery Example</title>
          <script type = "text/javascript" 
             src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
          </script>
    		
          <script type = "text/javascript" language = "javascript">
             $(document).ready(function() {
                $("em").addClass("selected");
                $("#myid").addClass("highlight");
             });
          </script>
    		
          <style>
             .selected { color:red; }
             .highlight { background:yellow; }
          </style>	
       </head>
    	
       <body>
          <em title = "Bold and Brave">This is first paragraph.</em>
          <p id = "myid">This is second paragraph.</p>
       </body>
    </html>

    This will produce following result −

    Attribute Methods

    Following table lists down few useful methods which you can use to manipulate attributes and properties −

    Sr.No. Methods & Description
    1 attr( properties )

    Set a key/value object as properties to all matched elements.

    2 attr( key, fn )

    Set a single property to a computed value, on all matched elements.

    3 removeAttr( name )

    Remove an attribute from each of the matched elements.

    4 hasClass( class )

    Returns true if the specified class is present on at least one of the set of matched elements.

    5 removeClass( class )

    Removes all or the specified class(es) from the set of matched elements.

    6 toggleClass( class )

    Adds the specified class if it is not present, removes the specified class if it is present.

    7 html( )

    Get the html contents (innerHTML) of the first matched element.

    8 html( val )

    Set the html contents of every matched element.

    9 text( )

    Get the combined text contents of all matched elements.

    10 text( val )

    Set the text contents of all matched elements.

    11 val( )

    Get the input value of the first matched element.

    12 val( val )

    Set the value attribute of every matched element if it is called on <input> but if it is called on <select> with the passed <option> value then passed option would be selected, if it is called on check box or radio box then all the matching check box and radiobox would be checked.

    Examples

    Similar to above syntax and examples, following examples would give you understanding on using various attribute methods in different situation −

    CSS

    The jQuery library supports nearly all of the selectors included in Cascading Style Sheet (CSS) specifications 1 through 3, as outlined on the World Wide Web Consortium's site.

    Using JQuery library developers can enhance their websites without worrying about browsers and their versions as long as the browsers have JavaScript enabled.

    Most of the JQuery CSS Methods do not modify the content of the jQuery object and they are used to apply CSS properties on DOM elements.

    Apply CSS Properties

    This is very simple to apply any CSS property using JQuery method css( PropertyName, PropertyValue ).

    Here is the syntax for the method −

    selector.css( PropertyName, PropertyValue );
    

    Here you can pass PropertyName as a javascript string and based on its value, PropertyValue could be string or integer.

    Example

    Following is an example which adds font color to the second list item.

     Live Demo

    <html>
       <head>
          <title>The jQuery Example</title>
          <script type = "text/javascript" 
             src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
          </script>
    		
          <script type = "text/javascript" language = "javascript">
             $(document).ready(function() {
                $("li").eq(2).css("color", "red");
             });
          </script>
       </head>
    	
       <body>
          <div>
             <ul>
                <li>list item 1</li>
                <li>list item 2</li>
                <li>list item 3</li>
                <li>list item 4</li>
                <li>list item 5</li>
                <li>list item 6</li>
             </ul>
          </div>
       </body>
    </html>

    This will produce following result −

    Apply Multiple CSS Properties

    You can apply multiple CSS properties using a single JQuery method CSS( {key1:val1, key2:val2....). You can apply as many properties as you like in a single call.

    Here is the syntax for the method −

    selector.css( {key1:val1, key2:val2....keyN:valN})
    

    Here you can pass key as property and val as its value as described above.

    Example

    Following is an example which adds font color as well as background color to the second list item.

     Live Demo

    <html>
       <head>
          <title>The jQuery Example</title>
          <script type = "text/javascript" 
             src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
          </script>
    		
          <script type = "text/javascript" language = "javascript">
             $(document).ready(function() {
                $("li").eq(2).css({"color":"red", "background-color":"green"});
             });
          </script>
       </head>
    	
       <body>
          <div>
             <ul>
                <li>list item 1</li>
                <li>list item 2</li>
                <li>list item 3</li>
                <li>list item 4</li>
                <li>list item 5</li>
                <li>list item 6</li>
             </ul>
          </div>
       </body>
    </html>

    This will produce following result −

    Setting Element Width & Height

    The width( val ) and height( val ) method can be used to set the width and height respectively of any element.

    Example

    Following is a simple example which sets the width of first division element where as rest of the elements have width set by style sheet

     Live Demo

    <html>
       <head>
          <title>The jQuery Example</title>
          <script type = "text/javascript" 
             src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
          </script>
    		
          <script type = "text/javascript" language = "javascript">
             $(document).ready(function() {
                $("div:first").width(100);
                $("div:first").css("background-color", "blue");
             });
          </script>
    		
          <style>
             div { 
                width:70px; height:50px; float:left; 
                margin:5px; background:red; cursor:pointer; 
             }
          </style>
       </head>
    	
       <body>
          <div></div>
          <div>d</div>
          <div>d</div>
          <div>d</div>
          <div>d</div>
       </body>
    </html>

    This will produce following result −

    JQuery CSS Methods

    Following table lists down all the methods which you can use to play with CSS properties −

    Sr.No. Method & Description
    1 css( name )

    Return a style property on the first matched element.

    2 css( name, value )

    Set a single style property to a value on all matched elements.

    3 css( properties )

    Set a key/value object as style properties to all matched elements.

    4 height( val )

    Set the CSS height of every matched element.

    5 height( )

    Get the current computed, pixel, height of the first matched element.

    6 innerHeight( )

    Gets the inner height (excludes the border and includes the padding) for the first matched element.

    7 innerWidth( )

    Gets the inner width (excludes the border and includes the padding) for the first matched element.

    8 offset( )

    Get the current offset of the first matched element, in pixels, relative to the document.

    9 offsetParent( )

    Returns a jQuery collection with the positioned parent of the first matched element.

    10 outerHeight( [margin] )

    Gets the outer height (includes the border and padding by default) for the first matched element.

    11 outerWidth( [margin] )

    Get the outer width (includes the border and padding by default) for the first matched element.

    12 position( )

    Gets the top and left position of an element relative to its offset parent.

    13 scrollLeft( val )

    When a value is passed in, the scroll left offset is set to that value on all matched elements.

    14 scrollLeft( )

    Gets the scroll left offset of the first matched element.

    15 scrollTop( val )

    When a value is passed in, the scroll top offset is set to that value on all matched elements.

    16 scrollTop( )

    Gets the scroll top offset of the first matched element.

    17 width( val )

    Set the CSS width of every matched element.

    18 width( )

    Get the current computed, pixel, width of the first matched element.

    DOM

    JQuery provides methods to manipulate DOM in efficient way. You do not need to write big code to modify the value of any element's attribute or to extract HTML code from a paragraph or division.

    JQuery provides methods such as .attr(), .html(), and .val() which act as getters, retrieving information from DOM elements for later use.

    Content Manipulation

    The html( ) method gets the html contents (innerHTML) of the first matched element.

    Here is the syntax for the method −

    selector.html( )
    

    Example

    Following is an example which makes use of .html() and .text(val) methods. Here .html() retrieves HTML content from the object and then .text( val ) method sets value of the object using passed parameter −

     Live Demo

    <html>
       <head>
          <title>The jQuery Example</title>
          <script type = "text/javascript" 
             src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
          </script>
    		
          <script type = "text/javascript" language = "javascript">
             $(document).ready(function() {
                $("div").click(function () {
                   var content = $(this).html();
                   $("#result").text( content );
                });
             });
          </script>
    		
          <style>
             #division{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
          </style>
       </head>
    	
       <body>
          <p>Click on the square below:</p>
          <span id = "result"> </span>
    		
          <div id = "division" style = "background-color:blue;">
             This is Blue Square!!
          </div>
       </body>
    </html>

    This will produce following result −

    DOM Element Replacement

    You can replace a complete DOM element with the specified HTML or DOM elements. The replaceWith( content ) method serves this purpose very well.

    Here is the syntax for the method −

    selector.replaceWith( content )
    

    Here content is what you want to have instead of original element. This could be HTML or simple text.

    Example

    Following is an example which would replace division element with "<h1>JQuery is Great </h1>" −

     Live Demo

    <html>
       <head>
          <title>The jQuery Example</title>
          <script type = "text/javascript" 
             src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
          </script>
    		
          <script type = "text/javascript" language = "javascript">
             $(document).ready(function() {
                $("div").click(function () {
                   $(this).replaceWith("<h1>JQuery is Great</h1>");
                });
             });
          </script>
    		
          <style>
             #division{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
          </style>
       </head>
    	
       <body>
          <p>Click on the square below:</p>
          <span id = "result"> </span>
    		
          <div id = "division" style = "background-color:blue;">
             This is Blue Square!!
          </div>
       </body>
    </html>

    This will produce following result −

    Removing DOM Elements

    There may be a situation when you would like to remove one or more DOM elements from the document. JQuery provides two methods to handle the situation.

    The empty( ) method remove all child nodes from the set of matched elements where as the method remove( expr ) method removes all matched elements from the DOM.

    Here is the syntax for the method −

    selector.remove( [ expr ])
    
    or 
    
    selector.empty( )
    

    You can pass optional parameter expr to filter the set of elements to be removed.

    Example

    Following is an example where elements are being removed as soon as they are clicked −

     Live Demo

    <html>
       <head>
          <title>The jQuery Example</title>
          <script type = "text/javascript" 
             src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
          </script>
    		
          <script type = "text/javascript" language = "javascript">
             $(document).ready(function() {
                $("div").click(function () {
                   $(this).remove( );
                });
             });
          </script>
    		
          <style>
             .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
          </style>
       </head>
    	
       <body>
          <p>Click on any square below:</p>
          <span id = "result"> </span>
    		
          <div class = "div" style = "background-color:blue;"></div>
          <div class = "div" style = "background-color:green;"></div>
          <div class = "div" style = "background-color:red;"></div>
       </body>
    </html>

    This will produce following result −

    Inserting DOM Elements

    There may be a situation when you would like to insert new one or more DOM elements in your existing document. JQuery provides various methods to insert elements at various locations.

    The after( content ) method insert content after each of the matched elements where as the method before( content ) method inserts content before each of the matched elements.

    Here is the syntax for the method −

    selector.after( content )
    
    or
    
    selector.before( content )
    

    Here content is what you want to insert. This could be HTML or simple text.

    Example

    Following is an example where <div> elements are being inserted just before the clicked element −

     Live Demo

    <html>
       <head>
          <title>The jQuery Example</title>
          <script type = "text/javascript" 
             src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
          </script>
    		
          <script type = "text/javascript" language = "javascript">
             $(document).ready(function() {
                $("div").click(function () {
                   $(this).before('<div class="div"></div>' );
                });
             });
          </script>
    		
          <style>
             .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
          </style>
       </head>
    	
       <body>
          <p>Click on any square below:</p>
          <span id = "result"> </span>
    		
          <div class = "div" style = "background-color:blue;"></div>
          <div class = "div" style = "background-color:green;"></div>
          <div class = "div" style = "background-color:red;"></div>
       </body>
    </html>

    This will produce following result −

    DOM Manipulation Methods

    Following table lists down all the methods which you can use to manipulate DOM elements −

    Sr.No. Method & Description
    1 after( content )

    Insert content after each of the matched elements.

    2 append( content )

    Append content to the inside of every matched element.

    3 appendTo( selector )

    Append all of the matched elements to another, specified, set of elements.

    4 before( content )

    Insert content before each of the matched elements.

    5 clone( bool )

    Clone matched DOM Elements, and all their event handlers, and select the clones.

    6 clone( )

    Clone matched DOM Elements and select the clones.

    7 empty( )

    Remove all child nodes from the set of matched elements.

    8 html( val )

    Set the html contents of every matched element.

    9 html( )

    Get the html contents (innerHTML) of the first matched element.

    10 insertAfter( selector )

    Insert all of the matched elements after another, specified, set of elements.

    11 insertBefore( selector )

    Insert all of the matched elements before another, specified, set of elements.

    12 prepend( content )

    Prepend content to the inside of every matched element.

    13 prependTo( selector )

    Prepend all of the matched elements to another, specified, set of elements.

    14 remove( expr )

    Removes all matched elements from the DOM.

    15 replaceAll( selector )

    Replaces the elements matched by the specified selector with the matched elements.

    16 replaceWith( content )

    Replaces all matched elements with the specified HTML or DOM elements.

    17 text( val )

    Set the text contents of all matched elements.

    18 text( )

    Get the combined text contents of all matched elements.

    19 wrap( elem )

    Wrap each matched element with the specified element.

    20 wrap( html )

    Wrap each matched element with the specified HTML content.

    21 wrapAll( elem )

    Wrap all the elements in the matched set into a single wrapper element.

    22 wrapAll( html )

    Wrap all the elements in the matched set into a single wrapper element.

    23 wrapInner( elem )

    Wrap the inner child contents of each matched element (including text nodes) with a DOM element.

    24 wrapInner( html )

    Wrap the inner child contents of each matched element (including text nodes) with an HTML structure.

    Events

    We have the ability to create dynamic web pages by using events. Events are actions that can be detected by your Web Application.

    Following are the examples events −

    • A mouse click
    • A web page loading
    • Taking mouse over an element
    • Submitting an HTML form
    • A keystroke on your keyboard, etc.

    When these events are triggered, you can then use a custom function to do pretty much whatever you want with the event. These custom functions call Event Handlers.

    Binding Event Handlers

    Using the jQuery Event Model, we can establish event handlers on DOM elements with the bind() method as follows −

     Live Demo

    <html>
       <head>
          <title>The jQuery Example</title>
          <script type = "text/javascript" 
             src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
          </script>
    		
          <script type = "text/javascript" language = "javascript">
             $(document).ready(function() {
                $('div').bind('click', function( event ){
                   alert('Hi there!');
                });
             });
          </script>
    		
          <style>
             .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
          </style>
       </head>
    	
       <body>
          <p>Click on any square below to see the result:</p>
    		
          <div class = "div" style = "background-color:blue;">ONE</div>
          <div class = "div" style = "background-color:green;">TWO</div>
          <div class = "div" style = "background-color:red;">THREE</div>
       </body>
    </html>

    This code will cause the division element to respond to the click event; when a user clicks inside this division thereafter, the alert will be shown.

    This will produce following result −

    The full syntax of the bind() command is as follows −

    selector.bind( eventType[, eventData], handler)
    

    Following is the description of the parameters −

    • eventType − A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types.

    • eventData − This is optional parameter is a map of data that will be passed to the event handler.

    • handler − A function to execute each time the event is triggered.

    Removing Event Handlers

    Typically, once an event handler is established, it remains in effect for the remainder of the life of the page. There may be a need when you would like to remove event handler.

    jQuery provides the unbind() command to remove an exiting event handler. The syntax of unbind() is as follows −

    selector.unbind(eventType, handler)
    
    or 
    
    selector.unbind(eventType)
    

    Following is the description of the parameters −

    • eventType − A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types.

    • handler − If provided, identifies the specific listener that's to be removed.

    Event Types

    The Event Object

    The callback function takes a single parameter; when the handler is called the JavaScript event object will be passed through it.

    The event object is often unnecessary and the parameter is omitted, as sufficient context is usually available when the handler is bound to know exactly what needs to be done when the handler is triggered, however there are certain attributes which you would need to be accessed.

    The Event Attributes

     Live Demo

    <html>
       <head>
          <title>The jQuery Example</title>
          <script type = "text/javascript" 
             src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
          </script>
    		
          <script type = "text/javascript" language = "javascript">
             $(document).ready(function() {
                $('div').bind('click', function( event ){
                   alert('Event type is ' + event.type);
                   alert('pageX : ' + event.pageX);
                   alert('pageY : ' + event.pageY);
                   alert('Target : ' + event.target.innerHTML);
                });
             });
          </script>
    		
          <style>
             .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
          </style>
       </head>
    	
       <body>
          <p>Click on any square below to see the result:</p>
    		
          <div class = "div" style = "background-color:blue;">ONE</div>
          <div class = "div" style = "background-color:green;">TWO</div>
          <div class = "div" style = "background-color:red;">THREE</div>
       </body>
    </html>

    This will produce following result −

    The Event Methods

    There is a list of methods which can be called on an Event Object −

    Sr.No. Method & Description
    1 preventDefault()

    Prevents the browser from executing the default action.

    2 isDefaultPrevented()

    Returns whether event.preventDefault() was ever called on this event object.

    3 stopPropagation()

    Stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.

    4 isPropagationStopped()

    Returns whether event.stopPropagation() was ever called on this event object.

    5 stopImmediatePropagation()

    Stops the rest of the handlers from being executed.

    6 isImmediatePropagationStopped()

    Returns whether event.stopImmediatePropagation() was ever called on this event object.

    Event Manipulation Methods

    Following table lists down important event-related methods −

    Sr.No. Method & Description
    1 bind( type, [data], fn )

    Binds a handler to one or more events (like click) for each matched element. Can also bind custom events.

    2 off( events [, selector ] [, handler(eventObject) ] )

    This does the opposite of live, it removes a bound live event.

    3 hover( over, out )

    Simulates hovering for example moving the mouse on, and off, an object.

    4 on( events [, selector ] [, data ], handler )

    Binds a handler to an event (like click) for all current − and future − matched element. Can also bind custom events.

    5 one( type, [data], fn )

    Binds a handler to one or more events to be executed once for each matched element.

    6 ready( fn )

    Binds a function to be executed whenever the DOM is ready to be traversed and manipulated.

    7 trigger( event, [data] )

    Trigger an event on every matched element.

    8 triggerHandler( event, [data] )

    Triggers all bound event handlers on an element.

    9 unbind( [type], [fn] )

    This does the opposite of bind, it removes bound events from each of the matched elements.

    Event Helper Methods

    jQuery also provides a set of event helper functions which can be used either to trigger an event to bind any event types mentioned above.

    Trigger Methods

    Following is an example which would triggers the blur event on all paragraphs −

    $("p").blur();
    

    Binding Methods

    Following is an example which would bind a click event on all the <div> −

    $("div").click( function () { 
       // do something here
    });
    

    Ajax

    AJAX is an acronym standing for Asynchronous JavaScript and XML and this technology helps us to load data from the server without a browser page refresh.

    If you are new with AJAX, I would recommend you go through our Ajax Tutorial before proceeding further.

    JQuery is a great tool which provides a rich set of AJAX methods to develop next generation web application.

    Loading Simple Data

    This is very easy to load any static or dynamic data using JQuery AJAX. JQuery provides load() method to do the job −

    Syntax

    Here is the simple syntax for load() method −

    [selector].load( URL, [data], [callback] );
    

    Here is the description of all the parameters −

    • URL − The URL of the server-side resource to which the request is sent. It could be a CGI, ASP, JSP, or PHP script which generates data dynamically or out of a database.

    • data − This optional parameter represents an object whose properties are serialized into properly encoded parameters to be passed to the request. If specified, the request is made using the POST method. If omitted, the GETmethod is used.

    • callback − A callback function invoked after the response data has been loaded into the elements of the matched set. The first parameter passed to this function is the response text received from the server and second parameter is the status code.

    Example

    Consider the following HTML file with a small JQuery coding −

     Live Demo

    <html>
       <head>
          <title>The jQuery Example</title>
          <script type = "text/javascript" 
             src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
          </script>
    		
          <script type = "text/javascript" language = "javascript">
             $(document).ready(function() {
                $("#driver").click(function(event){
                   $('#stage').load('/jquery/result.html');
                });
             });
          </script>
       </head>
    	
       <body>
          <p>Click on the button to load /jquery/result.html file −</p>
    		
          <div id = "stage" style = "background-color:cc0;">
             STAGE
          </div>
    		
          <input type = "button" id = "driver" value = "Load Data" />
       </body>
    </html>

    Here load() initiates an Ajax request to the specified URL /jquery/result.html file. After loading this file, all the content would be populated inside <div> tagged with ID stage. Assuming, our /jquery/result.html file has just one HTML line −

    <h1>THIS IS RESULT...</h1>
    

    When you click the given button, then result.html file gets loaded.

    Getting JSON Data

    There would be a situation when server would return JSON string against your request. JQuery utility function getJSON() parses the returned JSON string and makes the resulting string available to the callback function as first parameter to take further action.

    Syntax

    Here is the simple syntax for getJSON() method −

    [selector].getJSON( URL, [data], [callback] );
    

    Here is the description of all the parameters −

    • URL − The URL of the server-side resource contacted via the GET method.

    • data − An object whose properties serve as the name/value pairs used to construct a query string to be appended to the URL, or a preformatted and encoded query string.

    • callback − A function invoked when the request completes. The data value resulting from digesting the response body as a JSON string is passed as the first parameter to this callback, and the status as the second.

    Example

    Consider the following HTML file with a small JQuery coding −

     Live Demo

    <html>
       <head>
          <title>The jQuery Example</title>
          <script type = "text/javascript" 
             src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
          </script>
    		
          <script type = "text/javascript" language = "javascript">
             $(document).ready(function() {
                $("#driver").click(function(event){
    				
                   $.getJSON('/jquery/result.json', function(jd) {
                      $('#stage').html('<p> Name: ' + jd.name + '</p>');
                      $('#stage').append('<p>Age : ' + jd.age+ '</p>');
                      $('#stage').append('<p> Sex: ' + jd.sex+ '</p>');
                   });
    					
                });
             });
          </script>
       </head>
    	
       <body>
          <p>Click on the button to load result.json file −</p>
    		
          <div id = "stage" style = "background-color:#eee;">
             STAGE
          </div>
    		
          <input type = "button" id = "driver" value = "Load Data" />
       </body>
    </html>

    Here JQuery utility method getJSON() initiates an Ajax request to the specified URL result.json file. After loading this file, all the content would be passed to the callback function which finally would be populated inside <div> tagged with ID stage. Assuming, our result.json file has following json formatted content −

    {
       "name": "Zara Ali",
       "age" : "67",
       "sex": "female"
    }
    

    When you click the given button, then result.json file gets loaded.

    Passing Data to the Server

    Many times you collect input from the user and you pass that input to the server for further processing. JQuery AJAX made it easy enough to pass collected data to the server using data parameter of any available Ajax method.

    Example

    This example demonstrate how can pass user input to a web server script which would send the same result back and we would print it −

     Live Demo

    <html>
       <head>
          <title>The jQuery Example</title>
          <script type = "text/javascript" 
             src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
          </script>
    		
          <script type = "text/javascript" language = "javascript">
             $(document).ready(function() {
                $("#driver").click(function(event){
                   var name = $("#name").val();
                   $("#stage").load('/jquery/result.php', {"name":name} );
                });
             });
          </script>
       </head>
    	
       <body>
          <p>Enter your name and click on the button:</p>
          <input type = "input" id = "name" size = "40" /><br />
    		
          <div id = "stage" style = "background-color:cc0;">
             STAGE
          </div>
    		
          <input type = "button" id = "driver" value = "Show Result" />
       </body>
    </html>

    Here is the code written in result.php script −

    <?php
       if( $_REQUEST["name"] ){
          $name = $_REQUEST['name'];
          echo "Welcome ". $name;
       }
    ?> 

    Now you can enter any text in the given input box and then click "Show Result" button to see what you have entered in the input box.

    JQuery AJAX Methods

    You have seen basic concept of AJAX using JQuery. Following table lists down all important JQuery AJAX methods which you can use based your programming need −

    Sr.No. Methods & Description
    1 jQuery.ajax( options )

    Load a remote page using an HTTP request.

    2 jQuery.ajaxSetup( options )

    Setup global settings for AJAX requests.

    3 jQuery.get( url, [data], [callback], [type] )

    Load a remote page using an HTTP GET request.

    4 jQuery.getJSON( url, [data], [callback] )

    Load JSON data using an HTTP GET request.

    5 jQuery.getScript( url, [callback] )

    Loads and executes a JavaScript file using an HTTP GET request.

    6 jQuery.post( url, [data], [callback], [type] )

    Load a remote page using an HTTP POST request.

    7 load( url, [data], [callback] )

    Load HTML from a remote file and inject it into the DOM.

    8 serialize( )

    Serializes a set of input elements into a string of data.

    9 serializeArray( )

    Serializes all forms and form elements like the .serialize() method but returns a JSON data structure for you to work with.

    JQuery AJAX Events

    You can call various JQuery methods during the life cycle of AJAX call progress. Based on different events/stages following methods are available −

    You can go through all the AJAX Events.

    Sr.No. Methods & Description
    1 ajaxComplete( callback )

    Attach a function to be executed whenever an AJAX request completes.

    2 ajaxStart( callback )

    Attach a function to be executed whenever an AJAX request begins and there is none already active.

    3 ajaxError( callback )

    Attach a function to be executed whenever an AJAX request fails.

    4 ajaxSend( callback )

    Attach a function to be executed before an AJAX request is sent.

    5 ajaxStop( callback )

    Attach a function to be executed whenever all AJAX requests have ended.

    6 ajaxSuccess( callback )

    Attach a function to be executed whenever an AJAX request completes successfully.

    Interaction

    Interactions could be added basic mouse-based behaviours to any element. Using with interactions, We can create sortable lists, resizeable elements, drag & drop behaviours.Interactions also make great building blocks for more complex widgets and applications.

    Sr.No. Interactions & Description
    1 Drag able

    Enable drag able functionality on any DOM element.

    2 Drop able

    Enable any DOM element to be drop able.

    3 Resize able

    Enable any DOM element to be resize-able.

    4 Select able

    Enable a DOM element (or group of elements) to be selectable.

    5 Sort able

    Enable a group of DOM elements to be sortable.

    Widgets

    a jQuery UI widget is a specialized jQuery plug-in.Using plug-in, we can apply behaviours to the elements. However, plug-ins lack some built-in capabilities, such as a way to associate data with its elements, expose methods, merge options with defaults, and control the plug-in's lifetime.

    Sr.No. Widgets & Description
    1 Accordion

    Enable to collapse the content, that is broken into logical sections.

    2 Autocomplete

    Enable to provides the suggestions while you type into the field.

    3 Button

    Button is an input of type submit and an anchor.

    4 Datepicker

    It is to open an interactive calendar in a small overlay.

    5 Dialog

    Dialog boxes are one of the nice ways of presenting information on an HTML page.

    6 Menu

    Menu shows list of items.

    7 Progressbar

    It shows the progress information.

    8 Select menu

    Enable a style able select element/elements.

    9 Slider

    The basic slider is horizontal and has a single handle that can be moved with the mouse or by using the arrow keys.

    10 Spinner

    It provides a quick way to select one value from a set.

    11 Tabs

    It is used to swap between content that is broken into logical sections.

    12 Tooltip

    Its provides the tips for the users.

    Theming

    Jquery has two different styling themes as A And B.Each with different colors for buttons, bars, content blocks, and so on.

    The syntax of J query theming as shown below −

    <div data-role = "page" data-theme = "a|b">
    

    A Simple of A theming Example as shown below −

     Live Demo

    <!DOCTYPE html>
    <html>
       <head>
          <meta name = "viewport" content = "width = device-width, initial-scale = 1">
          <link rel = "stylesheet" 
             href = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
    			
          <script src = "https://code.jquery.com/jquery-1.11.3.min.js">
          </script>
          <script src = "https://code.jquery.com/jquery-1.11.3.min.js">
          </script>
          <script 
             src = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js">
          </script>
       </head>
    	
       <body>
          <div data-role = "page" id = "pageone" data-theme = "a">
            <div data-role = "header">
                <h1>Tutorials Point</h1>
             </div>
    
             <div data-role = "main" class = "ui-content">
    			
                <p>Text link</p>
                <a href = "#">A Standard Text Link</a>
                <a href = "#" class = "ui-btn">Link Button</a>
                <p>A List View:</p>
    				
                <ul data-role = "listview" data-autodividers = "true" data-inset = "true">
                   <li><a href = "#">Android </a></li>
                   <li><a href = "#">IOS</a></li>
                </ul>
    				
                <label for = "fullname">Input Field:</label>
                <input type = "text" name = "fullname" id = "fullname" 
                   placeholder = "Name..">    
                <label for = "switch">Toggle Switch:</label>
    				
                <select name = "switch" id = "switch" data-role = "slider">
                   <option value = "on">On</option>
                   <option value = "off" selected>Off</option>
                </select>
    				
             </div>
    
             <div data-role = "footer">
                <h1>Tutorials point</h1>
             </div>
          </div>
       </body>
    </html>

    This should produce following result −

    A Simple of B theming Example as shown below −

     Live Demo

    <!DOCTYPE html>
    <html>
       <head>
          <meta name = "viewport" content = "width = device-width, initial-scale = 1">
          <link rel = "stylesheet" 
             href = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
          <script src = "https://code.jquery.com/jquery-1.11.3.min.js">
          </script>
          <script src = "https://code.jquery.com/jquery-1.11.3.min.js">
          </script>
          <script 
             src = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js">
          </script>
       </head>
    	
       <body>
          <div data-role = "page" id = "pageone" data-theme = "b">
            <div data-role = "header">
                <h1>Tutorials Point</h1>
             </div>
    
             <div data-role = "main" class = "ui-content">
                <p>Text link</p>
                <a href = "#">A Standard Text Link</a>
                <a href = "#" class = "ui-btn">Link Button</a>
                <p>A List View:</p>
    				
                <ul data-role = "listview" data-autodividers = "true" data-inset = "true">
                   <li><a href = "#">Android </a></li>
                   <li><a href = "#">IOS</a></li>
                </ul>
    				
                <label for = "fullname">Input Field:</label>
                <input type = "text" name = "fullname" id = "fullname" 
                   placeholder = "Name..">    
                <label for = "switch">Toggle Switch:</label>
    				
                <select name = "switch" id = "switch" data-role = "slider">
                   <option value = "on">On</option>
                   <option value = "off" selected>Off</option>
                </select>
    				
             </div>
    
             <div data-role = "footer">
                <h1>Tutorials point</h1>
             </div>
          </div>
       </body>
    </html>

    This should produce following result −

    Utilities

    Jquery provides serveral utilities in the formate of $(name space). These methods are helpful to complete the programming tasks.a few of the utility methods are as show below.

    $.trim()

    $.trim() is used to Removes leading and trailing whitespace

    $.trim( "    lots of extra whitespace    " );
    

    $.each()

    $.each() is used to Iterates over arrays and objects

    $.each([ "foo", "bar", "baz" ], function( idx, val ) {
       console.log( "element " + idx + " is " + val );
    });
     
    $.each({ foo: "bar", baz: "bim" }, function( k, v ) {
       console.log( k + " : " + v );
    });

    .each() can be called on a selection to iterate over the elements contained in the selection. .each(), not $.each(), should be used for iterating over elements in a selection.

    $.inArray()

    $.inArray() is used to Returns a value's index in an array, or -1 if the value is not in the array.

    var myArray = [ 1, 2, 3, 5 ];
     
    if ( $.inArray( 4, myArray ) !== -1 ) {
       console.log( "found it!" );
    }

    $.extend()

    $.extend() is used to Changes the properties of the first object using the properties of subsequent objects.

    var firstObject = { foo: "bar", a: "b" };
    var secondObject = { foo: "baz" };
     
    var newObject = $.extend( firstObject, secondObject );
     
    console.log( firstObject.foo ); 
    console.log( newObject.foo );
    

    $.proxy()

    $.proxy() is used to Returns a function that will always run in the provided scope — that is, sets the meaning of this inside the passed function to the second argument

    var myFunction = function() {
       console.log( this );
    };
    
    var myObject = {
       foo: "bar"
    };
     
    myFunction(); // window
     
    var myProxyFunction = $.proxy( myFunction, myObject );
     
    myProxyFunction();

    $.browser

    $.browser is used to give the information about browsers

    jQuery.each( jQuery.browser, function( i, val ) {
       $( "<div>" + i + " : <span>" + val + "</span>" )
       .appendTo( document.body );
    });

    $.contains()

    $.contains() is used to returns true if the DOM element provided by the second argument is a descendant of the DOM element provided by the first argument, whether it is a direct child or nested more deeply.

    $.contains( document.documentElement, document.body );
    $.contains( document.body, document.documentElement );
    

    $.data()

    $.data() is used to give the information about data

     Live Demo

    <html lang = "en">
       <head>
          <title>jQuery.data demo</title>
          <script src = "https://code.jquery.com/jquery-1.10.2.js">
          </script>
       </head>
    	
       <body>
          <div>
             The values stored were <span></span>
                and <span></span>
          </div>
     
          <script>
             var div = $( "div" )[ 0 ];
    			
             jQuery.data( div, "test", {
                first: 25,
                last: "tutorials"
             });
    			
             $( "span:first" ).text( jQuery.data( div, "test" ).first );
             $( "span:last" ).text( jQuery.data( div, "test" ).last );
          </script>
       </body>
    </html>

    An output would be as follows

    The values stored were 25 and tutorials
    

    $.fn.extend()

    $.fn.extend() is used to extends the jQuery prototype

     Live Demo

    <html lang = "en">
       <head>
          <script src = "https://code.jquery.com/jquery-1.10.2.js">
          </script>
       </head>
    	
       <body>
          <label><input type = "checkbox" name = "android"> 
             Android</label>
          <label><input type = "checkbox" name = "ios"> IOS</label>
     
          <script>
             jQuery.fn.extend({
    			
                check: function() {
                   return this.each(function() {
                      this.checked = true;
                   });
                },
                uncheck: function() {
                   return this.each(function() {
                      this.checked = false;
                   });
                }
             });
     
             // Use the newly created .check() method
             $( "input[type = 'checkbox']" ).check();
    			
          </script>
       </body>
    </html>

    It provides the output as shown below −

    $.isWindow()

    $.isWindow() is used to recognise the window

     Live Demo

    <!doctype html>
    <html lang = "en">
       <head>
          <meta charset = "utf-8">
          <title>jQuery.isWindow demo</title>
          <script src = "https://code.jquery.com/jquery-1.10.2.js">
          </script>
       </head>
    	
       <body>
          Is 'window' a window? <b></b>
     
          <script>
             $( "b" ).append( "" + $.isWindow( window ) );
          </script>
       </body>
    </html>

    It provides the output as shown below −

    $.now()

    It returns a number which is representing the current time

    (new Date).getTime()
    

    $.isXMLDoc()

    $.isXMLDoc() checks whether a file is an xml or not

    jQuery.isXMLDoc( document )
    jQuery.isXMLDoc( document.body )
    

    $.globalEval()

    $.globalEval() is used to execute the javascript globally

    function test() {
       jQuery.globalEval( "var newVar = true;" )
    }
    test();

    $.dequeue()

    $.dequeue() is used to execute the next function in the queue

     Live Demo

    <!doctype html>
    <html lang = "en">
       <head>
          <meta charset = "utf-8">
          <title>jQuery.dequeue demo</title>
    		
          <style>
             div {
                margin: 3px;
                width: 50px;
                position: absolute;
                height: 50px;
                left: 10px;
                top: 30px;
                background-color: green;
                border-radius: 50px;
             }
             div.red {
                background-color: blue;
             }
          </style>
    		
          <script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
       </head>
    
       <body>
          <button>Start</button>
          <div></div>
     
          <script>
             $( "button" ).click(function() {
                $( "div" )
                .animate({ left: '+ = 400px' }, 2000 )
                .animate({ top: '0px' }, 600 )
    				
                .queue(function() {
                   $( this ).toggleClass( "red" );
                   $.dequeue( this );
                })
    				
                .animate({ left:'10px', top:'30px' }, 700 );
             });
          </script>
       </body>
    </html>

    It provides the output as shown below −

    Flickerplate

    Flickerplate is a jQuery plugin for creating a slider which allows you cycle through images with animated arrows and dots navigation.

    A Simple of flickerplate example as shown below −

    <!DOCTYPE html>
    <html>
       <head>   
          <meta charset = "utf-8">
          <meta name = "viewport" content = "width = device-width, 
             initial-scale = 1.0, maximum-scale = 1.0, user-scalable = no">    
    	
          <script src = "/jquery/src/flickerplate/js/min/jquery-v1.10.2.min.js" 
             type = "text/javascript">
          </script>
    			
          <script src = "/jquery/src/flickerplate/js/min/modernizr-custom-v2.7.1.min.js" 
             type = "text/javascript">
          </script>
    			
          <script src = "/jquery/src/flickerplate/js/min/hammer-v2.0.3.min.js"
             type = "text/javascript">
          </script>
    
          <link href = "/jquery/src/flickerplate/css/flickerplate.css"  
             type = "text/css" rel = "stylesheet">
    			
          <script src = "/jquery/src/flickerplate/js/min/flickerplate.min.js" 
             type = "text/javascript">
          </script>	
    	
          <script>
             $(function(){
                $('.flicker-example').flickerplate({
                   auto_flick        : true,
                   auto_flick_delay  : 8,
                   flick_animation   : 'transform-slide'
                });
             });
          </script>
    
          <link href = "/jquery/src/flickerplate/css/demo.css"  
             type = "text/css" rel = "stylesheet">
       </head>
    	
       <body>
          <div class = "flicker-example">
             <ul>
                <li data-background = "https://genblock.com/wp-content/uploads/2015
                   /05/download-circles-abstract-wallpaper-
                   abstract-photo-abstract-wallpaper.jpg">
    					
                   <img src = "https://www.tutorialspoint.com/about/images/mohtashim.jpg" 
                      style = "margin-left: 428px;">
    						
                   <div class = "flick-title">Mohtashim M.</div>
    					
                   <div class = "flick-sub-text">
                      Mohtashim is an MCA from AMU (Aligarah) and a Project
                      Management Professional. He has more than 17 years of 
                      experience in Telecom and Datacom industries covering 
                      complete SDLC. He is managing in-house innovations, 
                      business planning, implementation, finance and the overall
                      business development of Tutorials Point.
                   </div>
    					
                </li>
                <li data-background = "https://genblock.com/wp-content/uploads/2015
                   /05/download-circles-abstract-wallpaper-
                   abstract-photo-abstract-wallpaper.jpg">
    					
                   <img src = "https://www.tutorialspoint.com/about/images/gopal_verma.jpg" 
                      style = "margin-left: 428px;">
    						
                   <div class = "flick-title">Gopal K Verma</div>
    					
                   <div class = "flick-sub-text">
                      Gopal is an MCA from GJU (Hisar) and a Cisco Certified Network 
                      Professional. He has more than 11 years of experience in core 
                      data networking and telecommunications. He develops contents 
                      for Computer Science related subjects. He is also involved in 
                      developing Apps for various Mobile devices.
                   </div>
                </li>
                <li data-background = "https://genblock.com/wp-content/uploads/2015
                   /05/download-circles-abstract-wallpaper-
                   abstract-photo-abstract-wallpaper.jpg">
    					
                   <img src = "https://www.tutorialspoint.com/about/images/mukesh_kumar.jpg" 
                      style = "margin-left: 428px;">
    						
                   <div class = "flick-title">Mukesh Kumar</div>
    					
                   <div class = "flick-sub-text">
                      Mukesh Kumar, having 7+years experience in writing on various
                      topics ranging from IT products and services, legal, medical,
                      online advertisement & education to e-commerce businesses.
                      He also has experience of text & copy-editing, & online
                      research. He has done two masters – MA (Geography) from
                      University of Delhi and MA (Mass Communication & 
                      Journalism) from Kurukshetra University.
                   </div>
                </li>
             </ul>
          </div>
          
       </body>
    </html>

    This should produce following result −

    Click here

    Slide Show

    Slideshow.js is a jQuery plugin for quickly and easily implementing slide show of images or videos into your website.

    A Simple of slide show example as shown below −

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
       "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns = "https://www.w3.org/1999/xhtml" xml:lang = "en" lang = "en">
       
       <head>
          <meta http-equiv = "content-type" content = "text/html; charset = UTF-8" />
    		
          <link rel = "stylesheet" href = "css/supersized.css" type = "text/css" 
             media = "screen" />
          
          <link rel = "stylesheet" href = "theme/supersized.shutter.css" 
             type = "text/css" media = "screen" />
    		
          <script type = "text/javascript" 
             src = "https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js">
             </script>
          <script type = "text/javascript" src =" js/jquery.easing.min.js"></script>
    		
          <script type = "text/javascript" src =" js/supersized.3.2.7.min.js"></script>
          <script type = "text/javascript" src = "theme/supersized.shutter.min.js"></script>
    		
          <script type = "text/javascript">
             jQuery(function($){
                $.supersized({
                   slideshow         :  1,			
                   autoplay          :  1,			
                   start_slide       :  1,			
                   stop_loop         :  0,			
                   random            :  0,			
                   slide_interval    :  3000,		
                   transition        :  6, 			
                   transition_speed  :  1000,		
                   new_window        :  1,			
                   pause_hover       :  0,			
                   keyboard_nav      :  1,			
                   performance       :  1,			
                   image_protect     :  1,			
                                                    
                   min_width         :  0,			
                   min_height        :  0,			
                   vertical_center   :  1,			
                   horizontal_center :  1,			
                   fit_always        :  0,			
                   fit_portrait      :  1,			
                   fit_landscape     :  0,			
                   
                   slide_links       :  'blank',	
                   thumb_links       :  1,			
                   thumbnail_navigation    :   0,			
                   slides            :  	
                   [			
                      {
                         image : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/slides/kazvan-1.jpg', 
                            title : 'Sample demo', 
                            thumb : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/thumbs/kazvan-1.jpg', 
                            url : 'https://www.tutorialspoint.com'
                      },
                      {
                         image : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/slides/kazvan-3.jpg', 
                            title : 'Sample demo', 
                            thumb : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/thumbs/kazvan-3.jpg', 
                            url : 'https://www.tutorialspoint.com'
                      },
                      {
                         image : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/slides/wojno-1.jpg', 
                            title : 'Sample demo', 
                            thumb : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/thumbs/wojno-1.jpg', 
                            url : 'https://www.tutorialspoint.com'
                      },
                      {
                         image : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/slides/wojno-2.jpg', 
                            title : 'Sample demo', 
                            thumb : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/thumbs/wojno-2.jpg', 
                            url : 'https://www.tutorialspoint.com'
                      },
                      {
                         image : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/slides/wojno-3.jpg', 
                            title : 'Sample demo', 
                            thumb : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/thumbs/wojno-3.jpg', 
                            url : 'https://www.tutorialspoint.com'},
                   ],
                   progress_bar      :	1,			
                   mouse_scrub       :	0
                });
             });
          </script>
       </head>
    	
       <style type = "text/css">
          ul#demo-block{ margin:0 15px 15px 15px; }
          ul#demo-block li{ margin:0 0 10px 0; padding:10px; display:inline; 
             float:left; clear:both; color:#aaa; background:url('img/bg-black.png'); 
             font:11px Helvetica, Arial, sans-serif; }
          ul#demo-block li a{ color:#eee; font-weight:bold; }
       </style>
    
       <body>
          <div id = "prevthumb"></div>
          <div id = "nextthumb"></div>
          
          <a id = "prevslide" class = "load-item"></a>
          <a id = "nextslide" class = "load-item"></a>
          
          <div id = "thumb-tray" class = "load-item">
             <div id = "thumb-back"></div>
             <div id = "thumb-forward"></div>
          </div>
          
          <div id = "progress-back" class = "load-item">
             <div id = "progress-bar"></div>
          </div>
          
          <div id = "controls-wrapper" class = "load-item">
             <div id = "controls">
                <a id = "play-button"><img id = "pauseplay" src = "img/pause.png"/></a>
    
                <div id = "slidecounter">
                   <span class = "slidenumber"></span> / <span class = "totalslides"></span>
                </div>
    
                <div id = "slidecaption"></div>
    
                <a id = "tray-button"><img id = "tray-arrow" src = "img/button-tray-up.png"/></a>
    
                <ul id = "slide-list"></ul>
             </div>
          </div>
       </body>
    </html>

    This should produce following result −

    Click here

    Drawsvg

    Drawsvg.js is a jQuery plugin to draw svg images

    A Simple of drawsvg example as shown below −

    <!DOCTYPE html>
    <html lang = "en">
       <head>
          <meta charset = "UTF-8">
          <link rel = "shortcut icon" type = "image/x-icon" href = "favicon.ico">
          <link rel = "stylesheet" 
             href = "https://fonts.googleapis.com/css?family=Open+Sans:400,600">
          <link rel = "stylesheet" href = "style.css">
       </head>
    	
       <body>
          <div class = "intro">
             <div class = "container">
                <div class = "overlay">
                   <div class = "inner">
                      <h1>jQuery DrawSVG Sample</h1>
    
                      <div class = "items-wrapper">
                         <div class ="item active">
                            <svg viewBox = "0 0 201 146" class = "svgClass" 
                               style = "background-color:#ffffff00" 
                                  xmlns = "https://www.w3.org/2000/svg" width = "201"
                                  height = "146">
    									
                               <g stroke = "#FFF" stroke-width = "1" fill = "none">
                                  <path d = "M200.5 128.586c0 9.302-7.678
                                     16.914-17.06 16.914H17.56C8.18 145.5.5 
                                     137.888.5 128.586V29.414C.5 20.112 8.178 
                                     12.5 17.56 12.5h165.88c9.382 0 17.06 
                                     7.612 17.06 16.914v99.172z"/>
    											
                                  <path d = "M183.828 80.118c0 26.467-21.644 
                                     47.924-48.34 47.924-26.698 
                                     0-48.342-21.457-48.342-47.924s21.644-47.924 
                                     48.34-47.924c26.698 0 48.342 21.457 48.342
                                     47.924z"/>
    											
                                  <path d = "M171.98 80.118c0 19.978-16.338
                                     36.177-36.493 36.177-20.15 
                                     0-36.49-16.2-36.49-36.177 0-19.98 
                                     16.34-36.177 36.49-36.177 20.155 0 
                                     36.494 16.2 36.494 36.178z"/>
    											
                                  <path d = "M50.18 48.637c0 6.49-5.304 
                                     11.747-11.852 11.747-6.543
                                     0-11.847-5.258-11.847-11.747  0-6.488 
                                     5.305-11.746 11.848-11.746 6.548 0 11.852 
                                     5.26 11. 852 11.747z"/>
    											
                                  <path d = "M17.928 39.877c3.41-7.835 
                                     11.258-13.305 20.416-13.305 9.16 0 17.006 
                                     5.47 20.416 13.305"/>
    											
                                  <path d = "M46 12V4H26v8"/>
                                  <path d = "M94.833 12l11.5-11.5h59.5l11.5 11.5"/>
                                  <path d = "M26.333 92.5h35.5"/>
                                  <path d = "M26.333 105.5h43"/>
                                  <path d = "M26.333 117.5h52"/>
                               </g>
    									
                            </svg>
                         </div>
    
                         <div class = "item">
                            <svg viewBox = "0 0 207 105" style = "background-color:#ffffff00" 
                               xmlns = "https://www.w3.org/2000/svg" width = "207" 
                               height = "105">
    								
                               <g stroke = "#FFF" stroke-width = "1" fill = "none">
                                  <path d = "M127 63.496C127 85.306 144.455 
                                     103 165.998 103 187.538 103 205 85.306 
                                     205 63.496 205 41.682 187.537 24 165.998
                                     24 144.455 24 127 41.682 127 63.496z"/>
    											
                                  <path d = "M195 63.497C195 47.206 182.015 34 166 34"/>
    										
                                  <path d = "M2 63.496C2 85.306 19.455 103 
                                     41.002 103 62.542 103 80 85.306 80 63.496 
                                     80 41.682 62.54 24 41.002 24 19.455 24 2
                                     41.682 2 63.496z"/>
    											
                                  <path d = "M64.296 22.732C57.656 18.094 
                                     47.492 16 41.002 16c-6.49 0-12.675 
                                     1.33-18.3 3.732-5.622 2.404-10.686 
                                     5.88-14.938 10.178"/>
    											
                                  <path d = "M159.715 63.576c0 3.634 2.902 
                                     6.575 6.49 6.575 3.582 0 6.484-2.94 
                                     6.484-6.574 0-3.63-2.903-6.575-6.486-6.575-3.587
                                     0-6.49 2.946-6.49 6.576z"/>
    											
                                  <path d = "M34.873 64.032c0 3.63 2.907 
                                     6.575 6.494 6.575 3.578 0 6.485-2.945 
                                     6.485-6.575  0-3.635-2.907-6.575-6.485-6.575-3.587 
                                     0-6.494 2.94-6.494 6.575z"/>
    											
                                  <path d = "M163.25 57.026L141.773 3"/>
                                  <path d = "M98 63.5H48"/>
                                  <path d = "M101.73 57.63L70.5 14.013"/>
                                  <path d = "M70.49 14.5h76.646v-.206"/>
                                  <path d = "M139.134 14.505L108.468 57.95"/>
                                  <path d = "M70.894 15.05L42.834 57.05"/>
                                  <path d = "M70.5 14V3"/>
                                  <path d = "M141.427 3.23s19.83-7.71 19.83 6.344"/>
    										
                                  <path d = "M97.816 62.52c0 3.576 2.86 6.475 
                                     6.39 6.475s6.392-2.9 
                                     6.392-6.476c0-3.577-2.86-6.476-6.39
                                     -6.476s-6.392 2.9-6.392 6.476z"/>
    											
                                  <path d = "M106.642 69.26l2.913 11.044"/>
                                  <path d = "M105 83l10-5"/>
                                  <path d = "M62.5 3.5h18"/>
                               </g>
    									
                            </svg>
                         </div>
    
                         <div class = "item">
                            <svg viewBox = "0 0 201 116" style = "background-color:#ffffff00" 
                               xmlns = "https://www.w3.org/2000/svg" width = "201" 
                               height = "116">
    									
                               <g stroke = "#FFF" stroke-width = "1" fill = "none">
                                  <path d = "M19.5 101.5V6.45C19.5 3.176 23.12.5 
                                     26.402.5H175.53c3.282 0 5.97 2.677 5.97
                                     5.95v95.05"/>
    											
                                  <path d = "M171.5 89.5h-140v-77h140v77z"/>
    										
                                  <path d = "M200.5 107.526c0 1.635-1.344 
                                     2.974-2.985 2.974H3.485c-1.64 
                                     0-2.985-1.34-2.985-2.974v-3.052c0-1.635
                                     1.344-2.974 2.985-2.974h194.03c1.64 0 2.985 
                                     1.34 2.9852.974v3.052z"/>
    											
                                  <path d = "M1 110l10.5 5.5"/>
                                  <path d = "M11.604 115.5H189.46"/>
                                  <path d = "M189.5 115.5l9.5-5.5"/>
                                  <path d = "M99.5 7.5h5"/>
                                  <path d = "M138.5 12.5l28 28"/>
                                  <path d = "M148.5 12.5l18 18"/>
                                  <path d = "M159.5 12.5l7 6"/>
                               </g>
    									
                            </svg>
                         </div>
    
                         <div class = "item">
                            <svg viewBox = "0 0 200 155" style = "background-color:#ffffff00" 
                               xmlns = "https://www.w3.org/2000/svg" width = "200" 
                               height = "155">
    									
                               <g stroke = "#FFF" stroke-width = "1" fill = "none">
                                  <path d="M161.996 151.39l-33.97-27.178-45.01 
                                     30.576-35.67-27.603L.36 154.245 38.662 20.04 
                                     80.893 4.034l39.066 17.41L161.995.213l37.792 
                                     22.932-37.792 128.246z"/>
    											
                                  <path d = "M47.346 127.185L80.892 4.035"/>
                                  <path d = "M83.015 154.788l36.942-133.343"/>
                                  <path d = "M128.025 124.212l33.97-124"/>
                                  <path d = "M46.278 23.935L32.29 75.605"/>
                                  <path d = "M95.802 45.718L81.19 97.225"/>
                                  <path d = "M106.91 33.115l-22.26 81.39"/>
    										
                                  <path d = "M176.768 46.665c0 3.523-2.85
                                     6.376-6.366 6.376-3.514 0-6.364-2.852
                                     -6.364-6.375 0-3.512 2.85-6.37
                                     6.364-6.37 3.516 0 6.366 2.858 
                                     6.366 6.37z"/>
    											
                                  <path d = "M180.9 52.392l-10.844 
                                     19.91-10.394-19.995s-1.143-3.215-1.
                                     143-5.067c0-6.514 5.273-11.81 11.79-11.81 
                                     6.508 0 11.782 5.296 11.782 11.81 
                                     0 1.852-1.192 5.152-1.192 5.152z"/>
    											
                                  <path d = "M43.86 92.528c0 3.523-2.85 
                                     6.376-6.367 6.376-3.514 0-6.364-2.
                                     853-6.364-6.376 0-3.512 2.85-6.37 
                                     6.363-6.37 3.517 0 6.366 2.858 
                                     6.366 6.37z"/>
    											
                                  <path d = "M47.99 98.255l-10.843 19.91L26.754 
                                     98.17s-1.143-3.215-1.
                                     143-5.067c0-6.514 5.275-11.81 
                                     11.793-11.81 6.507 0 11.78 5.296 
                                     11.78 11.81 0 1.852-1.192 
                                     5.152-1.192 5.152z"/>
                               </g>
    									
                            </svg>
                         </div>
    							
                      </div>
                   </div>
                </div>
             </div>
          </div>
    		
          <div id = "fb-root"></div>
          <script async src = "//assets.codepen.io/assets/embed/ei.js">
          </script>
          <script src = "https://cdn.jsdelivr.net/jquery/1.11.3/jquery.min.js">
          </script>
          <script 
             src = "https://cdn.jsdelivr.net/jquery.easing/1.3/jquery.easing.1.3.min.js">
          </script>
          <script src = "jquery.drawsvg.min.js"></script>
    		
          <script>
             $(function() {
    
                var $doc = $(document),
                $win = $(window);
    
                var $intro = $('.intro'),
                $items = $intro.find('.item'),
                itemsLen = $items.length,
    				
                svgs = $intro.find('svg').drawsvg({
                   callback: animateIntro,
                   easing: 'easeOutQuart'
                }),
    				
                currItem = 0;
    
                function animateIntro() {
                   $items.removeClass('active').eq( currItem++ % itemsLen 
                      ).addClass('active').find('svg').drawsvg('animate');
                }
    
                animateIntro();
    
                var $header = $('header'),
                headerOffTop = $header.offset().top,
                isFixed = false;
    
                function menu() {
                   if ( $win.scrollTop() >= headerOffTop ) {
                      if ( !isFixed ) {
                         isFixed = true;
                         $header.addClass('affix');
                      }
                   } else if ( isFixed ) {
                      isFixed = false;
                      $header.removeClass('affix');
                   }
                }
    
                $win.on('scroll', menu);
                menu();
    
                $header.on('click', 'a[href^="#"]', function(e) {
                   e.preventDefault();
    
                   var hash = this.hash,
                   offset = $(hash).offset().top;
    
                   $('body, html').animate({
                      scrollTop: offset
                   }, 600, 'easeInOutQuart', function() {
                      document.location.hash = hash;
                   });
                });
    
             });
          </script>
       </body>
    </html>

    This should produce following result −

    Click here

    Weather

    Weather.js is a jQuery plugin to find the information about weather details.

    A Simple of Weather.js example as shown below −

    <!DOCTYPE html>
    <html lang = "en">
       <head>
          <meta charset = "UTF-8">
          <meta name = "viewport" content = "width = device-width, 
             initial-scale = 1">
          <link rel = "stylesheet" 
             href = "https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
          <link rel = "stylesheet" 
             href = "https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.css">
          <link href = 'https://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700'
             rel = 'stylesheet' type = 'text/css'>
          <link rel = "stylesheet" type = "text/css" href = "weather.css">
       </head>
    	
       <body id = "weather-background" class = "default-weather">
          <canvas id = "rain-canvas"></canvas>
          <canvas id = "cloud-canvas"></canvas>
          <canvas id = "weather-canvas"></canvas>
          <canvas id = "time-canvas"></canvas>
          <canvas id = "lightning-canvas"></canvas>
    		
          <div class = "page-wrap">
             <header class = "search-bar">
    			
                <p class = "search-text">
                   <span class = "search-location-text">
                      What's the weather like in 
                      
                      <input id = "search-location-input" 
                         class = "search-location-input" type = "text"
                         placeholder = "City"> ?
                   </span>
                </p>
    					
                <div class = "search-location-button-group">
                   <button id = "search-location-button" 
                      class = "fa fa-search search-location-button search-button">
                      </button>
    						
                   <!--  -->
                   <button id = "geo-button" class = "geo-button fa
                      fa-location-arrow search-button"></button>
                </div>
    				
             </header>
    
             <div id = "geo-error-message" class = "geo-error-message hide">
                <button id = 'close-error' class = 'fa fa-times 
                   close-error'></button>Uh oh! It looks like we can't 
                   find your location. Please type your city into the search 
                   box above!
             </div>
    
             <div id = "front-page-description" 
    			   class = "front-page-description middle">
                <h1>Blank Canvas Weather</h1>
             </div>
    			
             <div class = "attribution-links hide" id = "attribution-links">
                <button id = 'close-attribution' 
                   class = 'fa fa-times close-attribution'></button>
    					
                <h3>Icons from <a href = "https://thenounproject.com/">
                   Noun Project</a></h3>
    					
                <ul>
                   <li class = "icon-attribution">
                      <a href = "https://thenounproject.com/term/cloud/6852/">
                      Cloud</a> by Pieter J. Smits</li>
    						
                   <li class = "icon-attribution">
                      <a href = "https://thenounproject.com/term/snow/64/">
                      Snow</a> from National Park Service Collection</li>
    						
                   <li class = "icon-attribution">
                      <a href = "https://thenounproject.com/term/drop/11449/">
                      Drop</a> Alex Fuller</li>
    						
                   <li class = "icon-attribution">
                      <a href = "https://thenounproject.com/term/smoke/27750/">
                      Smoke</a> by Gerardo Martín Martínez</li>
    						
                   <li class = "icon-attribution">
                      <a href = "https://thenounproject.com/term/moon/13554/">
                      Moon</a> by Jory Raphael</li>
    						
                   <li class = "icon-attribution">
                      <a href = "https://thenounproject.com/term/warning/18974/">
                      Warning</a> by Icomatic</li>
    						
                   <li class = "icon-attribution">
                      <a href = "https://thenounproject.com/term/sun/13545/">
                      Sun</a> by Jory Raphael</li>
    						
                   <li class = "icon-attribution">
                      <a href = "https://thenounproject.com/term/windsock/135621/">
                      Windsock</a> by Golden Roof</li>
    						
                </ul>		
             </div>
    			
             <div id = "weather" class = "weather middle hide">
                <div class = "location" id = "location"></div>
                   
                   <div class = "weather-container">
                      <div id = "temperature-info" class = "temperature-info">
                         <div class = "temperature" id = "temperature">
                         </div>
                         <div class = "weather-description" id = "weather-description">
                         </div>
                      </div>
    						
                      <div class = "weather-box">
                         <ul class = "weather-info" id = "weather-info">
                            <li class = "weather-item humidity">Humidity:
                               <span id = "humidity"></span>%</li><!---->
                            <li class = "weather-item wind">Wind: <span 
                               id = "wind-direction"></span> <span 
                               id = "wind"></span> <span 
                               id = "speed-unit"></span></li>
                         </ul>
                      </div>
    						
                      <div class = "temp-change">
                         <button id = "celsius" 
                            class = "temp-change-button celsius">°C
                            </button><button id = "fahrenheit" 
                            class = "temp-change-button fahrenheit">
                            °F</button>
                      </div>
    						
                   </div>
                </div> 
    				
             </div>
    			
             <script 
                src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js">
                </script>
             <script src = "weather.js">
          </script>
          </div>	
       </body>
    </html>

    This should produce following result −

    Click here

    Categories:
    Similar Videos

    0 Comments: