Browse by Domains

JQuery Tutorial or What is JQuery?

jQuery – Home

What is jQuery?

  • jQuery is a lightweight and fast JavaScript library which contains lots of features.
  • Its easy to understand and create sophisticated effects with little coding.
  • It is also compatible with almost all the browsers.

Why JQuery?

JQuery is better than other languages; the most significant advantage is its selectors. These selectors let you traverse DOM trees of HTML document structures more efficiently.

It does have prebuilt methods that allow you to create animations and showcase effects like hiding, showing, sliding elements just by writing a piece of code. 

jQuery saves you a lot of time through its built-in selectors and its effects. It makes JavaScript tasks more straightforward and easier to accomplish. It does create interactive web pages with lots of features, and you just need to add a few lines of code. An example of this can be that you can obtain server information and update pages without even having to refresh the page. jQuery is quite easy to use and is quite compatible with a variety of browsers, be it Google Chrome, Mozilla Firefox, Internet Explorer, Opera, or Safari. Almost all browsers successfully use jQuery. It is also downloadable, and its availability is free, which is an added bonus.

You can also take up jQuery courses and learn the basic knowledge required for you to build a successful career.

The birth of jQuery

Back in those old days, where computers were just used by Scientists, Academician and Researchers and they had a huge difficulty in collaborating within their own communities. Hence, the world of HTML began. Research papers were published with the help of HTML in a simple notepad like format.  As days went by, CSS started coming in.  LAN was the primary source of communication network used. Later on the Internet came into the picture. HTML was written browser-specific which became a tedious task.  Document Object Model was introduced so that the tree-like structure for a webpage provides a similar structure across all the browsers. DOM is language-independent where the branch of the tree ends up in nodes and nodes represent the object of the document.  This DOM helped to organize HTML, CSS and JavaScript files for the front-end development.

If HTML represents the structures for a web page, and CSS represents the style for a web page then JavaScript describes the behaviour of a web page.  Few examples of JavaScript application are: drop-down hamburger menu, button click, and show or hide information etc.  As time flew, the repeated tasks using JavaScript became a small framework that got circulated among the developers. These frameworks then gave birth to the idea of having a library for JavaScript and it was called jQuery.

What to expect from this tutorial?

This jQuery tutorial is for anyone who wants to get an insight into the programming of jQuery and its concepts. It is expected that the user does have little knowledge about Html, JavaScript, CSS and DOM (Document object model). The coding provided in this tutorial will have a detailed explanation.

jQuery – Overview 

Some of the features supported by jQuery are-

Selecting and Filtering:

To make a selection DOM(Document object model), jQuery has a selector engine. There are various methods that jQuery has, which allows it to work with a selection to control the elements you are working with from the DOM. Some methods let you select different elements present in the code. They are the parent elements, sibling elements, ancestor elements, and descendant elements. You can remove elements from the selection, add elements to a selection and also reduce a selection to a specific subset of elements.

Event wrapper methods:

jQuery offers a comprehensive and powerful event API. Its event API provides wrapper methods that contain most of the events in JavaScript. It also provides the capability to attach events that it doesn’t explicitly support through its event methods. The jQuery event API even has the capability to apply events to elements that might not even exist in the document yet. In jQuery events can be organized neatly and the names spaced within it. You can organize these events neatly into named categories; this, therefore, makes it a lot easier to manage the events. It is also easier to remove the specific events also.

Manipulating Content and Attributes:

Working with attributes is quite easy in jQuery. The first thing you need to do is make a selection after you’ve made a selection; you can do something with your selection like you can set the attributes and access the attributes. Setting the attributes on a selection sets those attributes on every element that you’ve selected. The DOM content can be shuffled around and things like replacing one element with another, inserting new text or even HTML into the tags of HTML, appending or prepending the contents, clinging the content and removing the contents that need to be gotten rid of. You can manipulate the attributes using jQuery. It does so by providing all the methods that are needed, which is already available in the library. Maybe there’s a necessity to save custom data with an element; well, jQuery has answers for that.

Ajax and jQuery:

Ajax stands for Asynchronous JavaScript and XML. It loads data in the background and displays the result on the page without the need of reloading the entire page. jQuery does provide a lot of methods for Ajax’s functionality. With the help of these Ajax methods, you can request HTML, request a text, or an XML file or even JSON. These can be requested from a remote server using the HTTP methods. They are the HTTP GET and the HTTP Post methods. By doing so, you can load the entire data into the specific HTML elements of the page.

jQuery and Animation:

There are jQuery methods that provide animation to elements like showing and hiding the elements through different ways like fading in, fading out, sliding in, sliding out. This can be done by defining the CSS properties that need to be animated. Elements can move up and down, using custom animation. It also provides a variety of easing effects that can be used to control the flow time in animation.

jQuery and CSS:

The term ‘CSS’ refers to cascading style sheets. They are mainly used for styling the elements that are present on the web page. It has control over how the layout is viewed by the end-user, and it also differs depending upon the device through which the user sees the webpage. jQuery has methods that are both versatile as well as intuitive that help you to change, add, remove the styles that are being present in the elements in the HTML file.

STARTING JQUERY

How to use jQuery within the code?

There are two ways to use jQuery in your HTML file.

ONE WAY:

DOWNLOADING JQUERY LIBRARY FROM JQUERY.COM

STEP 1:Goto this link https://jquery.com/download/

STEP 2: To download the jquery script .right click the download the compressed production jQuery 3.5.1 as shown in the below image.Save the file name as jquery-3.5.1.min.

STEP 3: For the jQuery script to work in your HTML file you will need to add jQuery source in the html file like the following code-

<head>
<script type='text/javascript' src='jquery-3.5.1.min'>
</script>
</head>

ANOTHER WAY:

INCLUDE JQUERY FROM CDN (Content delivery network) like Google or Microsoft.

A Content Delivery Network or CDN is a network of servers designed to serve files to users. Using a CDN link on your web page will move the responsibility of hosting files from your server to a series of external ones. Google, Microsoft, jQuery foundation all provide CDNs that host jQuery core. CDN does not require you to host your version of jQuery.

Google CDN

This code includes the Google CDN-

<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script></head>

MICROSOFT CDN

This code includes the Microsoft CDN-

<head><script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script></head>

For the jQuery script to work. It must be included inside the HTML file ie <script> tag needs to be inside the <head> column.

What is DOM?

The HTML Document object model is the interface in which one can edit, add or delete objects in an HTML file. When your HTML is opened, the DOM must be loaded to ensure that the file is working properly. Once your DOM is loaded, your entire tree of data has been created. You can now be adding external elements into the HTML file.

Program 1: Program to add content inside the body of the HTML file through jQuery.

<html>  
<head>  
<title>Jquery title</title>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>  
<script type="text/javascript">  
$(document).ready(function(){  
 $("#messg").html("<h2>This is Hello World by HTML</h2>");  
});  
</script>  
</head>  
<body>  
<div id="messg">  
</div>  
</body>  
</html>  

The dollar symbol($) that’s present in the code means that such code calls a function to interact with the programming language. The dollar symbol is a code word standin of jquery.

To select a part of a document is the fundamental operation in jQuery. This can be done with the $() function. It typically takes a string as a parameter, that can contain any CSS selector expression. When $() is called the function returns a new jQuery object instance. This object allows us to interact with the DOM elements in many different ways, and it also encapsulates zero or more Dom elements. $() is the syntax for jQuery function.

The “.ready()” method in $(document).ready allows you to wait for the DOM to be loaded before adding other elements to your HTML file. JQuery tends to manipulate or read the DOM. As soon as the DOM is ready, the required events should be added. and it should be called inside the function 

$(document).ready().The dollar symbol represents a function of jQuery. This function stands by while it’s waiting for the page to load completely. Once the page gets loaded, the code within it gets executed immediately. 

