5. jQuery

5.1. Introduction

jQuery is the Javascipt library.

5.1.1. Requirements

  • First create a file ‘jQuery.html’. Next, we need three files, i.e. one CSS (Line 9) and two Javascipt (Lines 23-24), for using the jQuery in this tutorial. These files are saved inside the folder ‘asset’, which can be downloaded from the repository. Lines 9 and 24 are the bootstrap files, whereas Line 23 is the actual ‘jQuery’ file which is required to use the jQuery.

Note

Note that, the ‘jQuery.js’ files should be placed above the ‘bootstrap.js’ file, otherwise the bootstrap-javascipt will not work.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!-- jQuery.html  -->

<!DOCTYPE html>
<html>
<head>
    <title>jQuery</title>

    <!-- CSS -->
    <link href="asset/css/bootstrap.min.css" rel="stylesheet">
    <!-- Add Custom styles below -->

</head>
<body>







    <!-- Javascript -->
    <!-- put jQuery.js before bootstrap.min.js; and then add custom jquery-->
    <script src="asset/js/jquery-3.3.1.min.js"></script>
    <script src="asset/js/bootstrap.min.js"></script>

</body>
</html>
  • If we open this html file in the browser, the a blank page will be displayed with header ‘jQuery’.

5.1.2. Add contents

Next add one jumbotron (Line 15-19) and few labels (Lines 21-26) in the html file as shown in Fig. 5.1.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<!-- jQuery.html  -->

<!DOCTYPE html>
<html>
<head>
    <title>jQuery</title>

    <!-- CSS -->
    <link href="asset/css/bootstrap.min.css" rel="stylesheet">
    <!-- Add Custom styles below -->

</head>
<body>

    <div class="jumbotron">
        <div class="col-md-offset-4 container">
            <h1><b>jQuery</b></h1>
        </div>
    </div>

    <span class="label label-lg label-default" id="l_default">Default</span>
    <span class="label label-primary" id="l_primary">Primary</span>
    <span class="label label-success" id="l_success">Success</span>
    <span class="label label-info" id="l_info">Info</span>
    <span class="label label-warning" id="l_warning">Warning</span>
    <span class="label label-danger" id="l_danger">Danger</span>




    <!-- Javascript -->
    <!-- put jQuery.js before bootstrap.min.js; and then add custom jquery-->
    <script src="asset/js/jquery-3.3.1.min.js"></script>
    <script src="asset/js/bootstrap.min.js"></script>

</body>
</html>
../_images/jquery1.png

Fig. 5.1 Jumbotron and labels are added

5.2. jQuery examples

Following are the important parts for writing a jQuery,

  • Selectors : to select the specific element (e.g. ‘id’, ‘class’ etc.) for operations.
  • Event handling : perform some operations (hide, toggle etc.) on the selected items at some events (e.g. click, mouser over etc.).

In this section, we will see the working of of jQuery with the help of some examples. Then in Section 5.3, we will see various methods to use the selectors to target the specific elements. Next, a list of operations are shown in Table 5.2. Finally in Section 5.5, a list of events are shown which can be used to initiate the operations.

5.2.1. Add jQuery code

Now, we can add the jQuery code as shown in Lines 36-40. Please note the following part,

  • $ sign is used to hit the jQuery. In the simple words, we can say that it execute the jQuery.

  • The code is written between the following block. This block stops the jQuery to execute until the whole page is loaded, i.e. jQuery will be executed after completion of the page-download.

    $(function() {
            // write code here
    });
    
  • The above block is a shorthand for below,

    $(document).ready(function() {
            // write code here
    });
    

Note

We can use multiple blocks, if we want to separate the codes; or we can write all the jQueries within one block.

  • Lastly, the below line hides the id “l_default” after 1000 ms, i.e. ‘Default’ label will not be displayed after 1000 ms as shown in Fig. 5.2

    $("#l_default").hide(1000); // hide id = 'l_default' using # operator after 300 ms
    
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!-- jQuery.html  -->

<!DOCTYPE html>
<html>
<head>
    <title>jQuery</title>

    <!-- CSS -->
    <link href="asset/css/bootstrap.min.css" rel="stylesheet">
    <!-- Add Custom styles below -->

</head>
<body>

    <div class="jumbotron">
        <div class="col-md-offset-4 container">
            <h1><b>jQuery</b></h1>
        </div>
    </div>

    <span class="label label-lg label-default" id="l_default">Default</span>
    <span class="label label-primary" id="l_primary">Primary</span>
    <span class="label label-success" id="l_success">Success</span>
    <span class="label label-info" id="l_info">Info</span>
    <span class="label label-warning" id="l_warning">Warning</span>
    <span class="label label-danger" id="l_danger">Danger</span>




    <!-- Javascript -->
    <!-- put jQuery.js before bootstrap.min.js; and then add custom jquery-->
    <script src="asset/js/jquery-3.3.1.min.js"></script>
    <script src="asset/js/bootstrap.min.js"></script>

    <script type="text/javascript">
        $(function() {
            $("#l_default").hide(1000); // hide id = 'l_default' using # operator after 300 ms
        });
    </script>
</body>
</html>
../_images/jquery2.png

Fig. 5.2 Label ‘Default’ is hidden after 1000 ms

Note

‘#’’ is used to select the ‘id’; whereas ‘.’ is sued to access the ‘class’.

  • In the below code, the label ‘Danger’ is removed; and “opacity=‘0.5’” is set for rest of the labels. Here, ‘.label’ selects all the classes which have the name ‘label’ in it. Since all the entries have classes with name ‘label’, therefore all are selected and faded according to ‘opacity=‘0.5’, as shown in Fig. 5.3.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!-- jQuery.html  -->

<!DOCTYPE html>
<html>
<head>
    <title>jQuery</title>

    <!-- CSS -->
    <link href="asset/css/bootstrap.min.css" rel="stylesheet">
    <!-- Add Custom styles below -->

</head>
<body>

    <div class="jumbotron">
        <div class="col-md-offset-4 container">
            <h1><b>jQuery</b></h1>
        </div>
    </div>

    <span class="label label-lg label-default" id="l_default">Default</span>
    <span class="label label-primary" id="l_primary">Primary</span>
    <span class="label label-success" id="l_success">Success</span>
    <span class="label label-info" id="l_info">Info</span>
    <span class="label label-warning" id="l_warning">Warning</span>
    <span class="label label-danger" id="l_danger">Danger</span>




    <!-- Javascript -->
    <!-- put jQuery.js before bootstrap.min.js; and then add custom jquery-->
    <script src="asset/js/jquery-3.3.1.min.js"></script>
    <script src="asset/js/bootstrap.min.js"></script>

    <script type="text/javascript">
        $(function() {
            $("#l_default").hide(1000); // hide id = 'l_default' using # operator after 300 ms
            $(".label-danger").hide();  // hide class = 'label' using . operator
            $(".label").css({opacity:'0.5'}); // add opacity to all classes with name 'label'
        });
    </script>
</body>
</html>
../_images/jquery3.png

Fig. 5.3 Faded labels

5.2.2. jQuery in separate file

It is better to write the jQuery in the separate files, therefore the codes are more manageable.

  • For this, first write the code in the separate file ‘my_jquery.js’ as below,

Note

‘html’ is used to change the content of the ‘id’ as shown in Line 5 below listing (see Fig. 5.4)

1
2
3
4
5
6
// asset/js/my_jquery.js

$(function() {
        $("#l_default").hide(1000); // hide id = 'l_default' using # operator after 300 ms
        $(".label-danger").html("Shark is dangerous");  // change content using 'html'
});
  • Next, import this file to ‘html’ as shown in Line 35 of below code,
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!-- jQuery.html  -->

<!DOCTYPE html>
<html>
<head>
    <title>jQuery</title>

    <!-- CSS -->
    <link href="asset/css/bootstrap.min.css" rel="stylesheet">
    <!-- Add Custom styles below -->