As the DOM gets loaded, all that’s inside the function also gets loaded, even before the page contents are loaded.

When DOM elements are ready or fully loaded, an element with id” messg” HTML is set by this function. The “#messg” is selected, and the content is added into the HTML file using the function .html() .you can see that the “#messg” here  represents the div tag’s id.

The ready method is called on the document by the following way:
$(document).ready(function)

HTML tags explained:

As you can see from Program 1 the code has 5 elements. The common elements you will find in HTML will include the following:

<html> and </html>; <head> and </head>; <title> and </title>; <script> and </script>; <body> and </body>

The <html> tags tell the browser that all the elements written inside these tags must be regarded as web pages. It is the element inside this tag that starts your HTML pages.

 The <head> tag designates the start of your head section. It usually contains scripts and titles. The elements present in this tag will contain information that will help you to control the way your web page is shown. The codes of CSS and JavaScript are present within this tag.

The <title> tag shows the title of the web page. These elements contain the title of the page, you can find these on the title bar, the Top most part of your browser.

The <script> tag calls the code or file within the tags to make JavaScript codes. It also features the library of jQuery as well as a script of code. This calls functions from jQuery’s library.

The <h1> tag creates the text for the header

The <div> tag creates a container for the content

The <script src =”” http://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script> tag is the line that shows where the jQuery library is located.

The < script type = “text/java script “> tag informs the web browser that the JavaScript codes are located in here.

jQuery – Basic

Data Types in jQuery

jQuery framework uses the functions and other features of JavaScript. The data types that are available in JavaScript are incorporated in jQuery as well.

String Data Type

The String data type is used to represent a sequence of characters. They are created by placing them between single quotes (‘’) or double quotes (“”). The variable that holds a string data type can later be used to store a number. The programming languages that allow such things are called “Dynamically typed”, it means that variables are not bound to the data types even though data types exist. we can put any data type in a variable.

String variable is declared as follows: var name = “Welcome to jQuery”

Program 2: This Program prints a variable in the html file. The variable is declared a string later the same variable holds a number data type.

<html>  
   <head>  
      <title>The jQuery Example</title>  
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
      <script type = "text/javascript">  
         $(document).ready(function(){  
           var name = "welcome to 'jQuery Tutorial'!";  
            document.write(name)  
  
            name =1234  
            document.write("<br />" +'You can add numbers to the same variable as well  '+name)  
         });  
      </script>  
   </head>  
   <body></body>  
</html>  

The Number Data Type

This data type represents numbers that may be either positive or negative. They may or may not contain decimal values also.

Program 3: This Program contains different kinds of number data types and they are printed in the HTML file.

<html>  
   <head>  
      <title>The jQuery Example</title>  
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
      <script type = "text/javascript">  
         $(document).ready(function(){  
           var num = 37;         // That's an integer  
            var dec_num = 90.5;       // Thats a floating point number  
            var exp_num = 9.35e+4;    // Those are the exponential notations  
            var exp_num2 = 9.35e-4;  
            document.write("The number =",num,"</br>The Decimal number is = ",dec_num,"</br>The Exponential number is = ",exp_num,"</br>Anther exponential number = ",exp_num2)  
         });  
      </script>  
   </head>  
   <body></body>  
</html>  

Note: The </br> tag is used to create a break line so that the lines are not next to each other but rather on a new line.

The Boolean Data type

It holds only two values and it’s either true or false.

Program 4: This program just assigns true and false to variables and prints it.

<html>  
   <head>  
      <title>The jQuery Example</title>  
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
      <script type = "text/javascript">  
         $(document).ready(function(){  
         a = true;  
         b = false;  
               document.write("value of a is ",a,"</br> Value of b is ",b)  
         });  
    </script>  
   </head>  
  <body></body>  
</html>  

Objects Data Type

A collection of data can be stored in an object. It is defined using a key-value pair. The key will always be a string. The value however can be of any data type including numbers, strings, Boolean values.

The declaration of the object would be  var object name = {key:value}

Program 5: This Program sets the object student. It has a name, roll number and the school’s name set and printed in the html file.

<html>  
       <head>  
          <title>The jQuery Example</title>  
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
          <script type = "text/javascript">  
             $(document).ready(function(){  
               var student = {  
                        name: "Jane",  
                        roll_number : 22,  
                        school :"International school"  
                    };  
                document.write("The student's name is ",student.name,"</br> The student's roll number is ",student.roll_number,"</br> The student's school is  ",student.school)  
             });  
     </script>  
       </head>  
   <body></body>  
    </html>  

Arrays data type

This data type represents a collection of variables, values.

Program 6:

This program declares two arrays and they are concatenated using the function .concat().the function just joins the two arrays.

<html>  
   <head>  
      <title>The jQuery Example</title>  
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
      <script type = "text/javascript">  
  $(document).ready(function(){  
                 var birds = ["Dove ", "Sparrow"];  
                 var animals = ["Lion", "Tiger", "cheetah"];  
                 var anibirds = animals.concat(birds);  
                document.write("The first array of birds are = ",birds)  
                document.write("</br>The second array of animals are = ",animals)  
               document.write("</br> When u concatenate two arrays they become = ",anibirds)  
         });  
    </script>  
   </head>  
  <body></body>  
</html>  

The Functio

In JavaScript the function is a callable object. They are objects and hence they can be assigned to variables also.

Program 7: This program declares a function and then assigns it to a variable and calls the function through the variable.

<html>  
   <head>  
      <title>The jQuery Example</title>  
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
      <script type = "text/javascript">  
         $(document).ready(function(){  
                        var dialogbox = function(){  
                                       return "Dialog box 1";  
                            }  
               alert(dialogbox());alert(typeof dialogbox)  
         });  
    </script>  
   </head>  
  <body></body>  
</html>  

The dialog boxes get popped up in the html page because of the alert function. In the first alert function the variable is called as a function. The second alert method just prints the type of the variable which is the function itself.

Arguments

It is a type of array that has the length as its property. It is passed through a function.

This way you can simply use a function to find (for instance) the highest value in a list of numbers:

Program 8:

Here in this program a list of numbers is passed as an argument into a function and the largest of the numbers is printed here. note that the variable arguments. Length contains the length of the argument.

<html>  
   <head>  
      <title>The jQuery Example</title>  
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
      <script type = "text/javascript">  
         $(document).ready(function(){  
                        x = findMax(87,98,66,55,22,12,9,8,3);  
                        alert("The largest number is  " +x)  
  
                                   function findMax() {  
                                     var j;  
                                     var max = -Infinity;  
                                     for (j = 0; j < arguments.length; j++) {  
                                       if (arguments[j] > max) {  
                                         max = arguments[j];  
                                       }  
                                     }  
                                     return max;  
                                   }  
         });  
    </script>  
   </head>  
  <body></body>  
</html>  

Context

It contains the values of the ‘this’ keyword. The keyword is a reference to an object that is getting executed in the function. When the page gets loaded, the ‘this’ keyword refers to the window document. Once the user clicks the id, then the ‘this’ keyword refers to the click function. 

Program 9:

<html>  
   <head>  
      <title>The jQuery Example</title>  
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
      <script type = "text/javascript">  
        $(document).ready(function() {  
                    // this refers to window.document  
        });  
  
        $("#Click").click(function() {  
           // this refers to the ID element.  
        });  
  
    </script>  
   </head>  
  <body></body>  
</html>  

Scope

JavaScript has two types of scopes and they are the Global variable and the Local variable. The global variable’s scope is global i.e. It is usually declared outside the function. The local variable’s scope is local ie.it is declared inside the function. And it can be accessed within the function in which it is designed. If there is a variable with the same name in the scopes of global and local, the local variable’s scope is always selected over the global variable.

Program 10:

<html>  
   <head>  
      <title>The jQuery Example</title>  
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
      <script type = "text/javascript">  
         $(document).ready(function(){  
                        var z = 20;  
            document.write('This is the global variable '+z)  
  
            function myFunction() {  
  
                    var z = 300;  
                    document.write('</br>This is the local variable '+z)  
            }  
            myFunction()  
         });  
    </script>  
  </head>  
  <body></body>  
</html>  

Callback

It is a function that is passed as an argument to another function. By doing so, it allows a function to call another function. This call back function can run from another function. Some events are used as callbacks; it gives the user a chance to react when some state is triggered. You listen for an event to occur, and then you react to it by supplying a function. This function will be called when an event happens by the browser. This is called a callback.

To listen to an event, there are a few things that are needed: the call to listen, The callback function, and an element.

Program 11:

<html>  
   <head>  
      <title>The jQuery Example</title>  
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
      <script type = "text/javascript">  
         $(document).ready(function(){  
                        var ButtonClick = function (event) {  
                                         // do something!  
                            };  
                            var bluebutton = document.querySelector('#blue-button');  
                            bluebutton.addEventListener('click', ButtonClick);  
         });  
    </script>  
  </head>  
  <body></body>  
</html>  

Here, an event listener called addEventListener is fired when a user clicks a button. It’s quite a common method that’s found on almost all the DOM elements. A button variable is declared and the listener is called on an element that is saved in the blue button variable. Here the callback function is ButtonClick.

Closures

This is an important concept in jQuery. A closure means that the variables and the parameters present in the outer function are always accessible to the inner function even when the outer function is returned.

In this program, the return Function2 returns the Function2 from Function1 when there was a call to the function Function1(). There’s a variable named ‘a’ that references the Function2() only, and not the Function1(). Whenever you call the Function2(), it still has access to the variable a, which is declared in the Function1(). 

<html>  
   <head>  
      <title>The jQuery tutorial</title>  
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
      <script type = "text/javascript">  
  
  
         $(document).ready(function(){  
  
                           function Function1() {  
                                    var a = 200;  
                                  function Function2() {  
                                      alert(a);  
                                  }  
                            return Function2;  
                           }  
                           var Func = Function1();  
                           Func();  
         });  
      </script>  
   </head>  
   <body>  
  
   </body>  
</html>  

jQuery Selectors

jQuery selectors are used when it’s needed to select one or more than one HTML element. And they are one of the most important parts of the jQuery library. One of the powerful features of jQuery is the ability to select DOM elements easily, and it’s done by the selectors. These selectors are used to select the specific HTML elements based on their id, name, class, attribute, type, values of attributes and etc. It also depends on the CSS Selectors. It has its own custom selectors also. These Selectors start in jQuery with a dollar sign($) and contain parentheses which has the attributes in them: $().jQuery also has custom selectors that can be used to select the elements which are based on special characteristics and special states. You can create your own custom selector.

Various jQuery selectors

To target a specific element or a set of elements inside a document,the easiest way to do this is to write a jQuery wrapper function and within that use a CSS selector. It goes like this- 

jQuery(‘#Content p a’)

what this code says is that it’s going to select all the anchor elements present inside the paragraph elements.here you can see that p tends to refer to the <p> tag for paragraph and a tends to refer to the <a> tag for anchor elements.After selecting the elements that are needed ,any of the jQuery’s methods can be run on the collection.

For Selecting an element in a page the following sections show how it’s done.

Selecting an Element by its ID

You can select the element by using the Id selector. This ID selector has a unique ID on its page. When an element needs to be selected by it’s id the syntax is $(“#first “) this selects all id with the name =first

Selecting an element by its class.

To select an element with a specific class the class selector can be used. This selects the specific class with the class name. The syntax is (“.first”) here the class name corresponding to first is called. You can note that the selecting a class starts with the ‘.’ Dot operator and for selecting an element by its id ‘#’ is used. 

Program 13:

This program adds different styles and background colors based on the ID and the class selected. An element can either be selected by it’s unique ID name or class name. After selecting the id name or the class name the styles are altered by using the .css function and passing on the specific styles to the specific div tags here.

<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() {  
  
            $(".first").css("background-color", "pink");  
            $("#name1").css("border", "1px solid blue" );  
            $("#name2").css("background-color", "green");  
            $(".second").css("font-size", "2em");  
            $("#name3").css("background-color", "purple");  
            $(".third").css("font-size","3em");  
         });  
      </script>  
   </head>  
  
   <body>  
      <div class = "first" id="name1">  
         <p>This is the starting of the First Paragraph.</p>  
      </div>  
  
      <div class = "second" id = "name2">  
         <p>This isthe starting of the second paragraph</p>  
      </div>  
  
      <div class = "third" id = "name3">  
         <p>This is the starting of the second paragraph</p>  
      </div>  
   </body>  
</html>  

.first refers to the class name first in the html file.and #name1 refers to the id in the same div tag in the html file.

Selecting an Element by its name

The element selector can be used to select elements based on the element name. So To select an element name you will need to specify the name inside the $(‘  ’).it can be a paragraph tag i.e. p or a table’s row like tr and it returns an array of all the tr or p elements found in the HTML page.

Program 14:

In this program a table is displayed in the html file.in the jQuery side the even and odd table rows are highlighted using the background color.

<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() {  
  
            $("tr:even").css("background-color", "lightblue");  
            $("tr:odd").css("background-color", "pink");  
         });  
      </script>  
   </head>  
  
   <body>  
      <table id="Table" border="1" width="100%">  
            <thead>  
                    <tr>  
                        <th class="studetid">StudentId</th>  
                        <th class="fname">First Name</th>  
                        <th class="lname">Last Name</th>  
                        <th class="rollnumber">Roll number</th>  
                        <th class="class">class</th>  
                    </tr>  
             </thead>  
            <tbody>  
                    <tr>  
                        <td class="studetid">2AJill</td>  
                        <td class="fname">Jill</td>  
                        <td class="lname">James</td>  
                        <td class="rollnumber">32</td>  
                        <td class="class">2</td>  
                    </tr>  
                    <tr>  
                        <td class="studetid">2AJane</td>  
                        <td class="fname">Jane</td>  
                        <td class="lname">Thomas</td>  
                        <td class="rollnumber">33</td>  
                        <td class="class">2</td>  
                    </tr>  
                    <tr>  
                        <td class="studetid">2AJohan</td>  
                        <td class="fname">Johan</td>  
                        <td class="lname">Thomas</td>  
                        <td class="rollnumber">34</td>  
                        <td class="class">2</td>  
                    </tr>  
             </tbody>  
        </table>  
   </body>  
</html>  

tr odd represents the odd table row and tr even represents the even table row.

Program 15:

In this program jQuery selectors are used to select the specific tags from the HTML file. The paragraph tag (p) and the div tags are selected and contents are displayed in these tags.

<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').append('This line gets added to all the P tags where ever they appear.</br>');  
            $('p:first').append('This gets added to the first P tag that appears.');  
             $('div').append('This div gets added to all the div tags that are present.');  
             $("div").html("This code adds the content in the div tags")  
             $("p:last").text("This gets added in the last p tag")  
            $("div:last").html("This gets added in the last div tag")  
         });  
      </script>  
  
   </head>  
  
   <body>  
            <p><div></div></p>  
            <p></p>  
            <div></div>  
            <p></p>  
            <div>  
  
            </div>  
  
  
  
   </body>  
</html>  

jQuery – Attributes

So what does an attribute actually mean? In terms of computing attribute actually means a specification that tends to define a property of an element, an object or a file. In terms of JQuery ,it enables you to manipulate an element’s attribute and also gives you access to the element’s instance so that you can change its properties accordingly .This can be done easily by using the attr() function.

Selecting an Element by its attribute

When we are handling the DOM elements,there are some basic components we can manipulate and these are the properties and the assigned attributes to these elements.