</head>
<body>

    <div class="jumbotron">
        <div class="col-md-offset-4 container">
            <h1><b>jQuery</b></h1>
        </div>
    </div>

    <span class="label label-lg label-default" id="l_default">Default</span>
    <span class="label label-primary" id="l_primary">Primary</span>
    <span class="label label-success" id="l_success">Success</span>
    <span class="label label-info" id="l_info">Info</span>
    <span class="label label-warning" id="l_warning">Warning</span>
    <span class="label label-danger" id="l_danger">Danger</span>




    <!-- Javascript -->
    <!-- put jQuery.js before bootstrap.min.js; and then add custom jquery-->
    <script src="asset/js/jquery-3.3.1.min.js"></script>
    <script src="asset/js/bootstrap.min.js"></script>
    <script src="asset/js/my_jquery.js"></script>

</body>
</html>
../_images/jquery4.png

Fig. 5.4 Changed content using ‘html’ option

5.2.3. Get input from user

Below is the complete html code, which we will use in this section,

Listing 5.1 complete HTML code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!-- jQuery.html  -->

<!DOCTYPE html>
<html>
<head>
    <title>jQuery</title>

    <!-- CSS -->
    <link href="asset/css/bootstrap.min.css" rel="stylesheet">
    <!-- Add Custom styles below -->

</head>
<body>

    <div class="jumbotron">
        <div class="col-md-offset-4 container">
            <h1><b>jQuery</b></h1>
        </div>
    </div>

    <span class="label label-lg label-default" id="l_default">Default</span>
    <span class="label label-primary" id="l_primary">Primary</span>
    <span class="label label-success" id="l_success">Success</span>
    <span class="label label-info" id="l_info">Info</span>
    <span class="label label-warning" id="l_warning">Warning</span>
    <span class="label label-danger" id="l_danger">Danger</span>

    <br><br>
    <span class="btn btn-sm btn-warning" id="b_warning">Toggle Warning Label</span>

    <br><br>
    <!-- label_id is custom attribute whouse values are set according to id of above labels-->
    <span class="btn btn-sm btn-default label-btn" label_id='l_default'>Toggle Default Label</span>
    <span class="btn btn-sm btn-primary label-btn" label_id='l_primary'>Toggle Primary Label</span>
    <span class="btn btn-sm btn-success label-btn" label_id='l_success'>Toggle Success Label</span>
    <span class="btn btn-sm btn-info label-btn" label_id='l_info'>Toggle Info Label</span>
    <span class="btn btn-sm btn-warning label-btn" label_id='l_warning'>Toggle Warning Label</span>
    <span class="btn btn-sm btn-danger label-btn" label_id='l_danger'>Toggle Danger Label</span>


    <!-- Javascript -->
    <!-- put jQuery.js before bootstrap.min.js; and then add custom jquery-->
    <script src="asset/js/jquery-3.3.1.min.js"></script>
    <script src="asset/js/bootstrap.min.js"></script>
    <script src="asset/js/my_jquery.js"></script>

</body>
</html>

5.2.3.1. Toggle label on mouse click

In this section, the ‘mouse click’ on the button ‘Toggle Warning Label (Line 29)’ is read; and then the label ‘warning’ is toggled.

  • The method ‘on’ waits for user’s input ‘click (i.e. mouse click)’.
  • On mouse-click next query i.e. ‘toggle’ is executed which hides/unhide the ‘warning label’ as shown in Fig. 5.5 - Fig. 5.6.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// asset/js/my_jquery.js

// 'hide label' and 'change content'
$(function() {
        $("#l_default").hide(1000); // hide id = 'l_default' using # operator after 300 ms
        $(".label-danger").html("Shark is dangerous");  // change content using 'html'
});


// toggle 'warning label' based on click on the button 'Toggle Warning Label'
$(function() {
    $('#b_warning').on('click', function(){
        $('#l_warning').toggle();
    });
});
../_images/jquery5.png

Fig. 5.5 Hide label ‘warning’

../_images/jquery6.png

Fig. 5.6 Show label ‘warning’

5.2.3.2. Toggle label based on the buttons

In previous section, we wrote the code which can toggle only one label. In this section, we will toggle multiple labels by writing one-generalized-jQuery as shown in Fig. 5.7.

../_images/jquery7.png