These attributes are available as DOM node properties through javascript.Some of the properties that are used are- The classname, the id,the title,the src,the rel

Some of the most basic components we can manipulate when it comes to DOM elements are the properties and attributes assigned to those elements.By using jQuery you can easily manipulate the attribute of an element and helps in giving us access to the element so their properties can be changed.

Getting the attribute value

The method that gets the attribute value is attr() method.This gets the value of an attribute from the first element that it finds .or it can set the attributes onto all of the matched elements.

Program 16: In this Program empty text boxes are first put in the HTML file.and by using jQuery we are populating the text boxes with the desired values.This is done by selecting the attribute input the syntax used is $(“attribute =[‘value’]”)

<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() {  
                $("input[name='first_name']" ).val("Jane");  
                $("input[name='last_name']" ).val("Thomas");  
                 $("input[name='email']" ).val("jane@thomas.com");  
                  $("input[name='zip_code']" ).val("765543");  
  
  
  
         });  
      </script>  
   </head>  
  
   <body>  
     <form>  
        <p><label>First Name: <input id="first_name" type="text" name="first_name"></label><p>  
        <p><label>Last Name: <input id="last_name" type="text" name="last_name"></label><p>  
        <p><label>Email Address: <input id = "email" type="text" name="email"></label><p>  
        <p><label>Zip Code: <input id= "zip_code" type="text" name="zip_code"></label><p>  
    </form>  
   </body>  
</html>  

The same program can be done by Selecting an element by its name and and it goes as follows-

Program 17:

<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() {  
                    $('#first_name').val("Jane");  
                    $('#last_name').val("Thomas");  
                    $('#email').val("jane@thomas.com");  
                    $('#zip_code').val("765543");  
   
  
         });  
      </script>  
   </head>  
  
   <body>  
     <form>  
        <p><label>First Name: <input id="first_name" type="text" name="first_name"></label><p>  
        <p><label>Last Name: <input id="last_name" type="text" name="last_name"></label><p>  
        <p><label>Email Address: <input id = "email" type="text" name="email"></label><p>  
        <p><label>Zip Code: <input id= "zip_code" type="text" name="zip_code"></label><p>  
    </form>  
   </body>  
</html>  

Setting the attribute value

You can also set an attributes name and its value onto the element by using the function .attr() where attr takes in two parameters and they are in the order of (name, value)

Program 19: In this program we are setting the color of each text and changing the values in the text by using the attribute function. On the click of a button which is an event the colors of the text are changed and their text also.

<html>  
  
<head>  
    <title>Jquery Tutorial</title>  
  
    <script src=  
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">  
    </script>  
    <script>  
        $(document).ready(function() {  
            $("#click1").click(function() {  
                  $("#firstext").attr("style", "color:yellow");  
                  $("#firstext").text("Hey I can change my colour");  
            });  
  
            $("#click2").click(function() {  
                $("#secondtext").attr("style", "color:red");  
                $("#secondtext").html("<b>I changed my colour too I am red now</b>");  
            });  
  
            $("#click3").click(function() {  
                 $("#thirdtext").attr("style", "color:pink");  
                $("#thirdtext").html("<b>I changed my colour too I am pink now</b>");  
            });  
        });  
    </script>  
</head>  
  
<body style="text-align:center;">  
  
    <h1 id="firstext" style = "color:blue;">  
        First Text  
    </h1>  
  
    <h2 id="secondtext">Second Text</h2>  
  
    <h3 id="thirdtext">Third Text</h3>  
  
  
  
    <button id="click1">For Line 1</button>  
    <button id="click2">For Line 2</button>  
    <button id="click3">For line 3</button>  
  
  
  
</body>  
  
</html>  

Applying Styles:

To add styles to specific elements we can use the method addClass() method. Multiple classes can be specified and they can be separated by spaces.

Program 20: In this following program there are four text boxes and these textboxes get highlighted according to the color assigned to them by the method addClass() after clicking the button.

<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>  
<style>  
 .addborder{  
  border: 1px solid red;  
  margin-bottom: 5px;  
 }  
 .limecolour {  
      border: 3px solid lime;  
  }  
   .bluecolor {  
      border: 3px solid blue;  
   }  
   .redcolor{  
      border: 3px solid red;  
             }  
 </style>  
      <script type='text/javascript'>  
            $(document).ready(function(){  
               $("button").click(function(){  
                            // Adding addborder class  
                            $('input[name="first_name"]').addClass('limecolour');  
                             $('input[name="last_name"]').addClass('limecolour');  
                              $('input[name="email"]').addClass('bluecolor');  
                               $('input[name="zip_code"]').addClass('redcolor');  
                  });  
  
});  
</script>  
</head>  
  
   <body>  
  
<div class='container'>  
                <p><label>First Name: <input type="text" name="first_name"></label><p>  
                                <p><label>Last Name: <input type="text" name="last_name"></label><p>  
                                <p><label>Email Address: <input type="text" name="email"></label><p>  
                                <p><label>Zip Code: <input type="text" name="zip_code"></label><p>  
                  <button type="button">Style Inputs</button>  
</div>  
   </body>  
</html>  

Query Selector Patterns

jQuery provides a number of ways to select a specific DOM element(s). The following table lists some of the selection patterns.