Fig. 5.7 Toggle labels based on button-clicked

  • Lines 21-26 and 31-38 of Listing 5.1 are used for this section,
  • Custom attributes “label_id=…” are added in each button which has the value which corresponds to one of the ‘label’s id’. e.g. ‘label_id’ for Line 33 (i.e. l_default) is same as ‘id’ at Line 21.
  • Next, in the below jQuery, we saved the ‘label_id’ in a variable (see Line 21) and then the variable is used to toggle the labels.
Listing 5.2 Toggle the label based on the button-clicked
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// asset/js/my_jquery.js

// 'hide label' and 'change content'
$(function() {
        $("#l_default").hide(1000); // hide id = 'l_default' using # operator after 300 ms
        $(".label-danger").html("Shark is dangerous");  // change content using 'html'
});


// toggle 'warning label' based on click on the button 'Toggle Warning Label'
$(function() {
    $('#b_warning').on('click', function(){
        $('#l_warning').toggle();
    });
});


// toggle panels according to the clicked-buttons
$(function(){
    $('.label-btn').on('click', function(){ // select class 'label-btn'
        var labelId = $(this).attr('label_id'); // store the attribute value of 'label_id'
        $('#' + labelId).toggle(); // toggle the label with id  stored in 'label_id'
    });
});

5.3. Selectors

In this section, we will use following HTML to understand the various combination of the selectors which are summarized in Table 5.1,

<!DOCTYPE html>
<html>
<head>
    <title>jQuery Selectors</title>
</head>
<body>
    <p>jQuery Selectors</p>

    <p class="foo"> Paragraph with class.</p>
    <p><span>Paragraph with span.</span></p>

    <p id="bar">Paragraph with ID. <span class="foo">Span with class and inside the paragraph-with-id.</span></p>

    <div>
        <p my-id="my_para">Paragraph (with custom id) inside the div</p>
        <p my-id="my_para2"><span>Span inside the paragraph (with custom id) inside the div</span></p>
    </div>


    <!-- Javascript -->
    <script src="asset/js/jquery-3.3.1.min.js"></script>

</body>
</html>

Note

  • Press ‘ctrl+shift+k’ (or go to Tools->Web Developer->Web Console) to open the web-console in Firefox and click on ‘console’ and type the ‘jQuery’ commands there.
  • Press ‘ctrl+shift+J’ (or go to Tools->Javascript Console) in ‘Chrome’ and type the jQuery commands there.
  • In this tutorial, the output of the ‘Firefox’ are shown.

5.3.1. Select elements

5.3.1.1. Select HTML elements

HTML elements, e.g. div, p, span and table etc., can be selected by writing them with the quotation mark as shown in below codes.

  • Here, ‘$(‘p’) is the command, whereas the lines below it are the outputs.
  • The outputs show the ‘selected elements’; and the total number of selected elements i.e. ‘length: 6’.
  • If we put the cursor to one of the outputs, then it will highlight the corresponding elements in the html as shown in Fig. 5.8.
$('p')
{…}
0: <p>
1: <p class="foo">
2: <p>
3: <p id="bar">
4: <p my-id="my_para">
5: <p my-id="my_para2">
length: 6
../_images/jquery8.png

Fig. 5.8 Output of $(‘p’); (see red-squares)

  • Similarly, we can select ‘div’ elements
$('div')
{…}
0: <div>
length: 1

5.3.1.2. Select class

Class can be selected using ‘.’ operator. In below code, class ‘foo’ is selected.

$(".foo")
{…}
0: <p class="foo">
1: <span class="foo">
length: 2

5.3.1.3. Select ID

ID can be selected using ‘#’ operator. In the below code, id ‘bar’ is selected.

$('#bar')
[…]
0: <p id="bar">
length: 1

5.3.1.4. Combining selectors

We can select a element with specific class name using ‘.’ operator as shown in below code. Here element ‘span’ with class ‘foo’ is selected,

$("span.foo")
{…}
0: <span class="foo">
length: 1

5.3.1.5. Multiple selectors

Use ‘,’ to select different types of elements. In the below code, “paragraph with id ‘bar’” and “elements with class ‘foo’” are selected ,

$('p#bar, .foo')
{…}
0: <p class="foo">
1: <p id="bar">
2: <span class="foo">
length: 3

5.3.1.6. Select descendant element

Select ‘span’ inside the ‘p’ (use space between ‘span’ and ‘p’),