CategorySelectorDescription
Find element$(‘div’)Finds all <div> elements
$(‘p’),$(‘div’)Finds all the  <p>,<div> elements
Finds all the elements$(*)Finds all the elements.
$(‘div p’)Finds the elements that’s the descendant of div 
$(‘div > p’)Finds the p tag that is a child of the div tag
Find by Id$(‘#firstdiv’)Finds the element who has the id firstdiv .
$(‘div:has(p)’)Finds all the div elements that has the p element
$(‘#firstdiv,#seconddiv’)Finds the elements by id and these multiple id’s are separated by commas.
Find by CSS class name$(‘div.firstclass’)Finds all the div element that has the class name as firstclass.
$(‘.firstclass’)Finds all the div elements that has the class name as firstclass
$(‘.firstclass,.secondclass’)Finds all the elements whose class name is either first class or second class
Finding the  child elements$(‘p:first-child’)Finds all p tag elements that are the first child of the element
$(“p:first-of-type”)Selects the p element tag that is the first type of the parent.
$(“p:nth-child(4)”)Selects all the p tag elements that is the fourth child of the parent. 
$(“p:nth-last-child(2)”)Selects the p tag elements which is the second last of the parent element.
$(“p:last-child”)Selects the p element which has the last child of their parent.

JQuery Effects

jQuery is quite an interesting library that has the power to provide animated effects to the web page elements like hiding, scrolling etc.,

These effects takes parameters such as: 

  1. Speed – This defines how fast or slow the animation effect should be.  Either it can be mentioned as “Slow” , “Normal”, “Fast”  or in milliseconds (1000,2000)
  2. Callback function – It is a custom function that can be applied to add in extra effects as needed or if needed.  This function is completely optional. 

JQuery effects can be classified into 4 categories:-

  1. Display Effects  
  2. Fading Effects 
  3. Sliding Effects 
  4. Custom Effects

Before getting into effects, create two boxes with the following style to work along with and the corresponding buttons for the effects.

The button is given the className of “btn” with id “button” and the corresponding styles.

The “btn” is used for CSS styling while “button” will be used for jQuery script.The box is given the id of “box”.

Display Effects

  1.   .hide ()  – This method hides the element. Hide can take speed and callback function as a parameter. Both the parameters are optional. Whenever this method is called, “display” : “none” property gets added to css and hence the element gets hidden. The strings “slow” (600 ms) and “fast” (200ms) can be given for the speed.

Syntax:   $(selector).hide (speed, callback);

Example:

$(document).ready (function () {
$(‘#button’).click (function () {
$(‘#box’).hide (1000);
});

The button when clicked will hide the box.  .click () – for click event.

  1.   .show ()  – This method unhide/shows the element. Show can take speed and callback function as a parameter. Both the parameters are optional. This method will add “display:block” property to the css and hence this will unhide the element.  This method will not override “!important” of the css. The strings “slow” (600 ms) and “fast” (200ms) can be given for the speed.

Syntax:   $(selector).show (speed, callback);

Example:

$(document).ready (function () {
$(‘#button’).click (function () {
$(‘#box’).show (1000);
});

The button when clicked will show the box.  .click () – for click event.

  1. .toggle () – This method toggles the state between to and fro the element. Toggle can take speed and callback function as a parameter. Both the parameters are optional. The strings “slow” (600 ms) and “fast” (200ms) can be given for the speed. This method changes the “display” property of css to “none” or “block” based on the toggle state.

Syntax:   $(selector).toggle (speed, callback);

Example:

$(‘#button’).click (function () {
$(‘#box’).toggle (1000);
}) ;

.click () – for click event.

Fading Effects   – Opacity gets adjusted

  1.   .fadeIn ()  – This method sets the opacity to opaque. fadeIn can take speed and callback function as a parameter. The strings “slow” (600 ms) and “fast” (200ms) can be given for the speed.

Syntax:   $(selector).fadeIn (speed, callback);

Example:

  $(‘#button’).click (function () {

                    $(‘#box’).fadeIn (1000);

                });

. .click () – for click event.

  1.   .fadeOut ()  – This method sets the opacity to transparent. fadeOut can take speed and callback function as a parameter. The strings “slow” (600 ms) and “fast” (200ms) can be given for the speed.

Syntax:   $(selector).fadeIn (speed, callback);

Example:

    $(‘#button’).click (function () {

                    $(‘#box’).fadeOut (1000);

                });

.click () – for click event.

  1.   .fadeToggle ()  – This method sets the opacity to opaque or transparent depending on the previous state. fadeToggle can take speed and callback function as a parameter. The strings “slow” (600 ms) and “fast” (200ms) can be given for the speed.

Syntax:   $(selector).fadeToggle (speed, callback);

Example:

  $(‘#button’).click (function () {

                    $(‘#box’).fadeToggle (1000);

                });

 .click () – for click event.

  1.  .fadeTo ()  – This method sets the opacity as given in the argument. fadeTo can take speed, opacity and callback function as a parameter. The strings “slow” (600 ms) and “fast” (200ms) can be given for the speed. Opacity can range from 0 to 1.

Syntax:   $(selector).fadeTo (speed, callback);

Example:

  $(‘#button’).click (function () {

                    $(‘#box’).fadeTo (1000, 0.5, function () {

                });.

 .click () – for click event.

Sliding Effects – Height gets animated

  1.   .slideUp ()  – This method animates the height of the element. It slides up and conceals elements. slideUp can take speed and callback function as a parameter. The strings “slow” (600 ms) and “fast” (200ms) can be given for the speed.

Syntax:   $(selector).slideUp (speed, callback);

Example:

  $(‘#button’).click (function () {

                    $(‘#box’).slideUp (1000);

                });

 .click () – for click event.

  1.   .slideDown ()  – This method animates the height of the element. It slides down and reveals elements. SlideDown can take speed and callback function as a parameter. The strings “slow” (600 ms) and “fast” (200ms) can be given for the speed.

Syntax:   $(selector).slideDown (speed, callback);

Example:

      $(‘#button’).click (function () {

                    $(‘#box’).slideDown (1000);

                });

3.  .slideToggle () – This method sets the height to conceal or reveal depending on the previous state. slideToggle can take speed and callback function as a parameter. The strings “slow” (600 ms) and “fast” (200ms) can be given for the speed.

Syntax:   $(selector).slideToggle (speed, callback);

Example:

    $(‘#button’).click (function () {

                    $(‘#box’).slideToggle (3000);

                });

 .click () – for click event.

Custom Effects – Extra effects that are not provided “out of the box”

  1.  .animate () – This method brings the animation by changing the numeric css property. For example: width, height, left can be modified but “background-color” cannot be modified as it’s a string css property. The numeric properties are considered to be in pixels by default.  “em” and “%” can also be used. “scrollTop” and “scrollLeft” are a few non-style property that can be animated.”+=” or “-=” can also be given to the property and the corresponding value will get added as needed. If duration is mentioned, then the element will complete its animation within the stipulated time.

Syntax: $(selector).animate ({property}, duration, function);

Example: 

$(“#button”).click (function () {
$(“#box”).animate ({
left:500,
height:’300px’,
width:’300px’,
opacity:0.5
});
});

The box will to the right first, then the height of the box will change, then it’s width will change and then the opacity will be reduced to 0.5.  Duration can also be added if needed as the second argument to the animate method.

  1. .delay() – This method will help to add delay the element.  Any effects mentioned post this delay method will execute only after pausing for the duration mentioned in the delay.

Syntax :

 $(selector).delay (duration)

Example:

$(“#button”).click (function () {

                    $(“#box”).slideUp (300).delay (800).fadeIn (300);

                });

In this example, the box will first slides up then after pausing for 800ms, the box will fade in.

  1. .stop ()  – This method halts the animation effects that’s running. It takes in two optional parameter clearQueue and jumpToEnd.  The default value for the both the argument is false. clearQueue if given True will remove all the animations in the queue. jumpToEnd if given True will end the current animation immediately. 

Syntax :

$(selector).stop ();

Example:

$(‘#button’).click (function () {

$(‘#box’).stop ();

});

The other animations effects are:

  1.  .queue () –This method will add the effects mentioned in this to the web element. 
  2. .dequeue () – This method will remove the effects that are imposed by .queue () and then the next effect will get executed.
  3. .clearQueue () – This method will remove all the effects that are not executed in the queue yet.
  4. .finish () – This method will stop the animation and removes the effects from the queue.
  5. jQuery.fx.off – This method will stop all the effects to all the elements in the page. This is mainly used when there are accessibility issues for the users, or when sufficient resources are not available for the jQuery effect to get executed. This can be reversed by setting the property to “false”.

JQuery User Interface

JQuery UI is a collection of higher interactive user effects, widgets, themes that is built on the basic jQuery.  To use this, one needs to either download it or can be used as a CDN.

To download use this link:

https://jqueryui.com/download/

For Google CDN:

http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js

JQuery UI Core

  1. : data ()  – This method is used to select the elements which has the same value that matches with the key .

Syntax:

                     :data (key)

Example: 

   $(“#box”).data (“color”, “blue”);

                $(“: data (color)”).each (function () {

                    var element = $(this);

                    element.css (“backgroundColor”, element.data (“color”));

                });

Here in this example,     .data () stores the value “blue” under the variable “color”. 

The Key here is “color” which is mentioned in: data (color).

The color blue is applied as a background color for those elements which has the variable “color” stored in it.

  1. .disableSelection() – This method does not allow to select the element.

Syntax:

                     $(selector).disableSelection ();

Example:

        $(‘#text’).disableSelection ();

Here “text” is the id given to a paragraph.  This method will not allow the user to select that paragraph.

  1. .enableSelection() – This method does not allow to select the element.

Syntax:

                     $(selector).enableSelection ();

Example: 

   $(‘#text’).enableSelection ();

Here “text” is the id given to a paragraph.  This method will allow the user to select that paragraph.

  1. : focusable  – This method selects the elements that could be focused.  The focusable elements are :
  • Input
  • Select
  • Textarea
  • Button
  • Object
  • Anchor tag – Focusable only if they have an “href” attribute or “tabindex” attribute.
  • Area tag – Focusable only if they have an “href”, “named map” and “visible image using the map”.
  • Elements with negative tab index are focusable as well.

Syntax:

(“: focusbale”)

Example:

$(‘: focusable’).css (“border-color”, ‘red’);

This example will select all the focusable elements in the page and then gives a “border-color” as “red”.

  1. jQuery.ui.keyCode – This method matches the input from the keyboard to their numeric values. 

The keyCodes are as follows :

  • BACKSPACE
  • COMMA
  • DELETE
  • DOWN
  • END
  • ENTER
  • ESCAPE
  • HOME
  • LEFT
  • PAGE_DOWN
  • PAGE_UP
  • PERIOD
  • RIGHT
  • SPACE
  • TAB
  • UP

Example:

$ (Document) .on (“keydown”, function (event) {

                    switch (event.keyCode) {

                        case $ .ui.keyCode.LEFT:

                            $(‘#text’).text (“You pressed left”);

                         break;

                         case $ .ui.keyCode.RIGHT:

                            $(‘#text’).text(“You pressed right”);

                        break;

                        }

            });

In this example – “You pressed left” or “You pressed right” will appear when the keyboard left/right button is pressed.

  1. :tabbable  – This method selects the elements that could be focused via tab button.  The tabbable elements are :
  • Input
  • Select
  • Textarea
  • Button
  • Object
  • Anchor tag  – Focusable only if they have an “href” attribute or positive “tabindex” attribute.
  • Area tag – Focusable only if they have an “href”, “named map” and “visible image using the map”.
  • Elements with negative tab index are focusable as well.

Syntax:

(“:tabbable”)

Example :

$(‘: tabbable’).css (“border-color”, ‘red’);

This example gives the border color red which can be viewed with tab key stroke.

  1. .uniqueId()  –  This method will generate “id” if an element doesn’t have any.The Id will be generated only after checking for the presence of “id” attribute.

Syntax:

$(selector).uniqueId ();

  1. .removeUniqueId ()  – This method will remove all the “id” that got generated when .uniqueId () is called upon.

Syntax:

$(selector).removeUniqueId ();

  1. .scrollParent()  – This method will find the element that is nearest to the element selected which can be scrolled. It works only on jQuery objects containing only one element.

Syntax:

$(selector).scrollParent ();

JQuery UI Interactions

  1. Draggable Widget – This method will make the element to be able to be dragged by mouse.

Dropppable elements will act as the drop target for the draggable elements. Draggable widgets borrows the help for its theme from jQuery UI CSS framework. To style the draggable widgets, the classes “ui-draggable”, “ui-draggable-disabled”, “ui-draggable-dragging” and “ui-draggable-handle” can be used.  The following options, methods, events can be used along with draggable widget elements.

$(“#box”).draggable();

  1. Droppable Widget –   They become the targets for the draggable objects.They accept being dropped upon.  “ui-droppable”,”ui-droppable-active” and “ui-droppable-hover”  are the CSS classes which can be used to edit the styles of the droppable as needed.

The following options, methods and events can be used with droppable.

Events:

Syntax:

$(selector).droppable ();

Example:

$(‘#box’).droppable ();

  1. Mouse Interaction  – This should be modified as other jQuery widgets will be using this as a base layer. The following options,methods and widgets can be used with this

Syntax:

$(selector).mouse();

Example:

$(‘#button’).mouse ();

  1. Resizable Widget – Element will be resized based on the mouse actions.  The CSS classes for styling the elements are :
    1. ui-resizable
    2. ui-resizable-resizing
    3. ui-resizable-autohide
    4. ui-resizable-handle
    5. ui-resizable-{direction}
    6. ui-resizable-ghost
    7. ui-resizable-helper

The following options, methods, events can be used with this method.

Syntax:

$(selector).resizable ();

Example:

$(‘#box’).resizable ();

  1. Selectable Widget – This method allows to select the item or items on the web page. Elements can be selected via click or drag or with ctrl button.

The following CSS classes are used for styling the widget:

  1. ui-selectable
  2. ui-selectee
  3. ui-selecting
  4. ui-selected
  5. ui-unselecting

The options, methods, events that can be used with this are :

Syntax :

$(selector).selectable();

Example:

$(“#box”).selectable ();

  1. Sortable Widget – This method helps to reorder the elements in the group. Css classes –  “ui-sortable”,”ui-sortable-handle”,”ui-sortable-placeholder”,”ui-sortable-helper” are the classes which can be styled as needed.

The following options, methods, events can be used with sortable.

Syntax:

$(selector).sortable ();

Example:

$(‘#group’).sortable ();

This will enable the user to drag and sort the elements in the group.

JQuery UI Widgets

Widgets are small plugins that jQuery provides which can be just added with jQuery methods instead of creating from the base.

  1. .accordion ()   – This method helps to create an accordion which is nothing a list of elements that area headers that are vertically stacked upon each other.

The following options, methods and events can be used along with accordion

The accordion container should have a pairs of headers and contents.  So that the following output can be obtained.

Here the “Section 1”  “Section 2” and “Section 3” are the headers that has content inside it. This entire pair gets packed inside a parent container to which the jQuery method can be applied upon.

The following keyboard interactions are available:

  • UP/LEFT  – Move the focus to previous header
  • DOWN/RIGHT – Move the focus to next header
  • HOME – Move the focus to first header
  • END – Move the focus to last header
  • SPACE/ENTER – Activate panel associated with focused header
  • CTRL + UP – Move focus to associated header

The Css classes that can be used for this method is:  

  • “ui-accordion”
  • “ui-accordion-header”
  • “ui-accordion-header-activator”
  • “ui-accordion-header-collapsed”
  • “ui-accordion-icons”
  • “ui-accordion-header-icons”
  • “ui-accordion-content”
  • “ui-accordion-content-active”

Syntax:

$(selector).accordion ();

Example:

$(“#accordion”).accordion ();

  1. .tabs ()  – Tabs are similar to accordion but are more in tab format. Where each tab will open up a section by clicking on the tab.Accordions are vertically stacked while tabs are horizontally stacked.  Tabs saves more space compared to accordions.

Tabs should have the following format to work properly.

  1. The tabs should be given in an ordered or unordered list
  2. The tab title should be enclosed with an list item and anchor tag
  3. The tab panels must have an id that matches with the href of the anchor tag.

Content for the panel can be loaded via AJAX or can be defined in HTML itself.

The tabs should look like this:

The following keyboard interactions are available:

  • UP/LEFT  – Move the focus to previous tab
  • DOWN/RIGHT – Move the focus to next tab
  • CTRL +HOME / HOME – Move the focus to first tab
  • CTLR + END / END – Move the focus to last tab
  • SPACE/ENTER – Activate panel associated with focused tab
  • CTRL + UP/LEFT – Move the focus to previous tab
  • CTRL + DOWN/RIGHT- Move the focus to next tab
  • ALT + OPTION / PAGE UP – Move focus to previous tab and immediately activate
  • ALT + OPTION /PAGE DOWN – Move focus to next tab and immediately activate

The following CSS classes can be used with this method :

  • “ui-tabs”
  • “ui-tabs-collapsible”
  • “ui-tabs-nav”
  • “ui-tabs-tab”
  • “ui-tabs-active”
  • “ui-tabs-loading”
  • “ui-tabs-anchor”
  • “ui-tabs-panel”

Syntax :

$(selector).tabs();

Example :-

$(‘#tabs’).tabs();

  1. .menu () –   Simply said this method creates the “menu” widget which is nothing but a list of list items that can be clicked upon.

To create a menu parent/child relationship has to be maintained. Unordered list is the most commonly used element. Content of each menu item should be a block level element.

Keyboard Interactions:

  • ENTER/SPACE  Invoke the focused menu item that can open a submenu
  • UP –Move focus to the previous item
  • DOWN – Move focus to the next menu item
  • RIGHT – Open the submenu if available
  • LEFT – Close the current menu and move the focus back to parent element
  • ESCAPE – Close the current menu

The following CSS styles can be used to change the style for the menu.

  • “ui-menu”
  • “ui-menu-icons”
  • “ui-menu-item”
  • “ui-menu-item-wrapper”
  • “ui-menu-icon”
  • “ui-menu-divider”

The following options, methods and events can be used for this method


Syntax:

$(selector).menu ();

Example:

$(‘#menu’).menu ();

  1. .tootltip ()  – Provided the tooltip where needed. Tooltip can display the content obtained from AJAX  or footnotes or warnings .  Customization can be done for the tooltip. Fade animation effect is used to show and hide the tooltip.

Keyboard Interactions :   

Escape – Close the tooltip

The CSS classes that can be used to style this method is:

  • “ui-tooltip”
  • “ui-tooltip-content”

The following options, methods and events can be used for this method

Syntax:

jQuery.tooltip ();

Example:

$(document).tooltip ();

The title attribute of the input element will be the tooltip.

  1. .datepicker() – This is used to help pick up a date.

The following options, methods and events can be used for this method

The datepicker’s following functionalities can be configured :

  • Date format
  • Language
  • Date ranges
  • Buttons
  • Navigation options

Keyboard Interaction

The following keyboard interactions are available :

  • CTRL +HOME– Open the datepicker if close
  • PAGE UP – Move to the previous month
  • PAGE DOWN – Move to the next month
  • CTRL + PAGE UP – Move to the previous year
  • CTRL + PAGE DOWN – Move to the next year
  • CTRL /COMMAND + HOME – Move to the current month
  • CTRL/COMMAND + LEFT – Move to the previous day
  • CTRL/COMMAND + RIGHT – Move to the next day
  • CTRL/COMMAND + UP – Move to the previous week
  • CTRL/COMMAND + DOWN – Move to the next week
  • ENTER – Select the focused date
  • CTRL/COMMAND + END – Close the datepicker and erase the date.
  • ESCAPE – Close the datepicker without selection

Utility Functions

  1. $datepicker.setDefaults (options) – Changes the default option for all datePickers.  To change individual settings choose options() method
  2. $datepicker.formateDate(format,date,options) – To format the date with a specified format into a string
  3. $datepicker.parseDate (format, value, options) – Extract dates from the given string along with a mentioned format.
  4. $datepicker.iso8601Week(date) – Determine the number of week for the current year
  5. $datepicker.noWeekends – Doesn’t allow to select weeks

Localization

JQuery Datepickers supports all languages.  The corresponding script file can be added to the <script> tag of HTML page.  The localized files can be obtained from 

https://github.com/jquery/jquery-ui/tree/master/ui/i18n.

$datepicker.regional[“language_code“]  – This can also be used.  Default is English.

The following CSS classes can be used with this method.

  • “ui-datepicker”
  • “ui-datepicker-inline”
  • “ui-datepicker-rtl”
  • “ui-datepicker-header”
  • “ui-datepicker-prev”
  • “ui-datepicker-next”
  • “ui-datepicker-title”
  • “ui-datepicker-month”
  • “ui-datepicker-year”
  • “ui-datepicker-calendar”
  • “ui-datepicker-week-end”
  • “ui-datepicker-other-month”
  • “ui-datepicker-unselectable”
  • “ui-datepicker-current-day”
  • “ui-datepicker-today”
  • “ui-datepicker-buttonpane”
  • “ui-datepicker-current”
  • “ui-datepicker-multi”
  • “ui-datepicker-group”

Syntax:

$(selector).datepicker();

Example:

$(‘#datepicker’).datepicker ();

  1. .button () – This is used to create buttons.  This method can create buttons out of anchor tag not only restricted to input tag having the type button. When used with type button/submit/reset is limited to plaint text labels and no icons.

The following options, methods and events can be used for this method

The following CSS methods can be used to modify the styles:

  • “ui-button”
  • “ui-button-icon-only”
  • “ui-button-icon”
  • “ui-button-icon-space”

Syntax:

$(selector).button();

Example:

$(‘#button’).button ();

  1. .autocomplete ()  – This widget is used to complete the input if the match is found in the list. Any input field can use this autocomplete feature. The typed data can be matched with the data from local storage or from remote source.

The following options, methods and events can be used for this method


Keyboard Interactions :

  • UP – Move focus to the previous item
  • DOWN – Move focus to the next item
  • ESCAPE – Close the menu
  • ENTER –Select the currently focused item and close the menu
  • TAB – Select the currently focused item, close the menu and move focus to the next item.
  • PAGE UP/DOWN – Scroll through the page of items.
  • UP/DOWN – Open the menu, if the minLength has been met.

The following CSS methods can be used to style the widget:

  • “ui-autocomplete”
  • “ui-autocomplete-input”
  • “ui-autocomplete-loading”

Syntax:

$(selector).autocomplete ();

Example:

$(‘#autocomplete’).autocomplete ();

  1. .buttonset () – This can be used when there are more than one button and all the buttons belong to the same group. Whenever this widget is used, .button () is called for each button in the group. Whenever the button group is destroyed, .destroy () is called upon each and every button.

The following options, methods and events can be used for this method


“ui-buttonset”   is the CSS class that can be used for styling the buttonset.

Syntax:

$(selector).buttonset();

Example:

$(“#buttonset’).buttonset();

  1. .checkboxradio() – This is used to convert checkboxes and radio buttons to buttons.

The following options,methods and events can be used for this method


The following CSS classes can be used to modify the styles

  • “ui-checkboxradio”
  • “ui-checkboxradio-label”
  • “ui-checkboxradio-checked”
  • “ui-checkboxradio-radio-label”
  • “ui-checkboxradio-icon”
  • “ui-checkboxradio-icon-space”

Syntax:

$(selector).checkboxradio();

Example:

$(‘#checkboxradio’).checkboxradio();

  1. .controlgroup() – This is for styling buttons and other input elements. It provides grouping visually.

The following options,methods and events can be used for this method

The CSS classes that can be used are:

  • “ui-controlgroup”
  • “ui-controlgroup-horizontal”
  • “ui-controlgroup-vertical”
  • “ui-controlgroup-item”

Syntax:

$(selector).controlgroup ();

Example:

$(‘#controlgroup’).controlgroup ();

  1. .dialog ()  – This is used to create a dialogbox. Dialog box will have buttons  and can be resized. Once the dialogbox opens, the focus automatically goes to the first item inside the dialogbox.The close button can be hidden styling via CSS.

The following options, methods and events can be used for this method

The following CSS classes can be used to modify the style:

  • “ui-dialog”
  • “ui-dialog-dragging”
  • “ui-dialog-resizing”
  • “ui-dialog-buttons”
  • “ui-dialog-titlebar”
  • “ui-dialog-title”
  • “ui-dialog-content”
  • “ui-dialog-buttonpane”
  • “ui-dialog-buttonset”

Syntax:

$(selector).dialog ();

Example:

$(‘#dialog’).dialog ();

  1.  .progressbar () – It displays the status of the process.The bar can be customized as needed. Determinate progress bar should be used only when they status is known. If the status is not known then undeterminate progress bar can be used.

The following options, methods and events can be used for this method


The CSS classes used here for styling this:

  • “ui-progressbar”
  • “ui-progressbar-indeterminate”
  • “ui-progressbar-complete”
  • “ui-progressbar-value”
  • “ui-progressbar-overlay”

Syntax:

$(selector).progressbar ();

Example:

$(‘#progressbar’).progressbar ();

  1. .selectmenu ()  – This is used when selection is to be made from a drop down list. It acts as a proxy to the <select> tag. Options can be disabled by adding “disabled” attribute.

Keyboard Interaction

Options when the menu is open

  • UP/LEFT: Move focus to the previous item.
  • DOWN/RIGHT: Move focus to the next item.
  • END/PAGE DOWN: Move focus to the last item.
  • HOME/PAGE UP: Move focus to the first item.
  • ESCAPE: Close the menu.
  • ENTER/SPACE: Select the currently focused item and close the menu.
  • ALT/OPTION + UP/DOWN: Toggle the visibility of the menu.

Options when the menu is close

  • UP/LEFT: Select the previous item.
  • DOWN/RIGHT: Select the next item.
  • END/PAGE DOWN: Select the last item.
  • HOME/PAGE UP: Select the first item.
  • ALT/OPTION + UP/DOWN: Toggle the visibility of the menu.
  • SPACE: Open the menu.

The following CSS class names can be used:

  • “ui-selectmenu-button”
  • “ui-selectmenu-button-closed”
  • “ui-selectmenu-button-open”
  • “ui-selectmenu-button-text”
  • “ui-selectmenu-button-icon”
  • “ui-selectmenu-button-menu”
  • “ui-selectmenu-button-optgroup”

Syntax:

$(selector).selectmenu ();

Example:

$(‘#select’).selectmenu ();

  1. .slider () – It is used to slide to a numeric value. The slide has a handle that can be moved with the mouse or the arrow keys.

The following options, methods and events can be used for this method

CSS classes for styling:

  • “ui-slider”
  • “ui-slider-horizontal”
  • “ui-slider-vertical”
  • “ui-slider-handle”
  • “ui-slider-range”
  • “ui-slider-range-min”
  • “ui-slider-range-max”

Sytanx:

$(selector).slider();

Example:

$(‘#slide’).slide();

  1.  .spinner ()  – It is used to update the number with the help of up and down arrow keys. User can type the value or modify it using the arrow buttons either via mouse or arrow keys from keyboard.

CSS classes for styling:

  • “ui-spinner”
  • “ui-spinner-input”
  • “ui-spinner-button”
  • “ui-spinner-up”
  • “ui-spinner-down”

Sytanx:

$(selector).spinner ();

Example:

$(‘#slide’).spinner ();

  1. Widget Plugin Bridge  – It acts as the intermediate between jQuery API and $.widget().It creates instance for the object and stores it under $.data cache. It doesn’t allow private methods but allows only public methods and provides protection against multiple initializations.

Syntax:

jQuery.widget.bridge (name, constructor)

name – name of the plugin for which bridge is to be formed

constructor – the object that needs to be invoked when the plugin is invoked.

Example:

$.widget.bridge (“colorToggle”,Highlighter);

  1. Widget factory –   This helps to create new widgets. This allows to inherit the widgets as well. To track the state of the widget, full life cycle for the widget should be introduced. The life cycle starts when the widget gets initialized. Call the plugin to initialize the widget. Options can also be passed to the widget if’s it’s needed. Options are to be passed during the initialization phase. All options are deep copied so that widgets will not get affected later. Name of the method is passed to the jQuery plugin in order to call the method on the widget. Each widget will have its own set of methods. Events are there for all the widgets. Instance () can be used to retrieve the widget’s instance.

Properties of the widgets:

  1. default Element 
  2. document
  3. element
  4. namespace
  5. options
  6. uuid
  7. version
  8. widgetEvenPrefix
  9. widgetFullName
  10. widgetName
  11. window

Syntax:

jQuery.widget(name,[, base],prototype);

name – name of the widget to be created

base – Base widget to inherit from

prototype – objet to use as a prototype for the widget.

JQuery UI Theming

JQuery UI library also has a rich collection of CSS frameworks that can be used easily with all of the above widgets, methods, elements etc., It also has a rich collection of Icons that can be used with all the above elements. JQuery UI library provides “Themes” that can be downloaded from the jQuery UI official site. The downloads will have the corresponding CSS files both the compressed and uncompressed versions.

CSS FRAMEWORK

The following list of classes can be used across all of the themes provided by jQuery UI.

LAYOUT HELPERS

  • .ui-helper-hidden
  • .ui-helper-hidden-accessible
  • .ui-helper-reset
  • .ui-helper-clearfix
  • .ui-front

WIDGET CONTAINERS

  • .ui-widget
  • .ui-widget-header
  • .ui-widget-content

INTERACTION STATES

  • .ui-state-default
  • .ui-state-hover
  • .ui-state-focus
  • .ui-state-active

INTERACTION CUES

  • .ui-state-highlight
  • .ui-state-error
  • .ui-state-error-text.
  • .ui-state-disabled
  • .ui-priority-primary
  • .ui-priority-secondary

ICONS

States and images

Icon Types

There are many icon types provided by jQuery UI which can be got fromabout:blankEmbed URLPaste a link to the content you want to display on your site.EmbedLearn more about embeds(opens in a new tab)Sorry, this content could not be embedded.Try again Convert to link

Misc Visuals

Corner Radius helpers

  • .ui-corner-tl
  • .ui-corner-tr
  • .ui-corner-bl
  • .ui-corner-br
  • .ui-corner-top
  • .ui-corner-bottom
  • .ui-corner-right
  • .ui-corner-left
  • .ui-corner-all

Overlay & Shadow

  • .ui-widget-overlay
  • .ui-widget-shadow

JQuery Tutorial FAQs

Q: What is jQuery used for? 

A: jQuery is a JavaScript library that is designed to make HTML DOM tree traversal and manipulation, along with CSS animation, event handling, and Ajax. It is absolutely free, open-source software that uses the permissive MIT License.

Q: What are the basics of jQuery? 

A: The basics of jQuery include String, Numbers, Boolean, Objects, Arrays, Functions, Arguments, Context, Scope, Callback, Closures, Proxy Pattern, Built-in Functions, and Document Object Model.

Q: Is jQuery easy to learn? 

A: It is not at all tough to learn. It in fact is even easier than Javascript. However, if you want to master every method of jQuery, it may be a little difficult but you can of course learn it.

Q: Where can I learn jQuery? 

A: You can learn jQuery through Great Learning. The jQuery tutorial you will find at Great Learning is ideal for beginners as it comes with examples.

Q: Is jQuery back end? 

A: jQuery is a JavaScript library and cannot be used on the backend. It instead can be used within the scope of a browser.

Q: Should I learn JavaScript or jQuery first? 

A: If you have a basic understanding of CSS and HTML, you can learn jQuery. However, if you have already learned JavaScript, it would be a lot easier to learn jQuery.

Q: Can I learn jQuery without knowing JavaScript? 

A: Knowing JavaScript is recommended to those who want to learn jQuery. The better you know JavaScript, the faster you will learn jQuery.

Q: What is $() in jQuery?

A: It is a selector function in JavaScript. In jQuery, the $ function does a lot more than just selecting things. It can be passed to a selector to get a collection of similar elements from DOM.

Q: How long will it take to learn jQuery? 

A: If you have a thorough knowledge of JavaScript, it will hardly take 4-5 hours for you to learn jQuery. However, once you learn it, you need to practice it.

Q: What are jQuery examples? 

A: The jQuery examples include jQuery Selectors, jQuery Events, jQuery Hide/Show, jQuery Fade, jQuery Slide, jQuery Animate, jQuery Stop Animations, jQuery HTML Get Content and Attributes, jQuery HTML Set Content and Attributes, jQuery HTML Add Elements/Content, etc.

Q: What does () => mean in jQuery? 

A: This new feature in JavaScript has been introduced in ES6, and is called the arrow function. The left part means the input of a function and the right part means the output of the same function.

Q: What is the jQuery syntax?

A: jQuery syntax is customized for selecting HTML elements as well as performing some of the actions of the elements. Basic syntax is: $(selector).action() A $ sign to define/access jQuery.

This brings us to the end of the blog on jQuery Tutorial. Hope this helps you to up-skill and boost your expertise. To learn more about jQuery and other related concepts, check out the courses on Great Learning Academy

Also, check out this free live master class on jQuery to gain more insights.

Avatar photo
Great Learning Team
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Leave a Comment

Your email address will not be published. Required fields are marked *

Great Learning Free Online Courses
Scroll to Top