$('p span')
{…}
0: <span>
1: <span class="foo">
2: <span>
length: 3

5.3.1.7. Select child element

The ‘>’ is used to select the child of an element.

$('div>span')
{…}
length: 0

Note

There is one element inside ‘div’ but it’s path is ‘div->p->span’ therefore ‘span’ is a child of ‘p’ (not of ‘div’). But tgis ‘span’ is the descendant of ‘div’ therefore can be accessed using space,

$('div span')
{…}
0: <span>
length: 1

5.3.1.8. Attribute selector

Custom attributes can be selected as below,

$('[my-id = my_para]')
{…}
0: <p my-id="my_para">
length: 1

$('p[my-id != my_para]')  // select p with 'my-id != my_para'
{…}
0: <p>
1: <p class="foo">
2: <p>
3: <p id="bar">
4: <p my-id="my_para2">
length: 5

$('p[class = foo]')
{…}
0: <p class="foo">
length: 1

5.3.2. Filters

Various filter options (e.g. filter, first, last and has etc.) can be used after ‘:’ as shown below,

$('p:first')  // select first element
{…}
0: p


$('p:last')  // last element
{…}
0: <p my-id="my_para2">
length: 1

$('p:not(.foo)')  // 'p' which does not have class 'foo'
{…}
0: <p>
1: <p>
2: <p id="bar">
3: <p my-id="my_para">
4: <p my-id="my_para2">
length: 5

$('p:has(span)')  // 'p' which has 'span' inside it
{…}
0: <p>
1: <p id="bar">
2: <p my-id="my_para2">
length: 3

$('p:hidden') // hidden 'p'
{…}
length: 0

$('p:visible') // visible 'p'
{…}
0: <p>
1: <p class="foo">
2: <p>
3: <p id="bar">
4: <p my-id="my_para">
5: <p my-id="my_para2">
length: 6

$('p:contains(with class)') // paragraph which contains class inside it
{…}
0: <p class="foo">
1: <p id="bar">
length: 2

$('p').filter(".foo") // same as p.foo
{…}
0: <p class="foo">
length: 1

$('p').not(".foo")  // p with not class foo
{…}
0: <p>
1: <p>
2: <p id="bar">
3: <p my-id="my_para">
4: <p my-id="my_para2">
length: 5

$('p').last()  // last element of 'p'
{…}
0: <p my-id="my_para2">
length: 1

$('p').has('span')  // p with span
{…}
0: <p>
1: <p id="bar">
2: <p my-id="my_para2">
length: 3

$('p').is('.foo')  // does 'p' contain 'foo'
true

$('p').children()  // children of 'p'
{…}
0: <span>
1: <span class="foo">
2: <span>
length: 3

$('p').children(".foo") // child of 'p' with class 'foo'
{…}
0: <span class="foo">
length: 1
Table 5.1 Selectors
Command Description example
$(‘elementName’) select the tags (p, body, table) $(‘p’), $(‘body’)
$(‘.className’) select element with ‘className’ $(“.foo”)
$(‘elementName.className’) element with className $(“span.foo”)
$(selector1, selector2) select selector1 and selector2 $(‘p#bar, .foo’)
$(selector1 selector2) select selector2 inside selector1 $(‘p span’)
$(selector1>selector2) select selector2 which is child of selector1 $(‘div>span’)
$(attributName = someName) select attribute with someName $(‘[my-id = my_para]’)
$p(attributName = someName) select ‘p’ with attribute with someName $(‘p[my-id = my_para]’)
See Section 5.3.2 for filters

5.4. Operations

In Listing 5.2 we saw some operations e.g. ‘hide()’ and ‘toggle()’. Table 5.2 shows some more such operations.

Table 5.2 Operations
Operations      
hide() hide(speed) fadeIn(speed) fadeOut(speed)
show() show(speed) slideDown(speed) slideToggle(speed)
slideUp(speed) toggle() toggle(speed) toggle(switch)

5.5. Event handling

In Listing 5.2 we saw one example of event handling, where certain operations are performed on the event ‘mouse click’. Table 5.2 shows a list of some more events.

Table 5.3 Event handle
Events      
click keydown keypress keyup
mousedown mouseover