Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
188 views

Bootstrap and J Query

This document provides an overview of developing responsive websites using Bootstrap and jQuery frameworks. It discusses the basics of Bootstrap including its benefits, setup, and file structure. It also covers an introduction to jQuery and creating responsive layouts and webpages using Bootstrap and jQuery.

Uploaded by

martin duy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
188 views

Bootstrap and J Query

This document provides an overview of developing responsive websites using Bootstrap and jQuery frameworks. It discusses the basics of Bootstrap including its benefits, setup, and file structure. It also covers an introduction to jQuery and creating responsive layouts and webpages using Bootstrap and jQuery.

Uploaded by

martin duy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 130

& Writing CSS HTM L

Code ^ jQ uer/
<>html</> Q J B o o tstra p
m

Developing Responsive Websites


with Bootstrap and jQuery
1. Basics of Bootstrap
2. Understanding Programming in Bootstrap
3. Basics of jQuery
4. Functions, Widgets, Plugins in jQuery
5. Creating Bootstrap Responsive Layout
6. Creating Responsive Webpages Using Bootstrap and jQuery
Developing Responsive W ebsites with Bootstrap and jQuery

SESSION 1- Basics of Bootstrap


Session Objectives:
This session introduces the Bootstrap framework along with its basic concepts, it also describes the
process of setting up the framework, the file structure of its precompiled version, and the default
source code template. The session also briefly explains the use of different Bootstrap templates that
are modifiable by changing their Cascading Style Sheet (CSS) and JavaScript (JS) code.

At the end of this session, you will be able to:

> Describe Bootstrap


--- *— explain the basic concepts of Bootstrap----------------------------------------------
> Describe the process of setting up Bootstrap
> Outline the file structure and the default source code in Bootstrap
> Use Bootstrap with CSS and JS
> Describe the significance of Bootstrap templates

1.1 Introduction to Bootstrap


Bootstrap is an intuitive and open-source framework that makes front-end development of Web
applications simpler as well as quicker. So, it is also known as the front-end framework. Primarily,
Bootstrap aims to make responsive Web applications as well as Websites. In fact, it is presently the
most popular CSS framework for building responsive Websites.

The framework encompasses JavaScript, CSS, and HTML for developing custom components while
designing Webpages. Developed by the Twitter team, Bootstrap also supports HTML5 and CSS3. It
includes a free set of tools for creating Web applications and Websites.

Bootstrap consists of CSS and HTML based templates for designing a variety of components such as
forms, layout, navigation, and even JavaScript extensions. It also includes a set of defined CSS classes
that Web developers can use directly. The framework also uses JavaScript/jQuery framework for
creating effects, styles, and actions for its components. In short, bootstrap is a CSS framework, a
templating system, and a JavaScript toolkit.

Web developers use CSS for applying styles to the elements of a Webpage by creating as well as
assigning classes to these elements. However, Bootstrap automates this styling task by facilitating a
developer to include the Bootstrap files and state the predefined class names for the elements. This
also eliminates the need of writing custom CSS classes for styling the elements. Thus, Bootstrap
saves a lot of time while designing Webpages.

1.2 Benefits of Bootstrap


There are many reasons why Web designers and developers prefer Bootstrap. Following are these
reasons:

• Easy and Flexible Enough to Get Started: Using Bootstrap is extremely easy, adaptable, and
quick. Web developers can use it along with CSS, dynamic stylesheet language (Less), or
Syntactically Awesome Style Sheets (Sass). Both Less and Sass are style sheet languages. While
Less is compiled into CSS, Sass is interpreted into CSS. Further, there are different ways of
adding Bootstrap to a Web project, which shows its flexibility.

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

• 100% Responsive Designs: A Website should be responsive to each Internet-enabled device. For
example, it should adapt to the screen of a smartphone or tablet without compromising its
smooth appearance and pleasant navigation. This is exactly what Bootstrap ensures through its
fluid grid layout that readjusts itself dynamically to the screen resolution. The ready-made
Bootstrap classes enable identifying the number of spots in the grid that each column should
use. This helps in identifying points at which the columns should load horizontally rather than
vertically for displaying the requested page accurately on the targeted smartphone. Bootstrap 3
comes with the mobile-first approach by offering mobile-first styles.
• Great Grid System: Bootstrap implements a 12-column, responsive grid that supports offset and
nested elements.
• Better Development Speed: Rather than coding from scratch, Bootstrap allows using ready­
made blocks of code for designing a Webpage. Merging these blocks with the code for cross­
browser compatibility and CSS-Less functionality can save several hours of coding. Even for
backend developers who need to do some user interface modifications, Bootstrap is efficient.
This is because there is no need for them to know HTML and CSS well for using Bootstrap.
• Browser Compatibility: Bootstrap resolves several cross-browser compatibility issues. This
means a Web application made using Bootstrap runs smoothly in Chrome, Safari, Internet
Explorer, and Firefox.
• Customization: It is possible to use Bootstrap as per the distinct design requirements. Web
developers can select the required aspects by ticking off those that are not required. These
aspects are available on the Bootstrap customize page, which includes common CSS,
components, JavaScript components, and utilities. This is the custom version of Bootstrap, which
is ready for download.
• Consistency: Initially, a few Twitter team members expanded the framework for improving the
consistency across the internal tools. However, later, Mark Otto who is the Co-founder released
the first open-source Bootstrap version after comprehending the framework's potential. He also
depicted how the framework expanded through the single core concept of combining designers
and developers.
• Big Support: There is a big supportive community for Bootstrap due to which Web developers
can obtain any kind of help at any time. Moreover, the makers frequently update the
framework. Currently, it is hosted and updated on GitHub with over 500 contributors. The open-
source framework is available at no cost.
• Bundled JavaScript Components: Bootstrap comes with a set of JavaScript components for using
different functionalities for user interface components. A few examples of these functionalities
include tooltips, alerts, and modal windows. This means that there is no need to write scripts for
these functionalities.
• Simple Integration: Web developers can integrate Bootstrap with other frameworks and
platforms, even for the existing Websites. Some Bootstrap elements are usable with an existing
CSS.
• Extensive Pre-styled Components: Bootstrap comes with a variety of pre-styled components for
drop-downs, alerts, and navbars.

1.3 Setting Up Bootstrap


It is easy to download, install, and set up Bootstrap for getting started. There are two ways to start
using the framework on a Website, which are:

• Downloading from getbootstrap.com


• Including it from a Content Delivery Network (CDN)

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

1.3.1 Downloading from GetBootstrap.com

The framework's latest version, 3.3.7, is available at getbootstrap.com. Figure 1.1 shows its home
page.

B
Bootstrap is the most popular HTML, C S S , and J S framework for
developing responsive, mobile first projects on the web.

Download Bootstrap

Figure 1.1: Home Page ofGetbootstrap.com

Clicking the Download Bootstrap button redirects to the Download page, as shown in figure 1.2.

Download
Bootstrap (currently v3.3.7) has a few easy ways to quickly get started, each one appealing
to a different skill level and use case. Read through to see what suits your particular needs.

Bootstrap Source code Sass


Compiled and minified CSS. JavaScript, Source Less. JavaScript, and font files, Bootstrap ported from Less to Sass for
and fonts. No docs or original source files along with our docs Requires a Less easy inclusion in Rails. Compass, or
are included. compiler and some setup. Sass-only projects

Download Bootstrap Download source Download Sass

Figure 1.2: Download Page

The Download page displays the following options, which are the different ways of downloading the
framework:

• Download Bootstrap: Enables downloading the precompiled, mini versions of Bootstrap CSS,
fonts, and JavaScript. It does not provide original files of source code or documentation. The
precompiled one facilitates drag-n-drop usage in any project. It includes the compiled CSS and JS
files, minified compiled versions of each, optional Bootstrap theme, and Glyphicon fonts.
• Download Source: Enables obtaining the latest documentation and JavaScript source code from
GitHub. This is the source code version that encompasses the precompiled CSS and JS files, font
files, and Bootstrap Less assets. It is a more comprehensive version with a higher learning core
than the precompiled version.
• Download Sass: Enables obtaining the latest Bootstrap version imported to Sass from LESS for
Sass-only projects.
1.3.2 Including from a CDN

Alternatively, Web developers can include Bootstrap from a CDN. This is the option for those
developers who do not intend to host the framework by themselves.

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

A CDN, as a system of distributed servers, delivers Webpages to a user as per the geographic
location of the server and the user. The closer the server, the faster is the content sent to the user.
CDN aims at accelerating the delivery of Web content for sites with global reach and high traffic. So,
using Bootstrap CDN provides the benefit of faster loading time.

1.4 File Structure and Source Code in Bootstrap


After downloading the precompiled Bootstrap version, a ZIP file contains all the directories and files.
This arrangement logically clusters the common resources and offers the minified as well as the
compiled variations. After extracting the ZIP file, its contents are visible in the form of structured css,
js, and fonts directories.
Figure 1.3 shows the file structure of precompiled Bootstrap version,

bootstrap/

+ - - css/

] + -- bootstrap.css

| + -- bootstrap.css.map

j + -- bootstrap.min.css

j + . . bootstrap.min.css.map

j + -- bootstrap-theme.css

j + -- bootstrap-theme.css.map

| + -- bootstrap-theme.min.css

i +-- bootstrap-theme.min.css.map

+ - - js/

| + - - bootstrap.js

| +-- bootstrap.min.js

+-- fonts/

+ - - glyphicons-halflings-regular.eot

+ - - glyphicons-halflings-regular.svg

+ - - glyphicons-halflings-regular.ttf

+ - - g lyphico ns-h aIfIings-r eg ula r.woff

+- - glyphicons-halflings-regular.woff2

Figure 1.3: Precompiled Bootstrap File Structure

Figure 1.3 shows the most basic form of the framework, which has compiled files.

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

These files enable a Web developer to use the desired components and plugins quickly by dragging
and dropping them onto the required positions on a Webpage of any Web project. It reveals
compiled CSS and JS files (bootstrap.*) along with minified and compiled CSS and JS
(bootstrap.min.*). CSS source maps in the form bootstrap.*.map are available for a few browser
developer tools.

The structure also includes fonts from Glyphicons and the optional Bootstrap theme. It is worth
knowing that JavaScript plugins require the inclusion of jQuery.

1.4.1 Inside the Bootstrap File Structure


In Bootstrap, HTML, CSS, JS, and other components are grouped into categories, which are
noticeable atop its documentation. Following are the categories:

• Scaffolding: Offers a basic grid structure, simple layouts,background, and link styles.
• CSS: Offers global CSS settings, advanced grid system, andstyles for basicHTML elements.
• Components: Offer styles for a variety of reusablecomponents suchasalerts, tabs, page
headers, and alerts.
• JavaScript Plugins: Offers custom and interactive jQuery plugins for components such as
modals, tooltips, and popovers.
The categories of Components and JavaScript plugins together offer the following user interface
elements:

• Button groups and button drop-downs


• Page headers and hero unit
• Navbar
• Navigational tabs, pills, and lists
• Labels
• Thumbnails
• Badges
• Drop-downs
• Tooltips
• Alerts
• Modals
• Progress bars

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

1.4.2 Default Bootstrap Template

Figure 1.4 shows the basic HTML template for Bootstrap, which includes everything that the file
structure specifies.
1 CDOCTYPE html>
2 3 <html lang“”en">
3 <head>
4 <meta charset="utf-8 ">
5 crr.eta http-equiv="X-UA-Co!npatible" content**" I£=edge”>
6 <rrseta narce="viewport" content="width=device-width, initial-scale=l">
7 <!— The above 3 meta tags “must* come first in the head;— >
8 <title>Bootstrap Basic Template</title>
9
10 <!— Bootstrap — >
11 <lin!c href=”css/bootstrap.min.css" rei= ’stylesheet">
12
13 <!— HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries — >
14 <!— WARNING: Respond.Js doesn't work if you view the page via file:// — >
15 <! — [if It IE 9]>
16 <scnpt arc— 'https://oss.maxcdn.com/htmlSshiv/3 .7 .3/html5shiv.mm.is,’></3 cript>
17 <script src°"https://oss .maxcdn.com/respond/l ■4 ■2/respond . m m ■13"X/3cript>
IS <![endif]— >
19 </head>
20 <body>
21 <hl>Hello, world!</hl>
22
23 <!— jQuery (necessary for Bootstrap’s JavaScript plugins) — >
24 <script src— ’https://alax.qooqleapis.com/alax/libs/icroery/1.12.4/icroery.min.is"X/script>
25 <!— Include all compiled plugins (below), or include individual files as needed — >
26 <script src=" js/bootstrap.min. js"x/script>
27 </body>
28 </html>

Figure 1.4: Basic Bootstrap Template

In figure 1.4, the template includes the bootstrap.min.css, jquery.min.js, and bootstrap.min.js files.
This converts the normal HTML file into a Bootstrapped one. It is essential to include the jQuery
library prior to the Bootstrap library. The template also includes html5shiv.min.js and
respond.min.js files for displaying HTML5 elements in Internet Explorer (IE) 8.

This HTML page is responsive, as it has the viewport meta tag in the <head> element. This tag
takes care of rendering and touch zooming on the Internet-enabled mobile gadgets. The width
property ensures that the page fits into the screen of the target device. By setting its value as
device-width, the page is rendered properly across various devices such as tablets, desktops,
and smartphones. The initial-scale = 1.0 property renders the page at a 1:1 scale at the
time of loading.

Figure 1.5 shows the output of the default Bootstrap template.

c © file:///C:/Users/dbollojx/Desktop/p.html

Hello, w orld!

Figure 1.5: Basic Bootstrap Template Output


MaxCDN also offers the desired JS and CSS files for working with Bootstrap. Code Snippet 1 shows
the different links to be added under the head tag for using Bootstrap through MaxCDN.

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

Code Snippet 1:
<!-- Compiled and minified CSS — >
clink rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.
min.css">

<!— Optional theme -->


clink rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-
theme.min.css">

<!-- Compiled and minified jQuery — >


<script
src=" https ://aj ax.googleapis .com/aj ax/libs/j query/3 .2 .0/j query.min j
s"></script>

<!-- Compiled and minified JavaScript -->


<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/J s/bootstrap.mi
n.js" ></scr ipt>
In the snippet the links are referring to the MaxCDN, a public distributed network hosting the
desired CSS and JS files. The first link is of the compiled and minified version of CSS. The second one
is optional and links to a Bootstrap theme. The third link is of the compiled and minified JS.

Code Snippet 2 shows how to add the required links under the head tag.

Code Snippet 2:
<!DOCTYPE html>
chtml lang="en">
<head>
<title>Bootstrap through CDN</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-
scale=1">

clink rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.
min.css">

<script
src=" https ://ajax. googleapis .com/aj ax/libs/j query/3 .2 .0/j query.min j
s" ></script>

<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/j s/bootstrap.mi
n.js" ></scr ipt>

</head>
In the snippet, the order of linking is important. The reference to minified version of jQuery
(jquery.min.js) will always come before the minimized version of JS (bootstrap.min.js).

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

1.5 Bootstrap with CSS and JavaScript


Bootstrap is a robust front-end framework to quickly develop a functional Website. To give a unique
and interactive look and feel to the site, it is essential to write JavaScript and CSS.

1.5.1 Using CSS

Bootstrap uses a few HTML elements and CSS properties that need the HTML5 doctype. It is
essential to include it at the beginning of any Web project. Code Snippet 3 shows how to include the
doctype.
Code Snippet 3:
<!DOCTYPE html>
<html lang="en">

</html>
While Bootstrap 2 came with the discretionary mobile-friendly styles, Bootstrap 3 is mobile-friendly
right from scratch. Rather than including the mobile styles, the version 3 framework have them right
at its core. Undeniably, Bootstrap is mobile first, which means the mobile-friendly styles are present
throughout the library rather than in isolated files.
For ensuring perfect rendering and zooming on touch, a Web developer should include the
viewport: meta tag in <head>, as shown in figure 1.4. It is possible to disable zooming on any
mobile device by including user-scalable=no to this tag. This allows users to scroll and disables
zooming, which gives a feel of a native application. However, experts do not recommend disabling
zooming for each site.

Bootstrap allows specifying the standard global display, link styles, and typography. These styles are
present in scaffolding.less.

In Bootstrap, all site contents and a grid system exist within a container, which is a containing
element. There are two containers namely, fixed and fluid. They are non-nestable, which means it is
not possible to include a container within another container.

Fixed Width Responsive Container


The fixed container has a preset width in pixels with respect to the whole page's layout (viewport). It
remains the same across different screens and browsers. This means that the container's width does
not change with a change in the resolution.

For example, in a viewport with a width of 960 pixels, each column has a preset width that does not
change. Now, if the user shrinks the browser to 959 pixels, the container snaps to a new layout as
per a media query having a maximum width of 768 px. The columns remain unchanged when the
width of the browser is between 768 and 960 pixels.

Such a layout is easier to use and personalize in terms of design. It also eliminates the need to
specify the minimum and maximum widths, which some browsers do not support.

To create a fixed container, a Web developer needs to use the . container class in <div>.

Figure 1.6 shows how to create fixed with responsive container.

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

<!DOCTYPE htal>
2 E3<html lang-"en">
3<head>
* <title>Bootstrap Container</title>
<mota charset-"utf-8 ">
<aeta name-"viewport" content-"width-device-width, initial-scale-l">
? Clink rel-"stylesheet"
href-"https://maxcdn.bootstrapcdn.corn/bootstrap/3 .3. 7/css/bootstrap .min.css">
9 <script src-"https://a^ax.qoo<;iloai>is.com/a1ax/libs/1<|\iorv/3.1 .l/1quory .min .1s"X/script>
10 <script sre-"https ://maxcdn .bootstrapcdn.com/bootstrap/3.3.7/} s/boots trap.min .}s"X/script>
^</head>
12 ED<body>

14 [}<div class»"containor">
1$ <hi>Bootstrap Container Page</hl>
1« <p>This part is inside a .container class.</p>

18 </div>
19 </body>
</html>

Figure 1.6: Fixed With Responsive Container Code

In figure 1.6, the <div> tag contains the container class to indicate that its content will come in
a fixed-width container.

Figure 1.7 shows the output.

C © file:///C:/Users/dboHojx/Desktop/p.html

Bootstrap Container Page


This part is inside a container class.

Figure 1.7: Fixed Responsive Container

In figure 1.7, it is noticeable that the content inside the fixed width container is aligned in the
middle.
Fluid Width Responsive Container

This container spans across the width of the whole viewport. In simple words, it stretches to cover
the available width for fitting to the window regardless of how wide it gets. The viewport's width
changes even if there is a smallest change in the size of the browser or screen. It continuously resizes
as the browser's width changes such that there is no additional empty space on the sides, unlike a
fixed width container.

The width is usually a percentage of the window instead of fixed number of pixels. For example, with
100% layout's width, each column adjusts its width as per the computed relative size (for instance,
25%) when the browser window resizes. Thus, fluid layouts stretch to contract as per the screen's
width.

To create a fluid container, a Web developer should use the . container-fluid class in <div>.

Figure 1.8 shows how to create fluid width responsive container.

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

This eliminates the need to write JavaScript. This is the first-class API of Bootstrap and is considered
initially for using a JavaScript plugin.

In a few scenarios, it might be necessary to turn off this functionality. Code Snippet 4 shows how to
disable the data attribute API.

Code Snippet 4:
$ ( ' b o d y ' ) . o f f ( ' . d a t a - a p i ')
Note: Through data attributes, the developer
The example unbinds all events on the body can use only a single plugin per element.
associated with the namespace, d a t a - a p i . On
the other hand, to turn the functionality off for a
specific plugin, a Web developer should include the plugin's name before the d a t a - a p i
namespace. Code Snippet 5 shows how to include the alert plugin's name before the namespace.
Code Snippet 5:
$(’body’).off('.alert.data-api')
Now, let's see how to use data attributes for displaying a modal. A modal is a restructured yet
flexible dialog box with least required functionality and wise defaults. It is a special window that may
contain a header, body, tooltip, video, and/or a popover for boosting the user experience.

Figure 1.10 shows the code for displaying a modal in a Webpage by using data attributes.
1 0 <body>
2
3 T<div class“’,container”>
4 <h2>Demo Modal Bxample</h2>
5 < i— Trigger the modal with a button — >
6 <button type“"button" class“"btn btn-info btn-lg" data-toggle“”modal"
7 data-target*"#myModal">Open Modal</button>
s <!— Modal — >
9 ] <div class="modal fade" id="myModal" role=”dialog">
10 E) <div clas3“''iaodal-dialogH>

12 <!— Modal content— >


13 0 <div class”"modal-content">
14 [;■] <div clas3“ "modal-header">
15 <button type=”button" cla3s=''close” data-di3ita.33="modal">4tiffies;</button>
16 <h4 class="modal-title">Modal Header</h4>
17 </dlv>
18 El <div class**"modal-body">
19 <p>This is my Demo Modal.</p>
20 </div>
21 15 <div clas3="modal-footer”>
22 <button type_"button" clas3 “"btn btn-default" data-di3 mi3 3 -"modal">Close</button>
23 </dlv>
24 </div>
25
26 </div>
27 </div>
28
29 -</dlv>
30
31 </b cdy>_________________________________________________________________________________

Figure 1.10: Code for Displaying Modal Using Data Attributes

In figure 1.10, the following steps take place:

• In step 6, the Open Modal button is set on the Webpage. Clicking it displays a modal
window. The b tn b t n - i n f o b t n - l g CSS class sets the large style for this button.

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

< ! DOCTYFf
l a n 7 » Mon**>
X h M d >
4 <title>Bootstrap C o n t a i n o r < / t i t le>
C n o t a c h 4 t i * t * Hu t £ - 8 * >
« < i M t a n a n o - " v i e w p o r t " c o n t o n t » Mw i d t h - < i o v i o o - w i d t h , i n i t i a l - * c a l o - l **>
clink r«l-"»tylo*hoetH
h r ® f - " h t t p s :/ / m a x c d n .b o o t s t r a p c d n .c o a / b o o t s t r a p / 3 . 3 . 7 / c s s / b o o t s t r a p . B i i n .c s s * >
< s c r i p t sre*** h t t p s : / / a l a x . a o o q l o . & p l s . c o o / a ) a x / l l b s / \ < n i a r Y / 3 .1 . 1 / Jffuory-nin. ) « " > < / s c r i p t >

</he*d>
,J<body>

<di v cias3-"contaL«ior-f l uidM>


<hi>My Bootstrap Pago</hl>
< p > T h i s p a r t 1st i n s i d o a .c o n t a i n o r - f l u i d class.</p>

</div>
</body>
</html>

Figure 1.8: Fluid Responsive Container Code

In figure 1.8, the <div> tag contains the container-fluid class to indicate that its content will
come in a fluid container.

Figure 1.9 shows the output.

C © filey//C:/Users/dbollOjx/Desk?op/p.html

My Bootstrap Page
This part ts ms«e a contamer-ftuM class

Figure 1.9: Fluid Responsive Container

When the user resizes the browsers window, the content within the container adjusts itself while
the width remains stretched across the viewport. A fluid design adjusts to the user's screen settings.
It also eliminates the need to include a horizontal scroll bar in case of a smaller resolution of the
screen, unlike a fixed width container.

It is unwise to modify the bootstrap.css file, as such a modification would invite complications while
upgrading Bootstrap. Thus, the best way to edit bootstrap CSS is to make a custom css file and
overwrite it whenever there is a different requirement. For example, if the default top bar is in black
color but the requirement is gray color, just create a specific selector for this bar and apply the color
rule. For instance, it can be ctable class=”zig-zag mycustomclass" >. Declaring the
custom css file just after bootstrap.css overwrites that part of code that needs a change.

1.5.2 Using JavaScript


Web developers can include JavaScript plugins in one of the following ways:

• Individually, using the *.js files.


• All at once, using the bootstrap.js or bootstrap.min.js file, as each of them have all
plugins.
There are two ways of using JavaScript plugins namely, through data attributes and via JavaScript.

Data Attributes

Web developers can utilize all Bootstrap plugins via the markup Application Programming Interface
(API).

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

• The data-toggle=" modal ” data attribute is a custom HTML5 attribute that conveys
Bootstrap what to do, which is to display a modal. The data-target data attribute
conveys Bootstrap which element to open. In this case, it is a modal, as its value points to
an element having an id attribute with value as myModal.
• In step 9, the modal fade CSS class sets the modal layout.
• In step 10, the modal-dialog class defines the dialog layout of the modal.
• In step 13, the class modal-content defines what the modal will contain.
• In step 14, the modal-header class defines the style of the modal's header.
• In step 15, the class= ” close ” property defines the style of the close button in the
modal window. The data-dismiss data attribute is a custom HTML5 attribute, which is
specified for closing the modal window.
• In step 16, the modal-title class sets the title of the modal.
• In step 18, the modal-body Bootstrap CSS class sets the style for the modal'sbody.
• Similarly in step 21, the modal-footer Bootstrap CSS class sets the style for the
modal's footer.
• In step 22, the CSS classes namely, btn and btn-default, specify the style for button
in the modal's footer.
Figure 1.11 shows the output.

Demo Modal E xam f'


Modal Header

This is my Demo Modal

Figure 1.11: Modal with Header, Body, and Footer

Programmatic API

Another way to use Bootstrap plugins is via JavaScript API. Any public API is a single, chainable
method that returns a collection. A method should receive an optional object called options, which
is a string targeting a specific method. It can even receive nothing, which triggers a plugin with a
default behavior. Code Snippet 6 illustrates both the statements.

Code Snippet 6:
$("#newModal").modal(’show’) // show is the string targeting the
show method to display the modal dialog immediately.

$("#newModal").modal() // This statement triggers Default


initialization.
The only difference between modal ( 1show ' ) and modal () is that the former manually opens a
modal. It also returns to the invoker prior to raising the relevant event, shown .bs .modal for
showing the modal.

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

Figure 1.12 shows how to display a modal by using modal ('show').


< I DOCTYPE h t * l >
0< h ta»l l a n q - "e n ">
£|<head>
< a o c a c h a r s e t » Mu t f - 8 " >
h t t p - e q u i v - " Z - U A - C o m p a t i b l e '* contont*" I B - « d g o " >
n<un<j»Bvlfl«port" e o n c « n t > Hw i d C h ad a v i c « - w i d t h < l n i t i a l - s c a l e — 1">
< t i t l e > E x a .n p l o of bootstrap 3 M o d a ls < /t it le >
<1 i n k r e l - " » t y l o * h o o t " h r e f « ' h t t p » ; //r a a x c d i v .b p p t g t x f l p o d n . o o n /b o Q t a t r f l p /3 ^ 3 a .? /c « j i /b < K > t a .t g a p .n i n . c a a "
i n t e g r i t y - ••» h a 3 8 4 - B V Y ii S IF o K ld O ^ J R A 3 c y o u H A H R c |3 2 0 B \ U c w w 7 o n 3 R Y d g 4 V a 4 P m S T **/K 6 8 v b < lE jh 4 u " c r o 9 9 o r i g i n » " a n o n y n o u » H>

i n t e g r i t y - * ”* h * 3 8 4 - r K y o N l i R » V 7 T V 4 n D 0 J u t l n G A 9 l C J u C 7 u w J d u W i S V r L v R Y o o P p ^ b W Y g m y J Q l X w l / S p " c r o 9 3 o r i g i n - " A i i o n y m o u i i ‘, >


o c r i p t » r c - - b v t y a ;//aJflA,tfreuloagla j.coci/alax/iJdfra/ltfuctv/1.12..4/3guaxy.siln. i a "> < / o c r i p t >
O c rip t 9 r c - "h tti> 9: / /e m x c d n .b o o t s t r a p o d n . c o r a /b o o t s t r a p /3 , 3 . 7/ I s / b o o t a t r a p , r v l n . 1 i w in te g rity -
"sha384-Tc5IQib027<rvy)SMf M ) O M a L k f u H V x Z x V P n C J A 7 1 2 m C W N I p C 9 m < J C D 8 w C N I o P D 7 T x a " c r o s o o r i g i n - ~ a n o n y m o u s " X / » c r i p t >
O c r i p t type-"text/}ava»oriptM>
((d o c u m e n t ). r e a d y (fu s c e :a a () <
♦ (" •c y M c d a i * ).n o d a l ('s h e w * ) j
»;
</ » c r i p t >
</h«ad>
<b o d y >
|<div id-~riyModa1" c l a B 3 » Mn o d n l fa<loM>
t <div clas3-"rv>dal -dialog*' >
< d i v c l « 3 2 - "m o d a l - c o n t e n t " >
<div class-" modal -header">
<button t y p c - "b u t to n " c la »3- "c lo a o " d a t a - d i 9 » i s s - ' * m o d a l *• a r i a - h i d d e n - " t r u e " > « c i a o i / < / b u t t o n >
<h4 c l a a s - ’T w d a l -t l t l « " > C o n f l r m a t i o n < / h 4 >
</di»>
| <div cla*9-"modal-body“>
<p>Do you want to tavo change* you m ade to docum ent b e fo r e o lo s in g ? < /p >
<p c l « s a » "t o x t - w a r n i n g ” > < 3 m a l l > If you d o n 't savo, your changes w ill be l o s t . < /s » a l l > < /p >
< / div >
<dir cl»ss-"r>odal-footer”>
< b u t to n t y p « » "b u t t o n * c l a s 2 » " b t n btn- ck sfault” d a t « - d i a a i s a » "m o d a l M> C l o » « < /b u t t o n >
< b u t to n t y p e * * b u t t o n “ c l a a s » " b t n b t n - p r im a r y ” > Save c h a n g e a < /b u t t o n >
</div>
</div>
</div>
</dir>
</body>
g/httb___________________________________________________________________________________________

Figure 1.12: JavaScript Code for Displaying a Modal

In figure 1.12, the MaxCDN links for Bootstrap contain the integrity and crossorigin
attributes. Both ensure that an obtained resource was sent without unfavourable manipulation. The
integrity attribute enables a browser to check the source and prevent its loading if the source is
manipulated. This kind of security is essential, as the CDN is a public network on which any malicious
user can manipulate the files on it. The crossorigin attribute set to anonymous conveys the
browser to execute the specified CDN link without transferring the user credentials. The
anonymous keyword indicates that there is no need of exchanging the credentials through HTTP
authentication, security certificates, or cookies.

In the script tag, document.ready () indicates that the HTML page is ready for changes through
JavaScript. Through it, JavaScript loads a modal through modal.show ( ) , which is also invoked for
closing the modal when the user clicks the Close button.

Figure 1.13 shows the output.

Figure 1.13: Output of JavaScript Code for Displaying a Modal

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

Code Snippet 7 shows how to initialize the modal plugin through the default method shown in Code
Snippet 6.

Code Snippet 7:
<script>
$ (document) .ready(function() {
$ ("#myBtn").click(function(){
$ ("#newModal") .modal() ;
});
});
</script>
In this snippet, when a user clicks the button whose id is #myBtn, the modal plugin is initialized by
invoking its default method.

In short, there are two ways of activating a modal and other JavaScript plugins, which are as follows:

• Through data attributes, as shown in figure 1.10, wherein data-toggle=" modal" is set
on the button controller and data-target=" myModal" is set to toggle a particular
modal
• Through JavaScript by initializing a modal with its id or invoking the show () method.
Each Bootstrap plugin also has a raw constructor, which is invoked through its Constructor
property. Code Snippet 8 shows how to use this property.
Code Snippet 8:
$.fn.popover.Constructor
For retrieving a specific plugin instance, it is possible to do so directly from an element. Code Snippet
9 shows howto do so.

Code Snippet 9:
$('[rel=popover]').data('popover')
Events

Bootstrap offers custom events to handle most distinct actions of plugins. Usually, they are available
in the infinitive and past participle form. The infinitive form is invoked in the beginning of an event,
while the completion of the action triggers its past participle form. For example, the show event is
triggered in the beginning, while the shown event is invoked once the action is completed.

An infinitive event comes with the preventDefault functionality for stopping the action's
execution prior to its beginning. Code Snippet 10 shows how to use this functionality.

Code Snippet 10:


$(’#newModal').on('show', function (e)

if (!data) return e .preventDefault() //stops modal from display


})

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

Transitions
Web developers should include Transition.js for applying a few basic transition effects. This is not
needed if they are using the compiled bootstrap.js, as the file is already included. Transition.js is a
helper file that other plugins use to verify the CSS transition support. Developers can use the plugin
for achieving the sliding and fading effects for modals, tabs, and alerts.

Figure 1.14 illustrates how to use the JavaScript API in Bootstrap to inform a user that something
went wrong after clicking the Submit: button on a Webpage.

1 < ! DXIYPE html>


2 n<html lang*"en">
3 R<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=l">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3 .3.7/css/bootstrap.min.css">
<script 3rc="https://ajax.gooaleapis.con/ajax/libs/jquery/3.2.0/jquery.min.js"></3cript>
<script 3rc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/is/bootstrap.min■is"X/script>
10 R <script>
-- E $(dccuiaent) -ready(function () {
12 R $('^btnSubmit') .click(function () {
13 $ ('fmyAlert').show('fade');
14 -

15 H $('‘
ilinJcClose').click(function () {
16 $('#myAlert').hide('fade') ;
17 - });
13 - });
19 -</script>
20 -</head>
21 H<body>
22 R<div class="container">
23 R <button id»nbtnSubmitM clas3»"btn btn-pri!nary">
24 Submit
25 -</button>
26
27 <br /><br />
2B R<div id="myAlert" clas3="alert alert-danger collapse">
23 <a id«"linkClose" href*"#" cla3s-"close">S£i2nes;</a>
<strong>Error!</strong> There is a problem submitting your form
31 -</div>
32 -</body>
33 -</html>

Figure 1.14: JavaScript Code for Displaying an Alert Message

In figure 1.14, the JavaScript code uses the id selector, btnSubmit, to find the button. As soon as
the button is clicked, the corresponding JavaScript function is triggered to display an alert box. This
box displays an error message. When a user clicks the Close link, the alert box hides itself by fading
away.

Figure 1.15 shows the output.

Figure 1.15: Output of JavaScript Code for Displaying an Alert Message

V 1 .0 © APTECH LIMITED
Developing Responsive Websites with Bootstrap and jQuery

1.6 Templates in Bootstrap


A bootstrap template refers to a mock Website that is designed using the bootstrap framework. Its
components are JS code, CSS code, HTML pages, fonts, and different images belonging to its design.
The template is usually designed for accomplishing a purpose, which can be to have an e-commerce
site, a corporate portal, a blog, or simply a vertical landing page.

Figure 1.16 shows a Bootstrap template fora blog.

Blog Search
P a g e H eading Secondary Text Q.

Blog Post Title


by Start Bootstrap Blog Categories
Category Name Category Name
O Posted on August 28.2013 at 10.00 PM
Category Nnmo Category Name
Category Name Category Name
Category Name Category Name

by Start Bootstrap Blog Categories


Category Name Category Name
O Posted on August 28.2013 at 10.00 PM
Catogory Nnmo Category Name
Category Name Category Name
Category Name Category Name

Side Widget Well

900*300 Lorem ipsum dotor s;t a m et coosectetur


adipi&c^ig olit. Inventor®. porspctatrs adiptsci
accusamus laudantium odn aliquam repoHat
tempore quos aspematur v»ro.

Lorem psu ni do'o? M artvet. consectetur adipt&cmg etit. Dokxe. ventat<s tempora, n e c e s s ito u s mventore nisi quam
qu a repoflat u t tempore la& orvn possimus oum a c ta >d a w n corrupti cW xis ipsum of1io« rerum.

Figure 1.16: Blog Bootstrap Template

Figure 1.17 shows a Bootstrap template fora business frontpage.

Start Bootstrap About S«« «■ » Contact

1 i

1920x400

What We Do Contact Us
mtrooueeme w r t o f t t f f w e iA n m v w g c * . * mteonaa** i n ! u*e Rtyworo* your »o 9t»n D co tttr j p
v n tea/c r> t-m tna me t>uvr*M )45i ue*o*ePuce
ca oo2to
l a w n n un ootry v t « n « con*«»etur W p f K f t j M Cl >w *tfta e Mmque etgenoi r e * * * * * * sunt drMncto 0 90
Qua r*q u e ip M *>pcx* qunquam ix jm 0« « w l accuw reum ao iU*fiercfciooo<*n r«f<*o vCAjpU** «p er*ye »
P(123)«^W0
C (Mmf^furvecom
C«l to Action »

300x300 300x300 300x300

Figure 1.17: Business Frontpage Template

V1.0© APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

Figure 1.18 shows a Bootstrap template for shopping item.

start Bootstrap aekx* Sc w o Contact

Shop Name

Category2
CMtOTr)
800x300
Pro d u c t N a m # 524.9*
See more sncpefe ike these onine s*ore f e w » at B ootv.pp ■rep fcoo b/w p p com

VVanl to t n * c Ihese revw*s • o r t ^ Cheek oat tJv* D uM ing * raview tu torial over X maioffsky com’

lorem p w m M o r U amet conoecte&jr acxpojcng e it sed <x>cnnmoO to rp w n co d u n t ut uoore et Ootoec m*yna Ut


enm ad r n n n v era m q m nostoid exert 4at»n u u m co latwns ns> ut a»quip ex eacom nodoccnscquat Oun aute ru re defer m
reprehendent r voK & j Oc veil esse c«wn (Wore eu ^ nuta p a rjtu r E-rcepteur t r t occaecai cupdatat non protiefit u r t m
cupa qui o flc a deserunt moat a w n >3est laCorum

* * * * « 4 0 tU r t 1r o w

* * * * * Arerymoui
Tr*» c ’oduct was great n M o m o fquatfy i «ouid O t*r*t*y t v r anome<*

rve atreoy ordered another one'

★ ★ ★ ★ <r Anonymew*
rve *een tome Defter f a n n t c m not al v n pnc« i recommend r « *

Figure 1.18: Shop Item Template

As per the purpose, Web designers try to find and include all relevant templates. For instance, if
templates are required for an e-commerce Website, they may find a product category page, a cart
page, a contact us page, and a customer testimonial page. While there are a couple of more
templates for such a Website, it is rational to pick only those that are required.

Bootstrap templates are also available in different versions. For adapting the template to the
targeted site or purpose by easily changing its content, it is essential to have some basic knowledge
about HTML, CSS, and JS. All Bootstrap Web templates are responsive, easy to customize, and ready-
to-use. They are reusable due to which Web developers can save a lot of time in designing some of
the most common Webpages.

Quick Test 1.1

1. It is possible to disable scrolling on a Bootstrap Webpage.


a. True
b. False

2. It is easier to display a modal window without JavaScript.


a. True
b. False

V1.0 © APTECH LIMITED


Developing Responsive Websites with Bootstrap and jQuery

r
___
> Summary
V

> Bootstrap is an open-source Web framework for quickly developing front-end and responsive
applications.

> Bootstrap uses CSS, HTML, JavaScript, and jQuery design interactive Webpages.

> Customization, browser compatibility, fully responsive pages, and an assortment of built-in
components are the major benefits of Bootstrap.

> There are two ways to start using Bootstrap namely, downloading its files from getbootstrap.com
or including them from a CDN.
> Structure of the precompiled Bootstrap version includes the css, js, and fonts directories offering
components and plugins for drag-n-drop usage.

> The basic HTML Bootstrapped template includes bootstrap.min.css, jquery.min.js,


bootstrap.min.js, and the jQuery library prior to the Bootstrap library.
> The default Bootstrapped template contains the viewport meta tag to make a Webpage
responsive.
> Bootstrap 3 is mobile first, which means the mobile-friendly styles are present throughout the
library rather than in isolated files.
> Bootstrap comes with two types of containers namely, fixed width and full width containers.
> There are two ways of using JavaScript plugins namely, through data attributes and via JavaScript.
> Bootstrap template are sample Webpages designed for using the bootstrap framework.
Developing Responsive Websites with Bootstrap and jQuery

Check Your Progress

1. Which of the following Bootstrap statements is true?


a. It is hard to get started.
b. It is a tem plating system .
c. It is a new version of JS.
d. All o f these
2. Which of the following options allows downloading Bootstrap without the source code or
documentation?
a. Precom piled
b. Source
c. Saas
d. None of these
3. Which of the following file naming conventions indicates minified and compiled files in the Bootstrap
structure?
a. Bootstrap.*.m in
b. Bootstrap.m in.*
c. Bootstrapm in.*
d. Bootstrap.m in*
4. Which of the following properties ensures that the page shall fit into the screen of the target device?
a. View port
b. Initial-scale
c. Device-w idth
d. W idth
5. Which of the following contains two different form of verbs for handling plugin actions?
a. Events
b. Data attributes
c. Program m atic API
d. O nly HTM L com ponents
Developing Responsive Websites with Bootstrap and jQuery

Answers to Check Your Progress


1. It is a templating system.
2. Precompiled
3. Bootstrap.min.*
4. Width
5. Events

Answers to Quick Test


Quick Test 1.1

1. False
2. True
Developing Responsive W ebsites with Bootstrap and jQuery

SESSION 2 - Understanding
Programming in Bootstrap_____
Session Objectives:
This session introduces different types of components available in Bootstrap. It also explains how to
use these components and how to apply Cascading Style Sheet (CSS) and JavaScript (JS) to them. The
eoeeion also briefly oxplains how to start coding in Bootstrap by modifying its dofault tomplato.----------

At the end of this session, you will be able to:

> Use different Bootstrap components


> Write programs in Bootstrap
> Apply CSS and JavaScript to Bootstrap components

2.1 Components in Bootstrap


The modular Bootstrap framework encompasses a collection of Less stylesheets that utilize its
different components. Bootstrap compiles them into a bundle for adding to Webpages although
individual sections are removable or replaceable. The stylesheets offer standard style definitions for
all major HyperText Markup Language (HTML) components. They offer an even and stylish look by
enabling formatting of text and forms.

There are a i et lfigqratron variables l liat regulate Hie

visible aspects of components such as padding and color. From Bootstrap 2, a customization wizard
creates a tailored version of Bootstrap, as per the desired components and its different settings.

Each Bootstrap component comprises an HTML structure, CSS code, and even associated JavaScript,
if required. In addition to the standard HTML components, Bootstrap offers other widely used
interface components. Web developers implement these components as CSS classes that are
applicable to some HTML elements in a Webpage.

Bootstrap also provides a variety of JavaScript components, which are available as jQuery plugins.
These components offer additional elements such as carousels, modals, tooltips, alerts, popovers,
drop-downs, and dialog boxes. They also extend the functionality of a few prevalent elements. For
example, an input field is now available with an auto-complete function.

Bootstrap 3 supports the latest Firefox, Opera, Chrome, Safari (not on Windows), and Internet
Explorer (IE) versions. It also supports the IE8 and the latest Extended Support Release (ESR) of
Firefox. In all these browsers, the Bootstrap components render themselves smoothly without
affecting consistency in appearance.

2.2 Layout Components


In Bootstrap, there are dozens of layout components all of which are reusable. They include
glyphicons, drop-downs, button groups, navbar, breadcrumbs, labels, badges, pagination, input
groups, progress bars, and panels.

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

2.2.1 Glyphicons

There are more than 250 glyphs or icon fonts in Bootstrap. They are available in the font format in
Glyphicons Halflings files of the font folder. Although not usually available free of cost, the set is
available for free usage through Bootstrap. Any of these icons needs a base as well as an individual
icon class. Following is the syntax for inserting a glyphicon:
<span class=" glyphicon glyphicon-<name>"x/span>
where,

• glyphicon: Is the base class.


• glyphicon-name: Is the individual icon class. It uses the Unicode font reference in
Glyphicons Halflings for rendering the icon on a Webpage. For example, the Unicode font for
envelope icon is 2709.
• name: Is to be replaced with the exact glyphicon name.
A Web developer should use an icon class only on elements that have neither text nor child
elements. Similarly, it is impossible to combine icon classes directly with other components. Further,
Web developers should not use them with other classes for the same element. Rather, it is
recommended using the icon classes within a nested <span> tag.
Figure 2.1 shows the code for displaying envelope and search glyphicons.
< ! D O C T Y P E h e m lg

Khtml lang="en">
|<head>
<title>Bootstrap Example</title>
<meta charset-"utf-8">
<meta name="viewport" content*"width=device-width, initial-scale=l">
<link rel="stylesheet" href=’’https.:jymaxc.c^ubpotstx.apccln...com/bpotstrapyj...3.,_T/cs.s./.b<a.Q.ts.t.rap_..min...g.ss''>
8 <script src="https ://aiax.qoocileapis.com/aiax/libs/icmerv/3.1.1/icmerv.min. is"X/script>
9 <script src»"https://maxcdn. boots trapcdn. com/bootstrap/3.3.7/is/bootstrap.min. js,,X/script>
10 </head>
11 |<body>
12
13 Kdiv class“"container">
14 <h2>Some Glyphicons</h2>
15 <p>Envelope icon: <span class="glyphicon glyph icon-enve lope " X / spanX/p>
£] <p>Hyperlinked Envelope:
<a href="#"Xspan ciass="glyphicon glyphicon-envelope"X/span></a>
18 </p>
19 <p>Search: <span class="glyphicon glyphicon-search"X/spanX/p>
20 </div>
21
</body>
</html>

Figure 2.1: Code for Envelope and Search Glyphicons

In figure 2.1, there is a space between the text and span tag specifying the appropriate glyphicon.
This is essential for putting space between the text and its glyphicon while displaying them in the
browser. Figure 2.2 shows these glyphicons.

Som e Glyphicons
Envelope icon: 3E
Hyperlinked Envelope: 55
searcn: Q.

Figure 2.2: Envelope and Search Glyphicons

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

For the users of assistive technologies, there are a few things to consider. The aria-hidden
attribute should be set to true to prevent any kind of unwanted or confusing output by a screen
reader. This is essential if the icons are just for decorative purpose. This is because the latest
assistive technology version of a reader tends to read both Unicode characters and CSS generated
content. Therefore, it can result in a confusing output due to which the attribute is used to hide the
characters.

In case of a component using only an icon and nothing else, it is rational to offer alternative content
to state the purpose of that component for the screen reader users. To do so, just add the arial-
label attribute to the element itself.
Example 2.1 shows the usage of aria-label and aria-hidden attributes.
<button type="button" class="btn btn-default" aria-label^ "Left
Align"xspan class="glyphicon glyphicon-align-left" aria-
hldden= "true"></spanx/button>

<button type="button" class="btn btn-default btn-lg">


<span class="glyphicon glyphicon-open" aria-hidden="true">
</span> Open</button>
Example 2.1: Usage of aria-label and aria-hidden Attributes

If there is an icon that reflects the desired text graphically, it is essential to ensure that a screen
reader conveys this text. For example, a Web developer can consider using the . sr-only class for
hiding the additional content on a Webpage but making it available for a screen reader to read.

Figure 2.3 shows the code for using the sr-only class to convey an error message.
1 < .1,DOCTYPE
: Bchtml lang-"en">
ychead>
Ctitle>Bootstrap Example</title>
<meta charset-"utf-8">
<meta name-"viewport" content-"width—device-width, initial-scale—1">
clink re 1-"stylesheet" href-"https;//maxcdn.bootstrapcdn,coro/kQ.o£s.£rap/_3^.3-^-?-/css/bootstrap,nun,css">
Cscript src-"https;//ajax.googleapis.com/ajax/libs/jquery/3,1 ,1/jquery,min.js">C/script>
Cscript src-"https://maxcdn .bootstrapcdn.co?n/bootstrap/3 .3 .7/Is/bootstrap .min.1s">C/script>
-C/head>
Bcbody>

yCdiv class-"container">
Cdiv class-"alert alert-danger" role-Malert">
Cspan class-"glyphicon glyphicon-exclamation-sign" aria-hidden-"true">C/span>
Cspan class-"sr-only">Error:C/span>
Enter digits only
-C/div>

C/body>
-C/html>

Figure 2.3: Code for Indicating an Error Message via the . sr-only Class

In figure 2.3, the icon of exclamation sign is used to indicate an error message. The sr-only class
conveys this error to the users of screen readers.

Figure 2.4 shows the output.

Q Enter digits only

Figure 2.4: Error Message

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

2.2.2 Navbars
A navbar or a navigation bar is a responsive navigation header visible on the top of a Webpage. In
Bootstrap, it is collapsible or extensible, as per the size of the targeted screen. A navbar can contain
links, drop-downs, buttons, icons, or a combination of all. A Web developer can align these elements
to left or right. A navbar is set horizontally when the existing width of the viewport increases.

Figure 2.5 shows the code for a navbar having three links namely, Home, About us, and Contact us.
<!DOCTYPE html>
2 F]<html lar.g="en">
3 J<head>
4 <title>Bootstrap Case</title>
5 diet a char3et="utf-8">
6 <raeta r.ame="viewport" content="width=devicel
7 <link rel»"stylesheet" href“"https://maxcdnI Note: If JavaScript is disabled in the user's
8 <script src="https://ajax.googleapis.com/ajl
9 <script src="https://maxcdn.bootstrapcdn.coi| browser and the viewport is so narrow
10 b</head>
11 ■D<body> that a navbar collapses, it is unfeasible to
12
13 D<nav cla33="navbar navbar-default"> expand the navbar or see the content in its
14 <div class="container-fluid">
15 <div class“"navbar-header"> collapsed state.
16 <a class="navbar-brand" href="#">WebSit<
17 </div>
18 <ul class="nav navbar-nav">
19 <11 cla3s="active"><a href="#">Home</a>*
20 < l i x a href-"#">Home</ax/li>
21 < l i x a href="#">About us</a></li>
22 < l i x a href="#">Contact us</ax/li>
23 </ul>
24 </div>
25 -</nav>
26
27 y<div class="container">
28 <h3>Basic Navbar</h3>
29 <p>A navigation bar is a navigation header 1
30 -</div>
31
32 -</body>
33 ^-</html>

Figure 2.5: Navbar Code

In figure 2.5, <nav class=" navbar navbar-default"> creates a standard navigation bar.
an unordered list. The active class indicates that the Home page is the current Webpage displayed
in the browser.

Figure 2.6 shows the output.

W ebSiteN am e Home Home About us Contact us

Basic Navbar
A navigation bar is a navigation header that s placed at the top of the page

Figure 2.6: Default Navbar

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

Bootstrap cannot recognize the amount of space the


content requires in a navbar. Therefore, it might trigger Note: it is impossible to add several
some content wrapping issues in the second row. To avoid form controls in an input group.
them, a Web developer can reduce the width or number of
navbar items.

For the users of assistive tools, Web developers must use <nav> or role= ” navigation ’ for
each navbar in case of a generic element such as <div>. This explicitly recognizes that section for
those users.

2.2.3 Input Groups


Bootstrap supports input, textarea, radio, select (even with multiple select), and check box form
controls. It also supports all input types of HTML5, which are:

• Text
• Number
• Password
• E-mail
• Datetime, datetime-local, week, time, month, and date
• URL
• Search
• Color

Example 2.2 shows how to create text and password input controls using the . form-control
class.
<div class="form-group">
clabel fbr="user">Name:</label>
cinput type="text" class="form-control" id="user">
</div>
<div class="form-group">
clabel for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
Example 2.2: Using the form-control Class

In example 2.2, the form-group class adds some space between controls.

Input groups are referred to as extended form controls using which it is easy to append or prefix
icons, buttons, or text to an input field. For example, you can prefix an input field taking price in
Dollars with a Dollar icon.

Bootstrap provides the . input-group container class for improving an input by adding help text,
button, or an icon in front or at the rear. It also offers the . input-group-addon class that
affixes text, icon, or button to the input field.
Figure 2.7 shows the code for using these input group classes.

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

<I DOCTYPE hCXLi>


0 < h t m l Iang - " e n " >
';’< h e a d >
<title>Bootatrap Exanple</title>
<ia«Cd chdi3et-**utf -8**>
< a e t a narao-"v i e w p o r t " c o n t o n t - " w i d t h - d o v i o o - w i d t h , i n i t i a l - s c a l o - l " >
< l i n k r o . - " s t y i o s h o o t " hr»f""tittjM.>//aa3Lgdn.lw>tgtjcapflda>.c«a/faQg.ta.ti:ao/3^ J/Zcaa/Jfeog.ta.txap.nip.cjsa">
< s c r i p t src«"htt,pa;//a^ax.gooalfiaplgu.Gflm/a^aai/lil?a/j<ruery/3.1.X/^querYiaini3a"X/script>
< a c r i p t 8 r c » whtU?a://rwmLcdn.bogtatJCdygda>g<Ki/bootaLr«ip/3..3>?/Ja/l?ogt>aixatf.aAn.Ja,,> < / a c r i p t >
:o -</h«ad>
:: 0<body>
I;Kform>
H <div ciaas«"input-group">
:■* < s p a n c l a s s * " i n p u t - g r o u p - a d d o n ">
<i c l a s s - " g l y p h i c o n g l y p h i c o n - u s e r " X / i X / s p a n >
:t < i n p u t id-"e?nai 1" t y p«-"text" c l a s s - " f o r m - c o n t r o l "
naae-"onail"
:e p i a c © h o l d o r - " K n t o r E - n a i l . ">
19 </div>
2j
‘ 0 < d i v c i a a a - M i n p u t - g r o u p ”>
21 y < s p a n class"**i n p u t - g r o u p - a d d o n ">
<i c l a s s - " g l y p h i o o n g l y p h i c o n - l o c k " X / i X / s p a n >
<input id-"pasaword" type-"paaaword" class-"form-oontrol"
24 r.aa««Hp d S s w o r d M
25 p ia c © h o ld o r - "K n t o r p a s s w o r d .">
2® </div>
2? <br >
zi B < d iv e la *»- "in p u t- g r o u p ">
<span class-"input-group-addon“>Toxt</span>
< i n p u t id-"msg" t y p*«"text" c l a s s - " f o r m - c o n t r o l " n M M - " m a g "
plac*hold«ia"Bnt«r mor« dotal In, if a n y . H>
52 </div>
as <br>
•1 LI <div class-"input-group">
<inpuc typo-" text" class-"forsi-control" placeholdo?-"Enter what
you w i s h to sear c h . *>
5 Li <div class-"input-group-btn">
C! <button claso-"btn btn-dofault" type-"submit">
<i claas-"glyphlcon glyphioon-so«»rch"X/i>
40 </button>
41 < /d i v >
42 </form>
•*: </body>
*i |-</hunl>

Figure 2.7: Code for Input Groups

In the example, the code for user and lock glyphicons is added before the < in p u t > element so that
the icons become visible before the input element. However, the code for search glyphicon exists
after the element so that the search icon appears after the element.

Figure 2.8 shows these input controls.

x
A
Ted llta n m M « « Jr*

[WMmKMoxm Q

Figure 2.8: Input Groups

2.2.4 Pagination
In case of a Website with many pages, adding blocks of page numbers or pagination component is
useful. To add this component, a Web developer should use the . pagination class in the <ul>
element.

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

Figure 2.9 shows the code for adding the default pagination component.

< ! D O C T Y P E htrtl>
2 <html lang - " e n " >
3 <head >
4 <ti t l e > B o o t s t r a p E x a m p l e < / t i t l e >
5 <nveta c h a r s e t « " u t f - 8 ,,>
6 one t a r.ojne-’’vie w p o r t " cor.ter.t""width"device-vidth, i n i t i 4 l - s c a l e - l " >
7 <ll n k rel""» t y l e s h e e t " h r e f ""h t t p s :/ / m a x c d n .b o o t s t r a p e d n .c o m / b o o t s t r a p / 3 .3.7 / c s s / b o o t s t r a p . m i n .css">
8 o c r i p t 3 r c “ "h t t p s : / / a 3 a x . g o o g l e a p i s . c o m / a 3 a x / l i b s / 3 q u e r y / 3 . 1 .l/}query.Bin. 5 * " x / s c r i p t >
9 < s c n p t s r c * " h t t p s :/ / m a x c d n .boo t s t r a p c d n .c o n / b o o t s t r a p / 3 .3.7 / j s / b o o t s t r a p .mi n .} s " X / s c r i p t >
10 -</head>
<body >
12
13 0 < d i v clas3*"container">
14 <h2 > P a g i n a t i o n < / h 2 >
15 < p > T h e .pagination cl a s s p r o v i d e s p a g i n a t i o n l i n k s :</p>
16 E~] <ul c l a 3 3 " " p a g i n a t i o n " >
17 <lixa href-"#">l</ax/li>
18 < U X 4 href-"#">2</ax/li>
19 <11X4 href-"#">3</ax/ll>
20 <11X4 href«"#">4</ax/li>
21 <11X4 href-"#">5</4X/ll>
22 <11X4 href-"#">6</4X/li>
23 </ul>
24 </div >
25
26 </bod y >
27 L</html>

Figure 2.9: Pagination Code

Figure 2.10 shows the output.

Pagination
The pagination class provides pagination links:

1 2 3 4 5 6

Figure 2.10: Pagination

2.2.5 Page Headers


The page header component is similar to the <H 1> tag. It acts as a section splitter and adds proper
spacing to the Webpage headings. This is useful for distinctly showing each title on a Webpage in
case there are many titles. To add a page header, a Web developer needs to wrap the title within
<div> and use the . page-header class.
Figure 2.11 shows the code for including a page header.
< !D O C T Y P E h t m l >
[ip]<html lar.g""cn">
y<head>
<title>Bootstrap Exam p l e C / ticle>
<meta char3et*"utf-8">
< m e t a n a m e — " v i e w p o r t " c o n t e n t — " w i d t h — d e v i c e - w i d t h , i n i t i a l - s c a l e — 1">
<lin)c r e l — " s t y l e s h e e t " h r e f — "h t t p s :/ / m a x c d n .b o o t s t r a p e d n .c o m / h o o t s t r a p / 3 . 3 . 7 / c s s / b o o t s t r a p . m i n . c s s ">
O c r i p t a r c - " h t t p s :/ / a j a x .g o o g l e a p i s .c o m / a j a x / l i b s / j q u e r y / 3 .1 . 1 / j q u e r y .min. j s " X / s c r i p t >
O c r i p t s r e - "h t t p s :/ / m a x c d n . b o o t s t r a p e d n .c o m / b o o t s t r a p / 3 . 3 .7 / j s / b o o t s t r a p . m i n . j s " > < / scri.pt>
</head>
L~)<bcdy>

b j<div c l a s s — " p a g e - h e a d e r ">


<hl>Example page header O m a l l > S u b t e x t for header</small></hl>
</div>

</body>
</html>

Figure 2.11: Page Header Code

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

In figure 2.11, the component uses the small element (default) of <H 1> to display text in small
case next to the header text.

Figure 2.12 shows the output.

Example Page Header Subtext for header

Figure 2.12: Page Header

2.2.6 Badges

In Bootstrap, badges are special labels indicating new items, which are similar to number of unread
e-mails near the Inbox tab in an e-mail account. They show numerical values that indicate the
number of items related to a link. For creating badges, a Web developer should use
the . badge class within <span> or other elements such as buttons and list groups.

Figure 2.13 shows the code for creating badges, wherein 2, 1 1, and 12 are badges.

1 <!DOCTYPE hcml>
2 EJchtml lang="en">
3 Hchead>
Ctitle>Bootstrap Examplec/title>
cir.eta charset="utf-8">
6cmeta r.air.e="viewport" content="width=device-width, initial-scale=l">
Clink rel»"stylesheet" href-"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
Cscript src="https://ajax.googleapis.com/ajax/libs/jquery/3.1 .1/jquery.min.js">C/script>
cscript src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">C/script>
10 -c/head>
11 Hcbody>
12
13 Qcdiv class»"container">
Ch2>Badges</h2>
ca href="#">Hello cspan class="badge">2c/span>c/a>cbr>
ca href="#">World cspan cla3s="badge">llc/span>c/a>cbr>
ca href="#">Folks Cspan clas3="badge">12c/span>c/a>
-C/div>

c/body>
LC/html>

Figure 2.13: Badges Code

Figure 2.14 shows the output.

Badges
Hello O
World Q
Folks

Figure 2.14: Badges

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

2.2.7 Panels
A panel refers to a container that can hold other components such as lists and tables with proper
padding. The . panel base class is used to create a panel with standard padding and border, while
the . panel-body class is used to place the content inside it.

Figure 2.15 shows the code for creating a panel.


<! DOCTYPE html>
2 <html lang="enM>
3 <head>
4 <title>Bootstrap Case</title>
5 cmeta charset="utf-8">
6 <rr.eta name""viewport" content""width—device-width, initial-scale-l">
7 Clink rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3 .7/css/bootstrap.min.css">
8 O c r i p t src="https ://ajax.googleapis .com/ajax/libs/jquery/3.1.1/jquery .min. j s " X / s c r i p t >
9 O c r i p t src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.j s " X / s c r i p t >
10 </head>
11 Ej3<body>
12
13 |<div cla3s="container">
14 <h2>Demo Panel</h2>
15 I <div class="panel panel-default">
16 <div class""panel-body">A Basic Panel</div>
17 </div>
18 </div>
19
20 </body>
21 L</html>

Figure 2.15: Panel Code

In figure 2.15, the . panel-default sub-class retains the default color style for the panel.

Figure 2.16 shows the output.

D em o Panel
A B asic Panel

Figure 2.16: Panel

2.2.8 List Groups


A list group renders an unordered list of items. Apart from this standard use, the component also
renders complex and tailored content. To create a standard list group, a Web developer should
include the . list-group class within <ul> and the . list-group-item class within <li>.

Figure 2.17 shows the code for creating a list group with badges on the right.

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

1 <!DOCTYPE html>
2 khtxnl lang="en">
3 !< h e a d >
4 <title>Bootstrap Example</title>
5 <meta charsec="utf-8">
6 <meta r.ame="viewport" content="width=device-width, initial-scale=l">
7 Clink rel="stylesheet" href“ "https://maxccln.bootstrapedn.com/bootstrap/3.3.7/css/bootstrap.min.css">
8 <script src*”https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"X/script>
9 <script src“"https://maxcdn.bootstrapedn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
10 </head>
11 kbody>
12
13 kdiv classas"container">
14 <h2>List Group With Badges</h2>
15 <ul class="list-group">
16 <li cIass="list-group-item">Hello <span class="badgel,>2</span></li>
17 <li class="list-group-item">World <span class="badge">15</span></li>
18 <li clas3="list-group-item">Folks <span clas3=”badge">13</span></li>
19 </ul>
20 </div>
21
22 </body>
23 </html>

Figure 2.17: List Group Code

Figure 2.18 shows the output.

List Group With Badges


Hello o
world o

Folks o

Figure 2.18: List Group with Badges

2.2.9 Progress Bars


A progress bar shows the status of an action or a process in progress, such as downloading and
uploading a file. It can even indicate a feedback or convey that an action regarding the Webpage
elements is occurring. Bootstrap offers different types of progress bars, that are as follows:

• Default
• Striped
• Animated
• Stacked

Figure 2.19 shows some of these progress bars.

Default Progress Bar Striped Progress Bar

Stacked Progress Bar

Figure 2.19: Different Progress Bars in Bootstrap

To generate a progress bar, a Web developer needs to use the . progress class in <div>.

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

Figure 2.20 shows the code for including a progress bar with a label showing the percentage of
progress.
<<!D0CTYPE htitj>
2 lan^""en">
B<< h ead >
<title>Bootstrap Example</title>
<roeca c h a r 3 e t - " a t f - 8 " > Note: JavaScript can also be a part of
< m e t a r.ar.e*"viewport" conter.t“ "width«device-wicl
clinic rel*"s t y l c s h e e t " h r e f • " https://ioaxcdn.boci the head section. However, it is ideal to do
<scnpt s r c « " h t t p s :/ / a j a x .googlcapi s .con/ajax/ll
<scnpt s r c - " h t t p s :/ / m a x c d n .b o o t s t r a p c d n .cora/bcj so. A browser loads a Webpage step wise
< /hea d >
<body >
from top to bottom. If JavaScript is present

? <div c l a 3 3 " " c o n t a l n e r " >

<h2>Proaress Bar With Label</h2>


in the head section, it may slow down the
loading orocess.

Progress Bar W ith Label

Figure 2.21: Progress Bar with a Percentage Label

Progress bars in Bootstrap implement CSS3 animations as well as transitions for a few effects.

2.3 Programming in Bootstrap


After setting up the environment for Bootstrap, a Web developer can start programming in
Bootstrap. CSS forms the core of Bootstrap and always exists in the head section, while JavaScript
comes at the end of the body section. In Bootstrap, JavaScript also depends on jQuery. Thus,
programming in Bootstrap consists of the following three main parts:

• Bootstrap CSS in the head section

• Bootstrap JavaScript at the end of the


body
Note: While Opera 12 has no support for
• jQuery at the end of the body
animations at all, older Firefox versions
and Internet Explorer 9 and below do not
support these effects.

V l.O © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

Figure 2.22 shows the basic template, which acts as a foundation for writing Bootstrap code.
<!DOCTYPE html>
2 E<html lar.g-"en">
3 H <head>
4 <meta charset*"utf-8 ">
<meta http-equiv-"X-UA-Compatible" concent*"3
<meta name*"viewport" content*"width-device-v
<!— The above 3 meta tags “muse* come first
any other head content must come *after* the
<title>Bootstrap Basic Template</citle>
10 <!— Bootstrap — >
<linJc href""css/bootstrap, rain,css" rel*"styl«
12
13 <!— HTML5 shim and Respond.3 s Cor IE8 suppos
<!— WARNING: Respond.js doesn't work if you
15 B <! — (If It IE 9] >
16 o c r ip t 3 re-"n^vc?; //sss .maxcdn■sam£isal5 aS
ocripc src="https://css .ir.axcdn .com/responc
18 - <![endlf] — >
19 - </head>
20 El <body>
21 <hl>Hello, world!</hl>
22
23 <!— 3 Query (necessary for Bootstrap's JavaSc
2~ o crip t 3rc~"https: //alax.oooaleaDis.com/a1a3i
25 <!— Include all compiled plugins (below), ojT
26 ocrlpc sre-"js/bootstrap.min. js"X/script;> Note:: For an <a> element, a Web
27 - </body>
28 L</hcml> developer should use the href
attribute rather than data-target.
Figure 2.22: Basic Bootstrap Template for
Programming

In figure 2.22, the html5shiv.js and respond.min.js files are added so that IE 8 can render the HTML5
elements. A Web developer needs to modify this template by adding the desired CSS and JavaScript
code for creating the intended Website.

To start programming in Bootstrap, let's modify this template to add a collapsible. A collapsible is
useful for showing or hiding a huge amount of content.

Figure 2.23 shows the code for adding collapsible content through Bootstrap code.
<!DOCTYF£ i t sl>
2 5<htal>
<head>
<s&ta naae-"viewport" conter.f"width-devioe-width, initial-scale-l">
<link rel-’ stylesheet"
<script src-"https://ajax.googleapis.ccn/ajax/libs/jquery/3.1.1/jquery.nln. js"X/script>
<script src-"httpg.;//n^c<iii,l? ^ tsUap«in.,c^a/l?^tsUapy3J,?/^/^t$tiagJinia, jg"X/script>
*</head>
9 3<body>
10 I
3<div ciass**container’ >
<h2>Collapsible Exanple</h2>
<buttor. type*"botton" class-"btn btn-info" data-tcggie-"collapse" id-"myBtn" data-target-"fde.r»o,,>Collapsible</button>
2 <div id-’ deno" class*"oollapse">
Collapsibles are useful when you want to hide and show large a'nount of content
:i h </div>
17 *</div>

K/body>
‘ </htal>

Figure 2.23: Bootstrap Code for Adding Collapsible Content

In figure 2.23, class= "collapse” marks a collapsible content, which is <div>. This content is
displayed or hidden when a user clicks the button of type info, which is created using the btn-

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

info class. To set the suitable toggle behavior for showing and hiding the content, the value of the
data-toggle attribute is set to collapse. The data-target attribute links the button with
the corresponding collapsible element.

Figure 2.24 shows the output.

Collapsible Example
Collapsible
Collapsibles are useful when you want to hide and show large amount of content

Figure 2.24: Collapsible Content

By default, the collapsible content is hidden. When a user clicks the button, the content becomes
visible. Upon clicking the button once more, the content hides, as the <div> tag collapses. To show
the content by default, a Web developer should use class=collapse .in in the <div> tag.

Figure 2.25 shows how to use JavaScript to create collapsible content.


< !KCHFE Ss«l>
} B<html>
3 2<heaa>
( <aeta na3e-"viewport" conter.t*”width-device-width, initia Note: The Bootstrap version in use
<linic rei-'stylesheet" href-"https:/Aiaxodn.bootstrapedn.
should include the transition.js (plugin)
<script src-"https ; / / w . x-gm l e a g i s .wrc/ a t o / l t o / i i m e n
<*cript src-"https://r»xcdn.bootstrapedn.con/bootstrap/3 for proper functioning of collapsible.
8 -</head>
9 2<body>
19 |
is 8< div class**container’ >
<h2 C o lla p s ib le Exa.Tple</h2>
<button type-”button" class-’ btn btn-info" id-''nyBtn">Coll
<div • d*"der»" class-"oollapse">
Collapsibles are useful when you want to hide and show
1« > </div>
17 -</div>

18
19 2<script>
: i tdccaten:) .r ta iy lto c c io o O (
:: $ ((’i-/3-").cllck(Aiactloo(){
22 S('.c4lla;.'t').cclltp3«();
2^ r II:
2i )):
J5 ^</script>
2i -</body>
2' -</html>

Figure 2.25: JavaScript Code for Collapsible Content

In figure 2.25, appropriate JavaScript code in the <body> tag specifies what should happen on the
click of the button. The $ ( ' . collapse ' ) .collapse () ; statement internally uses the collapse
plugin to automatically provide the control over <div>.

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

2.4 Demo on Bootstrap Functionality


Let's see a sample Bootstrap application by designing an HTML form. Styling the controls in an HTML
form one by one with manual CSS code is often tedious and subject to errors. Bootstrap eliminates
tediousness and risk of errors by offering a predefined collection of classes for styling and aligning
the form controls.

For forms, Bootstrap offers three layouts, which are as follows:

• Vertical
• Horizontal
• Inline

Irrespective of a layout, a Web developer needs to wrap each element in <div> that uses the
. fo r m -g r o u p class. This is required for optimal spacing. Further, it is necessary to use the
.form-control class in the <input>, <textarea>, and <select> elements.
2.4.1 Vertical Forms

A vertical layout is the default layout in Bootstrap for forms. In this layout, styles are specified for
controls without a base class. The controls are piled with labels that are alighed to the left.
Figure 2.26 shows the code for creating a vertical form having two input fields, two labels, a check
box, and a button. The vertical layout is the default form layout in Bootstrap.

<!DOCTYPE hcml>
F)<html lar.g*"en">
0<head>
<title>Bootstrap Example</title>
<meta charset»"utf-8">
<rr.eta name*"'viewport" cor.tent*"width=device-width, initial-scale=l">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.roin.css">
<script 3rc»"https://aiax.qooaleapis.com/aiax/libs/icrnerv/3.1.l/icroerv.min.is"x/3cript>
<script src="httK>s ://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/is/bootstrap.min. is"x/script>
-</head>
0<body>

R < d i v class="contai:ner">
F] <forin>
H <div class="form-group">
<labei for="email">User Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email">
</div>
H <div class="form-group">
<lafcel for="pwd">Password:</lafcel>
<input type="password" cla33="form-control" id="pwd" place'nolder="Enter password">
</div>
3 <div class="checkbox">
<labelxinput type=" checkbox" > Remember me</label>
</div>
Cbutton t\'pe="submit" class="btn btn-default">Submit</bucton>
</form>
-</div>

-</body>
-</html>

Figure 2.26: Code for Vertical Form with Controls

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

Figure 2.27 shows the output.

. Re-mefnt** me
SuCkth;

Figure 2.27: Vertical Form with Controls

At times, a Web developer may need to arrange the controls side-by-side for squeezing the layout
vertically. This is when an inline form layout is useful, which is likely to suit the device's screen. In an
inline form, all elements are in line, one after the other and are left-aligned. This is relevant to forms
displayed within a viewport whose width is minimum 768 pixels. To create an inline form, a Web
developer needs to include the . form-inline class in the <form> element.

Figure 2.28 shows the code for an inline form containing two labels, two input fields, a check box
and a button.
3<body>

3<div class="container">
<h2>Inline form</h2>
<form class="form-inline">
<div class-"form-group">
Clabel for="email">Email:</label>
<input type-"email" class-"form-contro
</div>
3 <div class-"form-group">
Clabel for="pwd">Password:C/label>
<input type»"password" class*"form-con|
</div> Note: The Bootstrap version in use
3 <div class*"checkbox">
ClabelXinput type="checkbox"> Rememb^ should include the tooltip.js (plugin) for
C/div>
Cbutton type="submit" class="btn btn-def| proper functioning of popovers.
</form>
-C/div>

-C/body>

Figure 2.28: Code for Inline Form with Controls

Figure 2.29 shows the output.

Inline form
Make the viewport larger than 768px wide to see that all of the form elements are inline, left aligned, and the labels are alongside.

Enter email P assword: Enter password □ Remember me Submit

Figure 2.29: Inline Form with Controls

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

Now, let's see how to implement jQuery in Bootstrap for creating a popover. A popover is analogous
to a tooltip. It refers to a pop-up dialog box appearing on clicking an element. However, unlike a
tooltip, a popover can display much more content.

Figure 2.30 shows the CSS and jQuery code for creating a popover.
<!DOCTYPE html>
Chtml lar.g="en">

<title>Bootstrap Example</t±tle>
<meta charset="utf-8">
<raeta name®" viewport" content="width=device-width, initial-scale=lM>
<linJc rel""stylesheet" href*"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css”>
<script src®"https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jqnery.min.js"X/script>
9 <scr±pt src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3 .7/js/bootstrap.min.js"X/script>
10 < /h e a d >
11 Ep<body>
12
13 <div clas3="container">
14 <h3>Javascript/JQuery Example</h3>
15 <a href™"#" data-toggle="popover" titleB "Popover Header" data-cor.ter.tB "Hi there! !">Toggle popover</a>
16 </div>
17
l<script>
I$ (document).ready(function(){
20 S ( ' [data-tocrgle="popover"] ') .popover (> ;
21 >> ;
</script>
23
24 < /b o d y >
</html>

Figure 2.30: Popover Code

In figure 2.30, data-toggle= ”popover" initializes a popover for the Toggle popover link.
The title attribute specifies the popover's header text, while the data-content attribute holds
the text that the popover should display in its body.

A popover is not CSS-only plugin due to which it is essential to initialize it through jQuery. So, in
figure 2.30, the jQuery statement, $ ( ' [ data-toggle=" popover" ] ') .popover ( ) , selects
the element that has the data-t:oggle property set to popover and invokes
the popover () method.

Figure 2.31 shows the output when a user clicks the Toggle popover link.

J a v a s c rip
~
t' Popover r“ ” - m ple
,rTv------Header r
Toggle popover
HI there!!

Figure 2.31: Popover Display

Quick Test 2.1

1. A W eb developer can use an icon class on the label element.


a. True
b. False

2. It is ideal to have JavaScript in the body section.


a. True
b. False

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

jT
__
V Summary

> Each Bootstrap component is reusable and comprises an HTML structure, CSS code, and even
associated JavaScript.

> Bootstrap provides a variety of JavaScript components, which are available as jQuery plugins.

>■ There are more than 250 glyphs in Bootstrap, which are available in Glyphicons Halflings files.
> An icon class is applicable to elements that have neither text nor child elements.
> A navbar is a responsive navigation header visible on the top of a Webpage and is collapsible or
extensible.

> Pagination refers to a block of numbers, each indicating a different page of a Website.
> Badges are special labels indicating new items, which is similar to the number of unread e-mails
near the Inbox tab in an e-mail account.
> A panel refers to a container that can hold other components such as lists and tables with proper
padding.
> A list group renders an unordered list of items as well as complex and tailored content.
> Bootstrap offers four main types of progress bars namely, default, striped, animated, and stacked.
> Programming in Bootstrap includes CSS in the head section and JavaScript/jQuery in the body
section.
> The html5shiv.js and respond.min.js files are included in the Bootstrapped template so that IE 8
can render the HTML5 elements.
> Bootstrap offers three form layouts namely, vertical (default), horizontal, and inline.
Developing Responsive W ebsites with Bootstrap and jQuery

Check Your Progress

1. Which of the following components is a jQuery plugin?


a. Page header
b. Popover
c. Badge
d. None of these
2. Which of the following classes is a base class for adding an icon in Bootstrap?
a .glyph
b .glyphicon-<name>
c .glyphicon
d .glyph-name
3. Which of the following classes adds spacing between two controls in a form?
a ..form-group
b ..form-corrtrol
c ..form-corrtrol --space
d ..form-group-space
4. Which of the following components aids in showing each title distinctly on a Webpage?
a. Pagination
b. Badges
c. Page header
d. None of these
5. Which of the following progress bars Bootstrap offers?
a. Animated
b. Vibrant
c. Horizontal
d. Inline
Developing Responsive Websites with Bootstrap and jQuery

Answers to Check Your Progress


1. Popover
2. glyphicon
3. .form-group
4. Page header
5. Animated

Answers to Quick Test


Quick Test 2.1

1. False
2. True
Developing Responsive W ebsites with Bootstrap and jQuery

( SESSION 3 - Basics of jQuery


Session Objectives:
This session introduces the jQuery library along with its basic concepts and implementation in
Bootstrap. It also describes the different jQuery selectors and various ways of creating functions. The
session also explains JavaScript Object Notation (JSON) along with its usage in jQuery. It further
explains conversions to JSON and event delegation in jQuery.

At the end of this session, you will be able to:

> Explain the basics ofjQuery and its usage with Bootstrap
> Outline selectors and functions in jQuery
> Describe JSON and its usage in jQuery
> Explain conversions to JSON
> Describe the concept of event delegation and its usage in jOuery

3.1 Introduction to jQuery and Integrating with Bootstrap


jQuery refers to a lightweight and concise JavaScript (JS) library that aims to make JS programming
easier and swifter. It is a feature-rich and open-source library that simplifies several complicated
tasks such as manipulating and traversing an HTML/CSS page, handling events, animating objects,
and making Asynchronous JavaScript and XML (AJAX) calls.

The library offers an easy-to-use Application Programming Interface (API) that is compatible across
several browsers. It wraps several common tasks into built-in methods. A Web developer can invoke
the desired method by writing just a single line of JS code instead of writing several lines of it. This is
how jQuery accomplishes the purpose of 'get more by writing less'.

3.1.1 Benefits of Using jQuery over JS


There are many JS frameworks available but jQuery is perhaps the most extendable one. Big brands
such as Google, IBM, and Microsoft are using it. Following are the benefits of using jQuery over JS or
other JS libraries:

• Unobtrusive JS: jQuery helps in designing Webpages through unobtrusive JS, an approach that
separates functionality between the presentation and structure of a Webpage. In other words,
inserting an event code in the script tag keeps the behavior separate from the Webpage's
structure or content.
• Lightweight: The reduced library size is in Kilobytes (KB), which is perhaps smaller than that of a
digital photo file. The jQuery version 2.x is smaller than the version 1.x. The former version is
more widely used, as it supports Internet Explorer (IE) 6/7/8. The browser needs to download it
once and cache it for using it in all Webpages of a site. In case a Web developer relies upon a
Content Delivery Network (CDN), the browser tends to cache the library across several Websites
instead of downloading for each.
• Ease of Use: This is due to the simple yet robust syntax and significantly reduced lines of JS code.
The syntax makes it simple to select the page elements that need a change. For this, the library
uses CSS3 selector specification, which eliminates the need to learn the jQuery syntax.
• Big and Focused Library: Unlike other JS libraries, Web developers can perform a variety of
functions. Further, to make JS tasks easier, jQuery offers several utility functions.

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

With these functions, Web developers can parse data, trim strings, and search for array
elements based on a filter. However, the library is focused, which means it contains only
essential features. A Webpage downloads only those features that it requires.
• Extensibility: jQuery comes with a plugin framework due to which it is simple to extend jQuery.
The framework includes both third-party and official plugins. So, if a feature does not exist in the
library, a Web developer may include it through a plugin.
• Browser Compatibility: Just as in few other JS libraries, jQuery flawlessly resolves cross-browser
issues. JS implementations tend to vary amongst browsers, which can take much time of Web
developers to get the code working across browsers. However, the makers of jQuery have
already implemented the code to display Webpages seamlessly across all major browsers.
• Strong Community: Although a new library, jQuery has an exclusive community through which
the dedicated developers tend to improve its functionality. Through this community, there are
several plugins available to accelerate the Web development process. Most of the plugins are
secured and efficient.
• AJAX Support: jQuery easily allows creating AJAX templates for gaining the benefits of smoother
interfaces and efficient loading. A user can perform an action on a Webpage without reloading
the whole page.
• Comprehensive Documentation: Official Website of jQuery has in-depth documentation and
tutorials, which helps even a beginner in programming to start easily.
3.1.2 Using Bootstrap and jQuery Together
Web developers can also jQuery with Bootstrap through the jQuery Ul Bootstrap theme, as shown in
Figure 3.1.

jQuery Ul Bootstrap

Accordion Buttons

- First D««ftA 1 2 1 ^ s s
|

lortm tpwm dolor « lc*em ipsuro dofor srt an-*< lor*m ipvum dolor Anchor Submrt
sA
Chcxt 1 1 (>■«<• ?
» Second
B 1 U
» Third

Figure 3.1: jQuery Ul Bootstrap Theme


Image Courtesy: https://webresourcesdepot.com
The theme allows using Bootstrap-themed widgets without breaking the appearance of
components. Originally, Bootstrap and jQuery cannot exist simultaneously due to which using them
together triggers conflicts with JS and CSS styles and classes. However, the new theme comes with
the relevant JS and CSS for designing a Web application using jQuery and Bootstrap. It also offers the
Bootstrap theme for several third-party jQuery widgets for designing user interfaces. Following are
the steps to use the theme:

1. Download the archive from the Internet.


2. Unzip it.
3. Look for custom-theme folder within the css folder of the unzipped package.

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

4. Move the custom-theme folder to the css folder of the Web application for which this
theme is to be used.
5. Add the relevant .css files to the Website's layout.

3.1.3 Using jQuery in Web Applications

The jQuery library is a JS file that a Web developer uses for programming in jQuery for developing a
Web application. There are two ways to use the file, which are as follows:

• Download the library file from jQuery.com and refer it in the HTML code just as a Web
developer would do for any other JS file. Save the downloaded file in the directory of
Webpages.
• Include the library into the code by referring to a CDN, such as Google and Microsoft. Code
Snippet 1 shows how to refer to the Microsoft CDN.
Code Snippet 1:
<head>
<script src="https: //ajax . aspnetcdn.com/ajax/jQuery/J query-
3.2.0.min.j s "></script>
</head>
3.1.4 Understanding the jQuery Syntax

With jQuery, a Web developer can quickly find and select an HTML element and trigger the desired
action or actions on it. For this purpose, the makers of jQuery have offered a customized syntax,
which is as follows:

$ ( selector) . action ()

where,
• $: Is the sign that indicates the use of jQuery and is the jQuery identifier.
• (selector):Is used to find and select the HTML element or elements.
• action ( ) : Is an action that jQuery should perform on the selected element or elements.
Following are a few samples that indicate how the syntax is used:
• $ (this) .hide () for hiding the element that is selected at present
• $("div") .fade In () for fading in all <div> elements
• $("#info") ,hide() for hiding an element whose id is setas info
• $ (" .info") .show () for showing an element whose class attribute as the value,
info
From these examples, it is clear that the selector can be an id, class, element, or this. Any jQuery
code exists within the document ready event. This helps in executing the code only after the
Document Object Model (DOM) loads completely or is ready. Following is the syntax of the event:
Syntax
$ (document).ready(function()
{
// Code jQuery functions here.
});

V l.O © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

OR
$ (function()//Alternate syntax
{
// Code JQuery functions here.
});
Where,

• $: Is the jQuery identifier.


• document: Refers to the DOM of the HTML page.
• ready: Is an event that is raised when the fully loaded DOM is ready for manipulation
through JavaScript. At this point, the script can safely findand access the HTML elements in
the DOM. For example, it can find the <a> element for associating it with a click event
handler.
• function: Refers to an anonymous function, as it has no name and it contains an action to
be taken.
It is rational to wait for the DOM to load fully before the HTML page handles any requests and
responses. This is because it is not sensible to hide an element or resize an image, which is not
loaded completely. This enables a Web developer to include JavaScript code inside the <head> tag.

3.2 Functions in jQuery


In jQuery, a Web developer can define a function in four different ways. It is also possible to define a
custom function.

3.2.1 Basic Declaration


This is the easiest way of declaring a function in jQuery. Code Snippet 2 shows the basic declaration
to define a function in jQuery.

Code Snippet 2:

function Multiply(varl, var2, var3)


{
return (varl * var2 * var3);
}
document.write("Basic Way:"+Multiply(10, 10, 8));
In Code Snippet 2, the Multiply function is defined to return the product of three numbers. This
way of declaring a function is useful for testing something quickly. It is not a good choice for
supporting code reuse.

3.2.2 Declaration as a Variable Name


A Web developer can define a function through an expression, which is assigned to a variable. After
storing the expression in a variable, this variable is then used as a function. Code Snippet 3 uses a
variable as a function.

Code Snippet 3:
var Multiply = function (varl, var2, var3)
{
return (varl * var2 * var3);
}

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

document.write("Function as Variable Name "+Multiply(10, 10, 8));


In Code Snippet 3, the code declares the variable Multiply and assigns an anonymous function to
it. This function returns the product of three numbers. In the write () method, the variable itself is
used as a function to return the product.

3.2.3 Self-invoking Function Declaration

Apart from assigning an anonymous function to a variable, a Web developer can pass it directly to a
method. This argument acts as a self-invoking function, which is typically an expression that the
script automatically invokes without being called. It has no name and is impossible to call it explicitly.

To declare such a function expression, a Web developer should add parentheses around the
function. Code Snippet 4 defines a self-invoking function.

Code Snippet 4:
(function () {document.write("Self Invoking Function, Hello! I
called myself") ;})();
In Code Snippet 4, the self-invoking function is within parentheses and calls itself on its own. The
string is the output that is displayed in the browser.

3.2.4 User-defined Function Declaration

Web developers can create their own jQuery functions, which are known as user-defined functions.
The j Query. fn or $ . fn object allows creating a user-defined function. It is equal to
j Query.prototype. Code Snippet 5 creates a user-defined function.
Code Snippet 5:
$ (document) .ready(function() {
$ .fn .myFunction = function (){
alert('You have successfully defined the function!');
}
$ (".call-btn") .click(function(){
$ .fn .myFunction () ;
}) ;
});
In Code Snippet 5, $ . fn object allows creating a user-defined function, myFunction, which shows
an alert message. It makes the function available for all objects of jQuery. This is evident when the
click property of the button whose class attribute is set to call-btn which is used to invoke the
newly created function.

Figure 3.2 shows a code that defines four functions, each with a different declaration method.

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

1 < ! DOCTYPE html>


2 R<html>
3 0<head>
4 <script src=Mhttps :// ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js,l></script>
5 0<script>
6 //Basic Way
function Multiply(varl, var2, var3)
8 0{
9 return (varl * var2 * var3);
10 }
11 document.write("Basic Way: "+Multiply(10, 10, S));
12 document.write ("<br>") ;
13 //Function as Variable
14 var Multiply * function (varl, var2, var3)
15 0{
16 return (varl * var2 * var3);
17 }
18 document.write("Function as Variable Name ”+Multiply(10, 10, 8));
19 document.write("<br>");
20 //Self Invoicing Function
21 0 (function () {
22 document.write("Self Invoking Function, Hello! I called myself");
23 })<>;
24 //Creating own functions
25 I$(document).ready(function(){
26 0 $.fn.myFunction = function(){
27 alert('You have successfully defined the function!');
28
29 0 $(”.call-btn").click(functian(){
$.fn.myFunction();
31 });
32 });
33 -</script>
34 -</head>
35 0<body>
36 <div id="divl"><h2>Fluntions in jQuery</h2></div>
cbutton type»"button" clas3»"call-btn">Click Me</ button>
38 -</body>
39 L</html>

Figure 3.2: Code for Declaring Functions in Different Ways

In figure 3.2, the code specifies the Google CDN reference. In the <script> tag, the code is
executed to invoke the Multiply function, which is written in the basic as well as in the variable
forms. The jQuery library invokes and executes the self-invoking function without writing any code
for doing the same. Finally, when a user clicks the Click Me button, its click property invokes
the user-defined function, myFunction and displays an alert box.

Figure 3.3 shows the output.

4 0 ( § ) [ a C:\Apps\8S.htmT P - Ci (Hi C:\Apps\BS.html

Basic Way:800
Function as Variable Name 800
Self Invoking Function, Hello! I called myself
Message from webpage
Funtions in jQuery
Click Me

Figure 3.3: Output of Code for Declaring Functions in Different Ways

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

3.3 Selectors in jQuery


The jQuery library allows using CSS and its own custom selectors for swiftly accessing and
manipulating the HTML elements in the DOM. A jQuery Selector refers to a function in the form of
an expression for searching the matching element in the DOM. In other words, selectors allow
selecting single or multiple HTML elements for triggering different actions on the selected ones. All
selectors begin with the jQuery identifier ($), which is followed by parentheses. The library allows
accessing the elements by:

• ID
• Class name
• Tag name
• Attribute
• Attribute values
• Other selectors
3.3.1 ID Selector

ID selector refers to the id attribute of a tag for searching the corresponding element. As the ID of
each element is unique, the selector is useful only forfinding a single tag at a time. It works by
relying on the document. getElementByld () function.

To find a tag or an element through its ID, a Web developer needs to specify ID selector, by
beginning it with the hash (#) character and following it by the id value of the element.

Syntax
$ (‘#<id>’)

where,

id: Is the value of id attribute of the required HTML element.

Figure 3.4 shows how to use an ID selector in jQuery.


1 <!DOCTYPE html>
2 <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
3 0<head>
4 <meta charset="utf-8" />
5 <titlex/title>
<script src="htto://aiax.aspnetcdn.com/aiax/iOuerv/iauerv-2.1.3.min.is,,x/script>
7 B <script type="text/javascript">
o E) S(document).ready(function () {
9 E $( ’#buttonl’).click(function () {
10 alert(’jQuery Selector’);
ill : »;
12 »;
131 </script>
14 </head>
15 <body>
161 <input id="buttonl" type="button” value="Click Me" />
17 </body>
18 </html>

Figure 3.4: Code for Using an ID Selector

V1.0 © APTECH LIMITED


Developing Responsive Websites with Bootstrap and jQuery

In figure 3.4, the click event is associated with the Click Me button whose id is button 1.
When a user clicks this button, the event is raised to execute an anonymous function that displays
the specified alert message.
Figure 3.5 shows the output.

Click Me
Message from webpage

Figure 3.5: Output of Code Using an ID Selector


Following are some points to remember about ID selector:

• It is the most efficient of all selectors.


• It accesses only the first element, in case of two or more tags with the same ID.
• It is not the same as document. getElementBy Id ( ) , as the latter returns a DOM object
and the former returns a jQuery object that includes the DOM object and provides different
methods. Therefore, a Web developer can invoke jQuery methods such as click () on the
returned object. To refer to the underlying DOM object using a jQuery object, a Web developer
should use, $ ( ' #btnidentifier') [0].
• It is slower in execution than document.getElementBy Id ( ). Still, it is in use for
harnessing the power of the extra functionality or methods of a jQuery object.
• It does not throw an error unlike document.getElementBy Id ( ) , which raises an error if
the element is not found. The length property of ID selector allows checking whether an
element was found and returned or not.
3.3.2 The Class Selector
The class selector looks for HTML elements that have the specified class. It works by using the
getElementsByClassName () native function. However, the user's browser should support this
function. To find a tag or an element through its class, a Web developer needs to specify the class
selector by beginning it with the dot (.) character and following it by the class name of the
element.
Syntax
$(‘.<class>’)
where,

class: Is the value of class attribute of the required HTML element.


Code Snippet 6 shows some examples of class selectors.

V1.0© APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

Code Snippet 6:
$(’.small') // Selects all elements with class small
$( .small,.big') // Selects all elements with class small or big
Figure 3.6 shows how to use a class selector in jQuery.

ll <!DOCTYPE html>
2 <html lane="en" xmlns=”httD://www.w3.org/1999/xhtml">
3 B<head>
4 <meta charset="utf-8" />
5 <titlex/title>
6 < s c r i D t s r c = " h t t D : //aiax.a s D n e t c d n .com/aiax/iOuerv/iauerv-2.1 .3.min.i s " x / s c r i D t >
7 B ' <script type="text/javascript”>
8 B $(document).ready(function () {
9 $('.small').css('border', '5px solid green');
10 });
11 </script>
12 </head>
13 <body>
14 S<span class="small">
15 Span 1
16 </span>
17 <br / x b r />
18 B <div class=”sraall”>
19 Div 1
20 </div>
21 <br />
22 B <span class="big">
23 Span 2
24 </span>
25 B <div class=”smaller">
26 Div 2
27 </div>
28 </html>

Figure 3.6: Code Using a Class Selector in jQuery

In figure 3.6, jQuery fetches all the elements whose class name is small. Then, it changes their
style to apply a green border, which is 5-pixel thick by invoking the jQuery object's css () method.
Figure 3.7 shows the output.

piTT

Spas 2
Div2

Figure 3.7: Output of Code Using a Class Selector

3.3.3 The Element Selector

The element selector access elements as per their name. To find an element by its name, a Web
developer needs to specify the element selector within the parentheses following the $ character.

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

Syntax
$(<element>)
where,

element: Is the name of the element.


Code Snippet 7 shows some examples of element selectors.
Code Snippet 7:
$('td') // Selects all <td> elements
$(’div a') // Selects all anchor elements that are inside the div
element
Figure 3.8 shows the code for using an element selector.

<!DOCTYPE html>
2 <html lang="en” xmlns="http://www.w3.org/1999/xhtml">
3 B<head>
4 <meta charset="utf-8" />
S <-ti-tle></ti-tle>
6 <scriot src="http://aiax. aspnetcdn.com/aiax/iOuerv/iquerv-2.1. 3.min. -is”x/script>
7 - <script type="text/javascript">
8 ^(document).ready(function () {
9 alert($(’td').length);
10 });
11 </script>
12 </head>
13 E<body>
14 B <table style="border:lpx solid black; border-collapse:collapse”>
15 <tr>
16 <td>India</td>
17 <td>Germany</td>
18 <td>France</td>
19 </tr>
20 <tr>
21 <td>Europe</td>
22 <td>Asia</td>
23 <td>Australia</td>
24 </tr>
25 </table>
26 </body>
27 </html>

Figure 3.8: Code for Using an Element Selector

In figure 3.8, the jQuery code displays the total number of <td> elements by triggering an alert box.
To find the total number of <td> tags, it uses the length property of the element selector,
$(‘td ’).
Figure 3.9 shows the output, which returns the count as 6.

i C :\ A p p s \ j q S e l e c t o r .h t m l

India Germany F rance


Europe Asia____ Australia

Figure 3.9: Output of Code for Using an Element Selector

V1.0© APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

3.3.4 The Checked Selector

The checked selector accesses and selects all selected radio buttons and check boxes. To access
these input controls, a Web developer needs to include: checked inside double quotes, which
should be within the parentheses following the $ character.

Syntax
$(":checked")
Code Snippet 8 shows how to access all radio buttons at once that a user has selected.

Code Snippet 8:
$('input[type="radio"]:checked')
Figure 3.10 shows how to use the checked selector.

1 <!DOCTYPE html>
2 <html lane="en" xmlns="httD://www.w3.ore/1999/xhtml">
3 B<head>
*1 <meta charset=''utf-8" />
5 <scriot src="htto://aiax.asonetcdn.com/aiax/iOuerv/iauerv-2.1 .3 .min.■is"x/scriDt>
6 B <script type="text/javascript">
7 B $(document).ready(furtction () {
8 $('#btnSubmit').click(function () {
9 var result = $('input[type="checkbox"] ichecked');
10 E if (result.length > 0) {
11 var resultString = result.length + ” checkboxe(s) checked<br/>”;
12 E result.each(function () {
13 resultString += $(this).val() + "<br/>”j
14 });
15 $('#divResult').html(resultString);
16 >
17 B else {
18 $('#divResult').html("No checkbox checked”);
19 >
20 »;
21 »;
22 </script>
23 </head>
24 B<body>
25 B Countries :
26 <input type="checkbox" name=”skills" value=”India" />India
27 Cinput type="checkbox" name=”skills" value=''Germany” />Germany
28 <input type="checkbox" name=”skills” value="Croatia"/>Croatia
29 Cinput type="checkbox” narae=”skills" value="Russia" />Russia
30 <br / x b r />
31 cinput id="btnSubmit’' type="submit" value=''subrait'’ />
32 <br / X b r />
33 <div id=”divResult">
34 </div>
35 </body>
</html>

Figure 3.10: Code for Using the Checked Selector

In figure 3.10, the jQuery code uses the checked selector to find out the number of selected check­
boxes and stores it in the result variable. This variable then is recognized as the returned
jQuery object. The object's length property helps in checking whether the user has selected any
check boxes or not. If yes, the code under the if statement is executed, which stores the total
count of selected check boxes in the resultStr ing variable.

Next, the each () method of result object is used to refer to each selected check box for
fetching the value of the corresponding value attribute.

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

After identifying the total count along with the check box names, ID selector is used to display the
result by invoking its html () method. ID selector is referring to the <div> tag with the id,
divResult. This whole process of finding the total count and check box names is triggered as soon
as a user clicks the submit button.

Figure 3.11 shows the output.

Skills: □ India 0 Germany □ Croatia □ Russia

submit

1 checkboxe(s) checked
Germany

Figure 3.11: Output of Code Using the Checked Selector

3.4 JSON and Conversions to JSON


JSON refers to a lightweight format for exchanging and storing data. It is an easier alternative to
eExtensible Markup Language (XML) in terms of usage. This is because it is a self-describing format
due to which it is simple to comprehend the data exchanged between a server and a client
(browser).

Exchanging data between these two nodes happens only in text format. JSON is a simple text format
to use in this scenario, although it uses JS syntax. It also works independent of any programming
language.

A Web developer can convert an object into JSON and then send it to the server. It is also possible to
convert data obtained from the server into JSON objects and arrays. Both the processes are free
from complex parsing.

3.4.1 Creating a JSON Object

The format of JSON is almost similar to JS objects. So, it is written in the form of key/value or
name/value pairs. However, unlike in JS, the key or name in JSON is always a string due to which it
must be within double quotes. Further, in JS, strings can appear in single or double quotes.

In JSON, a name in double quotes is separated by the value with a colon.

Syntax
{"name"lvalue}
In a name/value pair, the value needs to a valid data type, which can be number, string, boolean,
array, null, or object. JSON do not support date data type. So, the only way to represent a date in
JSON is to make it a string. Code Snippet 9 shows some examples of name/value pairs in JSON.

Code Snippet 9:
{"city":"Moscow"}
{"age":40}
{"marriage":"1980-12-23"}

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

In Code Snippet 9, city is the key or name in double quotes and Moscow is its string value.
Similarly, age is the key, while 40 is its numeric value. For the marriage key, the value is a string
showing the wedding date. In jQuery, Web developers usually work with JSON objects. Code Snippet
10 shows how to store employee data in a JSON object, employeeJSON.

Code Snippet 10:


var employeeJSON =
{
"firstName": "Philips",
"lastName": "LG",
"gender": "Male",
"salary": 5000,
"bike": null
};
In Code Snippet 10, the employee data is included inside the curly braces. Further, comma separates
each name/value pair. There is no comma at the end of the last name/value pair.

Each name/value pair is referred to as a property. A Web developer can specify any number of
properties in a JSON object. Code Snippet 11 represents the same data using XML.

Code Snippet 11:


<Employee>
<firstName>Philips</firstName>
<lastName>LG</lastName>
<gender>Male</gender>
<salary>5000</salary>
<bike>null</bike>
</Employee>
From Code Snippet 11, it is clear that the JSON format is simpler than XML.

3.4.2 Accessing Data from a JSON Object

The dot (.) notation and the corresponding property name enable accessing data from a JSON object.

Syntax
<0bj ect>.<propertyName>;
Code Snippet 12 shows how to fetch the first name of the employee from the employeeJSON
object created in Code Snippet 10.

Code Snippet 12:


var firstName = employeeJSON.firstName;
Figure 3.12 shows the code for accessing all data from the employeeJSON object using jQuery.

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

1 <!DOCTYPE html>
2 <html lang="en" xmlns= 'http: //www. w3 .orp/1999/xhtml">
3 - <head>
4| <meta charset="utf-8” />
5 <script src="http://aiax.aspnetcdn.com/aiax/jOuerv/jquerv-2.1.3.min.js"x/script>
6 <script type="text/javascript">
7 $(document).ready(function () {
8
9 // Creating a 3S0N object
10 0 var employeeJSON = {
11 "firstName”: "Philips”,
12 "lastName": "LG",
13 "gender": "Male",
14 "salary” : 5000
15 >;
16
17 // Accessing data from a 3SON object
18 var result = "j
19 result += 'First Name = + employeeJSON.firstName + ’ <br/>*
20 result += ’Last Name = + employeeDSON.lastName + ’<br/>’ ;
21 result += ‘Gender » + employeeJSON.gender + ' <br/>’ ;
22 result += ’Salary = + employeeJSON.salary + ’<br/>’ ;
23
24 $(’#resultDiv’).html(result);
25 »;
26 </script>
27 </head>
28 B<body style="font-family:Arial">
29 <div id="resultDiv"x/div>
30 </body>
31 </html>

Figure 3.12: Code for Fetching Data from a JSON Object

In figure 3.12, the code inside the anonymous function creates the required JSON object as soon as
the document is loaded. It then declares a variable named result for accessing the data from the
object. The variable is set to a concatenated string, which uses the individual property name of the
JSON object for fetching all its data. The result is a JSON string that is displayed through the <div>

Figure 3.13 shows the output.

First Name = Philips


Last Name = LG
Gender = Male
Salary = 5000

Figure 3.13: Output of Code for Fetching Data from a JSON Object

3.4.3 Using JSON Arrays

Let's imagine a scenario wherein a Web developer needs to store the data of more than one
employee in a JSON object. This is where a JSON array is useful. A JSON array can hold several
objects. To create a JSON array, include the objects in square brackets and separate each by a
comma. Code Snippet 13 shows how to create a JSON array indicating the colors in a rainbow.

Code Snippet 13:


f "Red", "Blue", "Green", "Yellow", "Violet”, "Indigo", "Orange" ]
A JSON array is almost similar to a JS array. However, its values or elements can be number, string,
boolean, array, null, or object. It cannot be a valid expression, unlike in JS. Code Snippet 14 shows
how to create a JSON object holding the data of two employees.

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

Code Snippet 14:


var employeesJSON = [
{
"firstName": "Philips",
"lastName": "LG",
"gender": "Male",
"salary": 5000
},
{
"firstName": "Samsung",
"lastName": "Sam",
"gender": "Female",
"salary": 4000
}];
In Code Snippet 14, both elements in the array are employee objects. To access these from the JSON
array, employeeJSON; a Web developer should use the object's index position. Code Snippet 15
shows how to retrieve the last name from both the objects of employeesJSON array.

Code Snippet 15:


var result = employeesJSON[0].lastName;
var result = employeesJSON[1].lastName;
3.4.4 Converting an Object or Array into a JSON String

When sending data to a server, it should be in the string format. So, for converting a JS object into a
string, a Web developer should use JSON . stringify () . This method is used on both arrays and
objects.

Figure 3.14 shows how to convert the employeesJSON array into a JSON string using
JSON .stringify ().
1 <!DOCTYPE html>
2 <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
3 0<head>
*1 <meta charset="utf-8" />
5 < script src=”http ://aiax.aspnetcdn. com/a-jax/-iOuerv/iquerv-2 .1. 3 .min .-js" ></script>
6 0 <script type«"text/javascript">
7 $(document).ready(function () {
8 var employeesJSON = [
9 E) {
10 "firstName": "Philips”,
11 "lastName” : "LG"*,
12 "gender": "Male",
13 "salary": 5000
14
15 {
16 "firstName": "Samsung",
17 "lastName": "Sam",
IS "gender": "Female",
19 "salary” : 4000
20 >
21 ];
22
23 var DSONString - 3SON.stringify(employees3SON);
24 $ ( '#resultDiv').html(DSONString);
25 »;
26 </script>
27 </head>
28 E<body style*"font-family:Arial">
29 <div id="resultDiv"></div>
30 </body>
31 </html>

Figure 3.14: Code for Converting an Array into a JSON String


Developing Responsive W ebsites with Bootstrap and jQuery

In figure 3.14, JSON .stringify () takes the array as an input and converts it into a string in
JSON notation. This string is stored in JSONString variable and is displayed on the Webpage
through the <div> tag. This string is now ready to be sent to the server.
Figure 3.15 shows the output.

[{"firstName":"Philips","lastName":"LG","gender":"Male"i"salary":5000},{"firstName":',Samsung"1”lastName":"Sam","gender'':"Female","salary":4000}]

Figure 3.15: Output of Code Converting an Array into a JSON String

3.4.5 Converting a String into a JSON Object or Array

A Web developer can parse a string using JSON .parse () to convert it into a JSON object or an
array. To avoid a syntax error, the string should be in JSON format.

Figure 3.16 shows how to convert a string into a JSON array using JSON .parse ().
1 <!DOCTYPE html>
2 <html lane="en" xmlns=''htto://wwK.w3.orp/1999/xhtml">
3 E;<head>
4 <meta charset="utf-8" />
5 <scriDt src="httD://aiax.asonetcdn.com/aiax/i0uerv/iauerv-2.1.3.min.is"x/scriDt>
6 B <script type="text/javascript">
7 E $(document).ready(function () {
8 var JSONString = '[{ "firstName": "Philips”, "lastName”: "LG”, "gender": "Hale", "salary": 5000 },
9 { "firstName": "Samsung”, "lastName”: "Sam”, "gender”: "Female", "salary": 4006 }]’;
10
11 var employees3SON = 3SON.parse(3SONString);
12
13 var result = ";
14
15 E) $.each(employees3S0N, function (i, item) {
16 result += 'First Name = ' + item.firstName + '<br/>';
17 result += 'Last Name = ’ + item.lastName + '<br/>'j
18 result += 'Gender = ' + item.gender + '<br/>';
19 result += 'Salary = ' + item.salary + ’<br/Xbr/>';
20 });
21
22 $('SresultDiv').html(result);
23 });
24 </script>
25 </head>
26 B<body style=''font-faniily:Arial”>
27 Li <div id="resultDiv"x/div>
28 </body>
29 </html>

Figure 3.16: Code for Converting a String into a JSON Array

In figure 3.16, a string variable, JSONString is set to a string in JSON syntax. The
JSON .parse () function takes this string as a parameter and converts it into a JSON array,
employeesJSON. Then, the each () method of jQuery allows looping through each employee
element or object in the array to retrieve its corresponding property values.
Figure 3.17 shows the output.

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

First Name = Todd


Last Name = Grover
Gender = Male
Salary = 50000

First Name = Sara


Last Name = Baker
Gender = Female
Salary = 40000

Figure 3.17: Output of Code Converting a String into a JSON Array

3.5 Event Delegation in jQuery


jQuery is customized for reacting to events occuring on a Webpage. An event denotes the exact
moment when an action from a user occurs. A few examples of events include loading a Webpage,
clicking an element, selecting a check box, and hovering the mouse over an element.

With events, Web developers can design dynamic Webpages. When an event is raised, an event
listener, which is associated with source of event, listens to it and notifies the handler. An event
handler, which is associated with the event, is usually a custom function that conveys what to do for
handling the event.

In jQuery, event delegation enables a Web developer to assign a single listener to a parent element,
which will listen for all descendants corresponding to a selector.

This is irrespective of whether these descendants are present now or are included later. The
descendants of an element encompasses all its children elements including the great grand-child
ones.

The on () and delegate () methods facilitate delegating an event in jQuery. Delegating an event
eliminates the need to add event listeners to particular tags. This is because a Web developer can
now add a listener to a parent element, which can analyze the bubbled events to look for a match on
child elements.

For example, let's assume that there is a parent <ul> element with 50 child elements. Something
should happen when a user clicks any child element. For this, a Web developer may add a distinct
event listener to each <li> element. However, a problem arises when the developer frequently
tends to add and remove these child elements. In this case, adding and removing the listeners would
be a tedious job and may lead to performance issues. So, it would be much better to add a listener
to the parent element.
However, an important question here is that how would the developer find out which child element
was clicked? The solution here is to use the target property of the event object to obtain a
reference to the clicked node while the event bubbles up to the parent element.

When the click event triggers on any child element of the <UL>, it also triggers on all ancestors of
that element. This is called event bubbling in which an event bubbles upwards from the source
element in the DOM tree. As a result, it activates each of its parent click handlers, which includes
<ul>, <div>, <p>, <body>, <html>, and root. In other words, clicking an <li> tag indicates
clicking the whole body of the document.

V1.0© APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

Event bubbling and t a r g e t property are the main features of event delegation in jQuery. They
boost performance when there are hundreds of child elements on which a specific event should be
listened and handled.

The t a r g e t property of any event refers to the element that originated the event. Through event
delegation, a Web developer can add a handler to an element, wait for event bubbling, and quickly
identify the event's source, which is the element where the event occurred. Following are the
benefits of event delegation:

• Less handlers to take up memory


• Better performance
• Reduced risk of crashing
• No re-assigning the handlers if the child elements keep changing

Figure 3.18 shows how to delegate and undelegate a click event for an unordered list using the
o n () method of jQuery.

1 <!DOCTYPE html>
2 <html lang="en" xmlns="http:/Aswv.w3.org/1999/xhtml">
3 B<head>
4 <meta charset="utf-8" />
5 <script src="http://aiax. aspnetcdn.com/aiax/~i0uerv/iauerv-2.1.3 -min.~is"></script>
6 3 <script type="text/javascript’’>
7 El $(document).ready(function () {
s H
$(’ul’).on(‘click’, ’li‘, function () {
9 $(this).fadeOut(500);
10 »
11
12 B $( #btnAdd‘).on(‘click’, function () {
13 $(‘ul‘).append(‘<li>New List Item</li>‘);
14 »
15
16 B s< # b t n l l n d e l e g a t e ’) . o n ( ‘c l i c k ’, f u n c t i o n () {
17 $ ( ‘u l ‘) . o f f ( ‘c l i c k ’, ’l i ’);
18 »;
19 »;
20 </script>
21 </head>
22 B <body style="font-family:Arial”>
23 <input id="btnAdd" type="button" value="Add a Hew List Item” />
24 <input id="btnUndelegate" type="button" value=’’Undelegate" />
25 B <ul>
26 <li>List Iteml</li>
27 <li>List Item2</li>
28 </ul>
29 </body>
30 </html>
?•
Figure 3.18: Code for Delegating and Undelegating an Event

In figure 3.18:

• Clicking any < l i > tag triggers event bubbling in which the click event bubbles up to its
parent element, < u l> . This is because there is no dedicated event handler attached to the
clicked list item. The parent element handles the bubbled event, as it has the click event
handler. The o n ( ) method of the jQuery object directly binds the c l i c k event to the
< u l> tag and the anonymous function acts as an event handler. It takes three parameters
namely, the event, selector parameter, and the anonymous function.

Vl.O© APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

• The selector parameter informs the handler to listen to the click event. It also tells the
handler to check whether the element triggering the click event matches with the selector
parameter at the time of hearing. In this case, the source of the event is <li>, which
matches with the second parameter. Thus, the anonymous function executes to fade out the
clicked <li> element in 3000 milliseconds.
• When a user clicks the button whose id is btnAdd for dynamically adding a new list item,
the item is added to <ul> using the append () method. There is no need to specify the
button's click event handler explicitly in the <input> tag. As the new item is added to the
same parent element <ul>, the click event of the list item also gets bubbled to the same
parent.
• Upon clicking the Undelegate button, the undelegate () method of the <ul>
element selector is invoked to stop event delegation.

Figure 3.19 shows the output.

Add a New List Item Undelegate

List Item l
List Item2
New List Item

Figure 3.19: Output of Code Delegating and Undelegating an Event

Quick Test 3.1

1. The checked selector allows finding which radio buttons are selected.
a. True
b. False

2. It is impossible to call a self-invoking function explicitly.


a. True
b. False
Developing Responsive W ebsites with Bootstrap and jQuery

> jQuery is a lightweight, open-source JS library that makes JS programming easier and more
efficient.

> jQuery uses unobtrusive JS, offers a variety of reusable functions, is extensible, and is compatible
with modern browsers.

> Web developers can either download the jQuery file or include it by referring to a CDN for using
jQuery in their Web applications.

>- The customized syntax of jQuery is $ ( selector) . act ion ().


>■ There are four ways of declaring a function in jQuery, which are basic, as a variable, self-invoking,
and user-defined.
>• A jQuery Selector refers to a function in the form of an expression for searching the matching
element in the DOM.

> The jQuery library allows selecting the HTML elements by ID, class name, tag name, attribute, and
attributed values.
>- JSON is a lightweight format for exchanging and storing data as well as an easier alternative to XML.
>- Unlike in JS, the key or name in JSON is always a string.
> Each name/value pair in JSON format is referred to as a property.
>• A JSON object is a collection of properties, each separated by a colon.
>- The JSO N . s t r i n g i f y () method converts a JSON object into a JSON string.
>- The JSO N . p a r s e () method converts a JSON string into a JSON object or array.
>■ Event delegation allows assining a single listener to a parent element, which will listen for all
descendants corresponding to a selector.
>• The on () and d e le g a t e () methods facilitate delegating an event in jQuery.
>■ Event bubbling in which an event bubbles upwards from the source element in the DOM tree.
>■ Event bubbling and t a r g e t property are the main features of event delegation.
Developing Responsive Websites with Bootstrap and jQuery

1. Which of the following statements about jQuery is true?


a. It has a small but vib ran t com m unity
b. It uses obtrusive JS
c. It supports AJAX
d. None o f these
2. __________ is a valid jQuery selector.
a . $ (t h is )
b. $ (p )
c . $ (* )
d . $ (# b tn )
3. Th e___________ object allows declaring a user-defined function.
a. .fn
b . $ .f n
c . Jq u e ry .p ro to ty p e
d . $ .f n .p ro to ty p e
4. Which of the following methods converts an object into a JSON string?
a . J S O N . s t r i n g ()
b . J S O N . c o n v e r t o s t r i n g ()
c . J S O N . s t r i n g i f y ()
d . J S O N . t o s t r i n g ()
5. Which of the following statements about event delegation is true?
a. It features event bubbling
b. It assigns an event handler to a parent elem ent
c. It boosts perform ance
d. All o f these
Developing Responsive Websites with Bootstrap and jQuery

Answers to Check Your Progress


1. It supports AJAX
2. $ (this)
3. $ . fn
4. JSON .stringify ()
5. All of these

Answers to Quick Test


Quick Test 3.1

1. True
2. True
Developing Responsive W ebsites with Bootstrap and jQuery

SESSION 4 - Functions, Widgets,


VjPlugins in jQuery____________
Session Objectives:
This session introduces the built-in methods in jQuery and elaborates briefly on the l±ve()
method for event delegation. It also describes the different Asynchronous JavaScript and XML (AJAX)
methods that jQuery supports and the callback concept. The session also briefly introduces the
jQuery Ul JavaScript (JS) library, its different widgets including autocomplete, and the datatable
dynamic control.

At the end of this session, you will be able to:

> Describe various types of functions in jQuery


> Explain use of AJAX in jQuery
> Elucidate the callback concept in jQuery
> Describe implementation and use of various controls such as widgets and datatables in
jQuery

4.1 Built-in Methods in jQuery


The jQuery framework features different capabilities of JavaScript (JS). As JS has a handy set of built-
in functions, all of them are also available through this framework. This is one of the examples
proving that functions are reusable blocks. The JS built-in functions are methods with which Web
developers can quickly manipulate data values such as dates, numbers, and strings.

Table 4.1 shows some of the built-in jQuery methods.

Method Description
tim ki tu theo charAt () Fetches the character at the mentioned index.
vi tri concat () Returns a new string by combining two strings.
Fetches the index inside the requesting string object of the initial
tim vi tri indexOf () occurrence of the mentioned value. If nothing is found, it returns
-1 .
length () Returns the number of characters in a string.
forEach () Invokes a function for each array element.
pop() Removes and returns the last array element.
Appends single or multiple elements at the end of an array and
push ()
fetches its modified length.
Extracts the string characters starting at the mentioned index
substr ()
location until the specified index length.
Changes the order of array elements by making the first one last
reverse ()
and the last one first.
sort () Arranges the array elements in an ascending or descending order.
toLowerCase () Converts a string value into lower case.
toUpperCase () Converts a string value into upper case.
tostrlng () Converts a given value into a string.
Table 4.1: Built-in Methods in jQuery

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

Figure 4.1 shows the code using some of the built-in methods.
1 <! DOCTYPE html>
2 F3<html>
3 []<head>
4 <script src»"https ://aiax .cioocrleapis .com/aiax/libs/iquerv/3 .2 .0/iquerv.min.is”X / s c r i p t >
5 E]<script>
6 [ ]function myFunction() {
7 var scr = "HELLO KCRLD";
S var res = str.charAt(0)
9 document.write("charAT Function:” ♦" " ♦ res);
10 document .write ("<br>") ;
11 var strl = ” FOLKS"
12 document,write ("concat Function:” + str.concat (strl));
13 document.write("<br>”);
14 document.write("Index Of Function:" ♦" "+ str.indexOf("WORLD"));
15 document.write("<k>r>") ;
16 document,write ("Length of string:" +" '*+ str.length) ;
17 document.write("<br>");
18 document.write("Converting to Lower case:” + ” "+ str.toLowerCase());
19 }
20 -</script>
21 -</head>
22 E]<body>
23
24 <p>Click here to execute builtin functions in jQuery.</p>
25
26 <button onclick="myFunction()">Click me</button>
27
28 -</body>
29 -</html>

Figure 4.1: Code Using Built-in Methods

In figure 4.1, the code uses different built-in functions of jQuery for manipulating two strings. The
charAt () built-in function returns the character at 0thposition in the string, which is precisely the
first character. The concat () function adds two strings namely, str and strl. The indexOf ()
function retrieves the index position from where the string WORLD starts in the string, str. The
length () function retrieves the total number of letters in the str string. Finally, the
toLowerCase () function converts the upper case letters in the string to lower case.
Figure 4.2 shows the output.

charAT Function: H
concat Function: HELLO WORLD FOLKS
Index O f Function: 6
Length of string: 11
Converting to Lower case: hello world

Figure 4.2: Output of Code Using Built-in Methods

4.1.1 Live Function in JQuery

The built-in live () method delegates single or multiple event handlers for all elements that match
with the selector and defines a function to run once the event occur. Event handlers attached in this
manner work for both existing and upcoming elements that match the selector. The live()
method is just another way to perform event delegation in jQuery.

V1.0© APTECH LIMITED


Developing Responsive Websites with Bootstrap and jQuery

The on() and delegate () methods facilitate bubbling up the event to the source's parent
element. On the other hand, the live() method bubbles up to the document object. A Web
developer can remove the associated event handler using the die () method.

Syntax
$ (selector).live(event,data,function);
where,

• event: Refers to single or multiple events to delegate to the elements, with multiple event
values parted by space.
• data: Is optional and represents extra data to be passed to the function.
• function: Indicates the function to execute once the event takes place.
In the latest version of jQuery, the
on () method takes care of all event Note: jQuery recommends using on () and
delegation tasks. It can handle all tasks
off() methods instead of live () and die ()
of the live () method.
methods to the users of latest version of jQuery.

Figure 4.3 shows the code for using live ( ) ,on ( ) , and die () methods.
< 1BOCTYPE htal>
]< h tsa i>
]<head>
3<acript s r c * " E■ ■7 /l q u c r y .f n i n .i » ">
< /a c r i p t >
]< s c rip t typ e- "t e x t /j a v a s c r i p t ” >
* (document).ready(function () (
t l 'l i ’ J.live(’ click', function () (
3 alert( .. ?
10

12
13 * C n c r - A d i ’) . © a ( ' c f u n c t i o n () {
»(' ) .a«>end( ):
is )>:

tl' • - • r.U n d e le ga :;- ) . o n ( 'c : i c i : - , f u n c t io n () (
i (• . ) . d l e ( 'c l : :« ) ;
)>:
I);
21 < /s c r i p t >
22 -< /h e«d >
□ <body s ty le - "fo n t - fa m ily : A r i a l '•>
<inp ut id-"bti\Add" type- "bu tton ” value-'-Add a Mew L i s t Jtejn" />
<ir.put id - "b tn U n d e le g a te " t ype- "button" value-"U n d e le g a t e " />
0 < u l>
< li> L i*t It e m < /li>
< li> L is t It c m < /li>
[ < /u l>
• </body>

-</html>

Figure 4.3: Code Using l i v e ( ) , o n ( ) , and d i e ( ) Built-in Methods

In figure 4.3, the code refers to an older version of jQuery framework to demonstrate the use of
liveQ method. The live () a n d o n Q methods attach the event handler to all <li> elements

V 1.0© APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

and btnAdd button, respectively. Both of them take the event and an anonymous function as
parameters. When a user clicks any list item, the live () method executes the function and
displays the alert box. When a user clicks the button, the on () method runs the function to add a
new list item to the existing unordered list. Clicking the btnUndelegate button invokes the on ()
method, which then calls the die () method to stop event delegation.
Figure 4.4 shows the output.

§ C:\Users\dbollojx\Desktop\functions.html

Add a New List Item Undelegate


Message from webpage
List Item
List Item
New List Item
New List Item

Figure 4.4: Output of Code Using liv e ( ) , o n (), and d ie ( ) Built-in Methods
4.2 jQuery AJAX
AJAX allows updating different parts of a Webpage by exchanging data with the Web server.
However, it does so without reloading or refreshing the whole Webpage. Some examples of AJAX
Websites are Gmail and YouTube.
Coding regular AJAX without jQuery can be a bit complicated, as its syntax for implementation tends
to vary from one browser to another. This means a Web developer need to write additional code for
testing their Webpages on each of the major browsers.

However, with jQuery, this extra effort is no longer required, as the makers have already coded for
it. Web developers can now code implement an AJAX functionality in just one or two lines. So, in
jQuery, it is easier to write AJAX code.

jQuery provides many AJAX methods for developing Web applications. Through the jQuery AJAX
methods, Web developers can request data from a distant Web server via GET and POST. They can
request data in any of the four different formats namely, text, JavaScript Object Notation (JSON),
extensible Markup Language (XML), and HTML. Further, they can easily load the remote data quickly
into desired HTML elements.

4.2.1 AJAX jQ uery Load() Method

The jQuery load () method is an easy and robust AJAX functionality. As the name suggests, it loads
the requested data from a Web server and inserts it into the desired HTML element.

Syntax
$ (selector).load(URL,data,callback);
where,

• URL: Indicates the Uniform Resource Locator (URL) of a resource on a server, a Web developer
intends to load.

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

• data: Is optional and indicates a set of key/value pairs as a query string in the form of JSON
object or string that goes along with the request. The default request method used here is GET.
• callback: Is optional and indicates the name of a callback function that will run after the
load () method completes executing the request.
Figure 4.5 shows how to fetch data from an HTML file on a server and load it in the body of a <div>
element.
<!DOCTYPE html>
2 F]<html>
3 R<head>
4 <script src="https://aiax.googleapis■com/aiax/libs/icmerv/3.1 .l/iouerv.min.is"X/scriPt>
5 H<script>
6 H $ (document) .ready (function () {
7 h $ ("button”).click(function(){
$("#divl").load("test.txt");
9 >);
10 -));
11 -</script>
12 -</head>
13 (i]<body>
14
15 <d±v id="divl"><h2>Ajax load demo</h2></div>
16
17 <buttor.>Get test file Content</button>
18
19 </body>
20 </html>

Figure 4.5: Code Using the load() Built-in Method

In figure 4.5, once the document is ready for manipulation and when a user clicks the button, the
click event is raised and the load () method triggers. The method triggers an AJAX request to the
URL.

The load () method takes the URL as the parameter and fetches its contents. Here, the text file is
in the same folder as this HTML file. The method finally loads the fetched content in the body of
<div> by assigning the content to it through the id selector.
Figure 4.6 shows the output.

Ajax load demo


Get test file Content

T his is text from text file

Figure 4.6: Output of Code Using the load () Built-in Method

4.3 Callbacks in jQuery


A callback function runs once the current jQuery effect such as hide, fade, or slide, is over. Usually, in
JS, execution occurs line by line. Nevertheless, when there is an effect to display, the next code line
can execute even if the former is not over. This can lead to errors. To keep this risk away, a Web
developer defines a callback function.

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

Syntax for Hide Effect


$ (selector).hide(speed,callback);
where,

• speed: Is optional and indicates the speed of hiding an element in milliseconds or as fast or
slow.
• callback: Is optional and indicates the name of a callback function to run after hide()
executes completely.

Figure 4.7 shows the code for hiding a paragraph without using a callback function.
1 < !DOCTYPE html>
2 <html>
3 0<head>
4 ocript src="https://aiax.qooaleapis.com/aiax/libs/icmerv/3.1.1/icroerv.min.is"></3cript>
5 Fj<script>
6 (document) .ready (function () (
7 $ ("button").click(function(){
8 $ ( " p " ) .hide( 1 0 0 0 ) ;
9 alert("The sentence is now hidden");
10 )) ;
11 ));
12 -</script>
13 </head>
14 £)<body>
15
16 <button>Hide</button>
17
18 <p>This is a sentence with little content.</p>
19
20 -</body>
21 -</html>

Figure 4.7: Code Hiding an Element without a Callback Function

In figure 4.7, the code invokes the anonymous function once a user clicks the button. The function
executes to hide the sentence in the <p> element in 1000 milliseconds and show the alert dialog
box.

Figure 4.8 shows the output.

This is a sentence with little content Message from webpage

I The sentence is now hidden

OK

Figure 4.8: Output of Code Hiding an Element without a Callback Function

In figure 4.8, it is clear that the alert box is displayed without waiting for the hide effect to get over.
Now let's see what happens when a callback fucntion is present.

Figure 4.9 shows the code for hiding a paragraph using a callback function.

V1.0© APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

1 < !DOCTYPE html>


2 3<html>
3 3<head>
4 <script src="h t t p s ://aiax.qoocrleapis.com/aiax/libs/icraerv/3.1 .1/icmerv.min. -is"></script>
5 3<script>
6 0^)$ (document;) .ready (function () (
7 $ ("bu c c o n " ) .c l i c k (function(){
8 $ ("p").hide("slow", f u n c t i o n (){
9 alert("The sentence is now hidden");
10 >>;
11 )) ;
12 ->> ;
13 -</script>
14 -</head>
15 3<body>
16
17 <button>Hide</button>
18
19 <p>This is a sentence with little content.</p>
20
21 -</body>
22 -</html>

Figure 4.9: Code Hiding an Element with a Callback Function

In figure 4.9, the code invokes the anonymous function once a user clicks the button. The function
executes to hide the sentence in the <p> element slowly and then, invoke a callback function to
display the alert dialog box.

Figure 4.10 shows the output.

Message from webpage

The sentence is now hidden

OK

Figure 4.10: Output of Code Hiding an Element with a Callback Function

In figure 4.10, it is clear that the alert box is displayed only after the sentence in the paragraph hides,
completely. This means that the callback function is called only after the effect is completed.

In the load () method, the optional callback parameter indicates a callback function. This executes
only when the desired content loads into intended section of a Webpage. This callback function can
take three parameters.

Syntax
$ (selector).load(URL,data,function(response,status,XHR));
where,

• response: Holds the fetched content in case loading is successful.

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

• status: Has the status of the loading action.


Note: XHR has all contents of the browser's
• XHR: Possesses the XMLHttpRequest object
native XMLHttpRequest object.
with response text.

Code Snippet 1 shows how to pass a callback function as a parameter to the load () method.

Code Snippet 1:
$("btnLoad") .click(function() {
$("#divLoad").load("test.txt", function(response, status, xhr){
if(status == "success")
alert("Content loaded!");
if(status == "error")
alert("Error in loading: " + xhr.status);
});

In code snippet 1, the code displays the alert box once the load () method's execution is over. If
the method succeeds, it displays the corresponding alert message. Otherwise, it shows an error
message using the status property of XMLHttpRequest object.

4.3.1 jQuery $ . g e t ( ) Method

The $ . get () method asks data of a resource from a Web server through a GET request.
Syntax
$.get(URL,callback);
where,

• URL: Indicates the URL a Web developer intends to request.


• callback: Is optional and is a function to be executed when the request is successful.
Figure 4.11 shows how to use $ . get () method with a callback function to display the contents of
an ASP file into an HTML page.
< !DOCTYPE html>
0<html>
3<head>
O c r i p t src="https://aiax.crooqleapis.com/aiax/libs/icmerv/3.1 .1/icroerv.min.is"></script>
5<script>
-]$ (document) .ready (function () {
$ ("button").click(function(){
$ .get("demo_test.asp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
));
}) ;
->>;
-</script>
-</head>
£3<body>

<button>Get response from concerning asp page</button>


-</body>
-</html>

Figure 4.11: Code for Using $ . g e t ( ) with a Callback Function

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

In figure 4.11, the occurrence of click event invokes the $ . get () method, which fetches the data
from the ASP file at the specified URL. An ASP file is a server side script. The method takes two
parameters, of which the second one is the callback function. This function contains the requested
data and status of the request. Following is the content existing in the ASP file:
<%
response.write("Response from asp file")
%>
Response .write () works in the same way as document.write () in HTML. It shows the
message on the HTML page.

Figure 4.12 shows the output.

Get response item concerning html page


Message from webpage

Data: Response from asp file


Status: success

OK

Figure 4.12: Code for Using $ . get ( ) with a Callback Function

Web developers might think that the $ . get () and load () methods are same. However, there is
a difference between these two methods of jQuery. Table 4.2 distinguishes them.

Point of L o a d () $.get()
Distinction
Functionality Loads only HTML data after retrieving Loads any type of data, such as JSON and
it from the server. script.
Type of Sends a GET or POST request, but it Sends a GET request always.
HTTP depends on whether the specified data
Request parameter. If data parameter is
specified, POST is used. Otherwise, GET
is used.
Selector Follows a selector for inserting the Does not follow a selector while coding.
Usage retrieved content into the element that Instead, it invokes a callback function to
matches with the selector. For insert the retrieved data from the server
example: into an HTML element. For example:
$ ('selector') .load $.get('url’, 'data',
('url', 'data'); function (response)
{
$ ('selector') .html(response) ;
}) ;
Table 4.2: Load ( ) versus Get ()

4.3.2 The jQuery $ . p o s t () Method


The $ . post () method asks data of a resource from a Web server through a POST request.

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

Syntax
$.post(URL,data,callback);
where,

• URL: Indicates the URL a Web developer intends to request.


• data: Is optional and represents extra data to be passed to the function.
• callback: Is optional and is a function to be executed when the request is successful.
Figure 4.13 shows how to use $ . post () method with a callback function to send data and display
the contents of an ASP file into an HTML page.
1 < !DOCTYPE htmlg
2 <html>
3 <head>
4 <script src-"https :/ / a i a x .qoo q leapis.com/aiax/libs/icroerv/3.1.1/icroerv.min.is"></scriPt>
5 <script>
6 $ (document).r e a d y (function(){
7 S("button").c l i c k (f u n c t i o n (){
8 $.p o s t ("demo_test_post.asp",
9
10 name: "Bruce Wayne",
11 city: "Gotham"
12 >,
13 (5 function(data,status){
14 alert("Data: " + data + "\nStatus: " + status);
15 )) ;
16 )) ;
17
18 -</script>
19 -</head>
20 P<body>
21
22 <button>Send an HTTP POST request and get the result back</button>
23
24 -</body>
25 -</html>

Figure 4.13: Code for Using $ . p o s t ( ) with a Callback Function

In figure 4.13, the jQuery $ . post () method takes three parameters: First being the ASP file URL,
second being the data of name and city, and third being the callback function. The code passes this
data along with the request. In the callback function, the first parameter possesses the requested
page's content, while the second one indicates the request's status.

By sending data as its second parameter, we are writing it to the demo_test_post.asp file and
fetching the same for displaying on the HTML page. The ASP file has the following script:

dim fname,city
fname=Request.Form("name")
c ity=Request.Form("city")
Response. Write ("Hello " & fname & ", where are you from" & city &
" . ")
%>

The ASP script here reads the parameters, assigns them to variables, and returns a result. The script
declares two variables namely, fname and city. Then, it assigns the values fetched from the HTML
page to them using request.form ().

V1.0 © APTECH LIMITED


Developing Responsive Websites with Bootstrap and jQuery

Figure 4.14 shows the output.

( < g ^ ) @ [aC !\A p p s\A H x .html p - o He C:\Apps\Ajax.html

Send an HTTP POST request and get the result back


Message from webpage

Data: Hello Bruce Wayne, where are you from Gotham


! Status: success

Figure 4.14: Output of Code Using $ . post ( ) with a Callback Function

Web developers may consider that the $ . g e t () and $ . p o s t () methods are same. However,
there is a difference between the two. Table 4.3 distinguishes them.

Point of $ •g e t ( ) $ . p o s t ()
Distinction
Functionality Is mainly for obtaining data from a Web Is mainly for changing data on a
server although it can send data. Web server although it can send
data.
Caching Is capable of caching the requested data Does not cache data.
and returning it.
Method of Sending Appends data to the URL as a query Includes the data in the message
Data string. body.
Limitation on Data Puts a limit on the amount of data to be Has no such limitation.
to Be Sent sent because of the limit on the length of
the data passed to an URL.

Table 4.3: $ . get () versus $ . post ()


4.4 Autocomplete Function in jQuery
While filling a form, it is common to see a drop-down menu giving a list of words that best matches
with the typed characters. In short, the browser tries to predict the exact value a user wishes to
enter in the text field. This is commonly evident when a user types just two or more characters of
the word or phrase in the search box of Google after which a drop-down.

Auto completion is a comonly used technique in modern Websites to offer a list of suggestions for
selecting the exact value instead of typing it. In jQuery, the autocomplete widget in JQuery Ul
provides this functionality. It is a control that functions similar to a drop-down list. However, it filters
the options for showing the ones that match with what the user is entering into a control.

JQuery Ul stands for jQuery User Interface and is a robust open-source JS library based on jQuery
framework. It offers a collection of jQuery plugins for easily adding new and complex functionalities
to the library of jQuery. It comprises the following:

• interactive plugins or interactions such as resize and drag


• jQuery plugins or widgets for inserting visual components such as menus, autocomplete, and
progress bars
• Effects encompassing transitions and custom animations, including toggle, show, and hide

V1.0© APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

• Utilities as modular functions or tools such as position and toggle for internal use by jQuery
Ul
Just as jQuery, Web developers can either download the jQuery Ul files from the its Official Website
or use a CDN to refer to them. Code Snippet 2 shows the CDN links to include in the <head> tag.

Code Snippet 2:
clink href = https://code .Jquery.com/ui/1.10.4/themes/ui-
lightness/jquery-ui.css rel = "stylesheet">
<script src = "https://code.j query.com/j query-1.10.2 .j s "></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-
ui .Js "></script>
In code snippet 2, the first link includes the theme of jQuery Ul, ui-lightness, through CSS to
give a stylish look to the user interface. The second link includes the jQuery library. It is essential to
add this link, as the new library is built based on the jQuery library. Finally, the third link includes the
jQuery Ul library to enable it for the Webpage in which these three links exist.

To use the autocomplete plugin, the library offers the autocomplete () method. Using this
method, a Web developer can specify a list of predicted values as a drop-down for any input field.

Syntax
$ (selector, context).autocomplete (opt);
This syntax states that an <input> element should be handled as an input field and displayed just
atop the drop-down list. The opt parameter refers to an object that conveys the behavior of the list.
A Web developer can include more than one option, which they can separate using a comma.

Syntax

$ (selector, context).autocomplete({opt1: vail, opt2: val2... });

Table 4.4 lists the different options.

Option Description
appendTo Appends an element to the list. The value
is null by default.
source Indicates how the data will be obtained,
which will then match with the input
data. It is essential to specify a value for
using the autocomplete widget. The
default value is none.
delay Refers to the waiting time in milliseconds
before fetching the matching values, as
per the value of the source option. The
default value is 300. This option
alleviates thrashing, especially while
fetching non-local data by giving time for
typing more characters prior to auto
search.
miniLength Refers to the number of characters to be
typed before fetching the matching
values. This option averts generating a

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

too big list. The default value is 1.


Autofocus Focuses the first menu item when its
value is true. The default value is
false.
Disabled Inactivates the widget if the value is
true. The default value is false.
Position Specifies the position of the list with
regards to input element. The default
value is { my: "left top", at:
"left bottom", collision:
"none" }.
Table 4.4: Autocom plete Options

Figure 4.15 shows how to use the autocomplete () method in jQuery.


<! doctype html>
2 R<html lang - "en">
3 R <head>
<meta charset = "utf-8">
<title>jQuery UI Autocomplete fun.ction</title>
<link href = "https://code.iquery.com/ui/l.10.4/themes/ui-licrhtness/iquery-ui.css"
rel = "stylesheet">
<script src ■ "https ://code .jquery.com/ jquery-1.10.2. js"X/script>
O c r i p t src - "https: //code .-icaiery. com/ui/l .10 .4/■jtruery-ui .is"X/3erip1:>
10 H <script>
11 R 5(function() {
12 var countries = [
13 "Germany ",
14 "Ghana",
15 "Craotia",
16 "Cambodia",
17
$ ( "#autcnplete-l" ) . autocosplete({
19 source: countries
20 - });
21 });
22 </script>
23 - </head>
24 H <body>
25 T<!— HTML — >
26 R <div class = "ui-widget">
<p>Type "g" or "c"</p>
<label for ■ "automplete-l">Tags: </label>
29 <input id « "automplete-l">
30 - </div>
31 - </body>
32 L</htrol>

Figure 4.15: Code for Using the a u t o c o m p le t e ( ) Method in jQuery

In figure 4.15, the CDN links for jQuery UI and jQuery exists under the <head> tag. Next, the code
defines an array named countries holding the names of four countries. Then, the
autocomplete () method is associated with the
input field whose id is a u t o m p le t e - 1. It takes the
source option whose value is set to countries,
which is an array. This populates the autocomplete
drop-down list with the elements of the array. This list
appears when the user enters 'g'or 'c' in the input
field. The type of source mentioned here is local, as it is
defined in the code. A local source is preferable for
having a fewer values in the autocomplete drop-down Go for a remote source for
list. populating the list with hundreds
of values from a database.

V1.0© APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

In the HTML body, the d i v tag contains the . u i - w i d g e t class. This class is applicable to the
autocomplete widget's outer container for setting the font family and its size.

Figure 4.16 shows the output.

Type' g" or "c"

Tags: d x
Germany
Ghana

Figure 4.16: Output of Code Using the a u to c o m p le te ( ) Method in jQuery


4.5 Widgets in jQuery
A few visual controls or elements on a Webpage are likely to accept the intended state, roles, and
responsibilities naturally at the time of development. Adding more such elements to a Webpage
usually increases the level of complexity. This triggers a need for a maintainable design solution.
Such a solution features modularity, purposeful design, and unit tests that strengthen the major
parts of the environment, coding language, and the platform.

In case of jQuery, the platform is the browser, JS is the language, and jQuery and jQuery Ul libraries
denote the environment's major parts. The libraries tend to make the code simple by:

• Reducing the number of lines.


• Resolving browser compatibility issues.
• Ensuring consistency in AIAX interactions.
• Implementing modularity.

At the core of jQuery Ul's visual section is a widget. A widget refers to an object associated with an
element on a Webpage for handling many aspects with other JS objects or widgets. These aspects

• Lifespan
• Interaction
• State
• Inheritance

Widgets in jQuery come from jQuery Ul and are handy for designing Webpages that are highly
interactive. The jQuery Ul widgets are special plugins that simplify the task of applying a functionality
to their associated elements. The standard jQuery plugins do not possess a few built-in capabilities,
such as regulating the plugin's lifespan, revealing methods, and associating data with its elements.
However, widgets come with these capabilities. Following are the jQuery Ul widgets:

• Accordions
• Buttons
• Tabs
• Sliders
• Autocomplete

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

• Dialogs
• Datepickers
• Progress bars
• Menus
• Spinners
• Tooltips
4.5.1 Using the Tooltip W idget

Replacing the native tooltip, the Tooltip widget comes with fresh themes and facilitates
customization. It allows display other content instead of just the title attribute, such as AJAX-
retrieved data and footnotes. The widget also customizes the alignment of tooltips, such as aligning
it in the middle. It also applies additional styling to personlize the appearance. This is useful for
indicating a warning or error.

Web developers can apply a tooltip to any HTML element. In HTML without jQuery, a Web developer
simply needs to specify the title attribute to the desired element for showing a tooltip. The
browser displays the value of this attribute as a tooltip when a user hovers over the element. Code
Snippet 3 illustrates the use of both the title attribute and Tooltip widget of jQuery Ul.

Code Snippet 3:
HTML
<label id="lName" for="tName" title="Full Name">Name</label>
<input id="tName" type="text" title="Your full name as it appears in
memo"/>

JQuery
$ ('tttName ') .tooltip () ;
In code snippet 3, the label element shows the native tooltip, while the text field uses the widget's
tooltip () method to display the tooltip. Code Snippet 4 shows how to apply the widget to all the
elements in a document, which have the title attribute.

Code Snippet 4:

$ (document) .tooltip () ;
jQuery Ul offers the tooltip () method for applying a tooltip to any HTML element. It applies a
fading effect by default to hide or show the tooltip instead of simply toggling the tooltip.

Syntax
$ (selector, context).tooltip(opt);
$(selector, context) .tooltip ({opt1: vail, opt2: val2... }) ;
Table 4.5 lists the different options that a Web developer can pass as parameters to the
tooltip () method.
Option Description
co n te n t Indicates the tooltip content. The default
value is a function that returns the value
of the title attribute.
it e m s Denotes the items that can display the
tooltip. The default value is t i t l e .

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

disabled Inactivates the widget if the value is


true. The default value is false.
hide Denotes the effect of animation while
hiding the widget. The default value is
true.
show Conveys the manner in which the display
of the tooltip shall be animated. The
default value is true.
track Allows the tooltip to follow the mouse if
the value is true. The default value is
false.
position Sets the tooltip's position with regards to
its target element. The values can be at,
within, of, using, collision, and
my. The default value is a function
returning the value of title attribute.
too It ipC lass Is useful for showing an error or warning
via a tooltip. The default value is null.
Table 4.5: Tooltip Options

Figure 4.17 shows how to use the tooltip () method in jQuery.


1 < Jdoctype html>
2 R < h t m l lang = "en">
3 H <head>
<meta charset ■ *'utf-8">
<title>jQuery Ul Tooltip</title>
<link href = "h t t p s ://code.jquery.com/ui/I.10.4/themes/ui-lightness/jquery-ui.cs s "
rel = "stylesheet">
< s c r i p t src = "h t t p s ://c o d e .j q u e r y .c o m / j q u e r y - 1 .10.2. j s ,,> < / s c r i p t >
9 <script src = "https ://code ■iquery. com/ui/l.10.4/icmerv-ui ■is" X / s c r i p t >
10 R <script>
11 H $(functionO {
12 $ ("ImyTocitip") .tooltip ();
13 });
14 </script>
15 </head>
16
17 i <body>
18 < !— HTML — >
19 <lafcel for = "nameM>FirstNaiae :</label>
20 Cinput id = "myTooltip" title = "Enter Your first name">
21 </body>
22 </html>

Figure 4.17: Code for Using the tooltip ( ) Method in jQuery

In figure 4.17, the tooltip () method is invoked to display the value of title attribute near the
text field. Figure 4.18 shows the output.

FirstName:

Enter Your first name

Figure 4.18: Output of Code Using the tooltip () Method in jQuery

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

4.5.2 Using the Dialog Widget

The Dialog widget provides a floating window that has a title and a body with content. The window is
moveable via dragging and resizable through stretching. A user can even close the dialog by clicking
the x icon present in its top-right corner. The window is dynamic enough to display a scrollbar if the
content exceeds its maximum height. For customizing it, a Web developer can add a button to its
bottom and modal in its body area.

jQuery Ul offers the dialog () method for showing a dialog box.

Syntax
$ (selector, context).dialog(opt);
$(selector, context).dialog({opt1: vail, opt2: val2... });
Table 4.6 lists a few options that a Web developer can pass as parameters to the dialog ()
method.

Option Description
title Indicates the title text. The default value
is null.
autoOpen Opens the dialog box if the value is
true, which is the default value. If false,
it opens the dialog box only when a Web
developer invokes dialog('open’).
closeOnEscape Closes the dialog box once a user presses
the Esc key when the focus in on the
dialog box if the value is true. This is the
default value.
buttons Includes buttons in the dialog box.
draggable Allows dragging the dialog box by
dragging its title bar if the value is true.
This is the default value.
resizable Allows resizing the dialog box in any
direction if the value is true. This is the
default value.
modal Applies the behavior of a modal to the
dialog box if the value is true. Other
items on the page are disabled. The
default value is false.
position Sets the dialog box's initial position,
which can be top, center, left, right, or
bottom.
Table 4.6: Dialog Box Options

Figure 4.19 shows how to use the dialog () method in jQuery.

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

1 < !doctype html>


2 n <html lang = "en">
3 H <head>
4 <meta charset - "utf-8">
5 Clink href = "h t t p s ://c o d e .jquery.c o m/ui/l.10.4/themes/ui-lightness/jquery-ui.c s s ”
6 rel - ”stylesheet">
7 <script src = "h t t p s ://c o d e .jqu e r y .com/jquery-1.10.2.js"></script>
8 <script src = "https ://code .jquery.com / u i / l .10 .4/iquery-ui .js" X / s c r i p t >
9 R <script>
10 R $ (function() {
11 R $( "tmyDialog" ).dialo$({
12 autoOpen: faLse,
13 }>;
14 $( "#open" ).click(function() {
T
15 $( "#jnyDialog" ).dialog( "open" );
16 });
17 });
18 </script>
19 </head>
20 <body>
T
21 <div id = "myDialog"
22 title * "Dialog">jQuery Dialog!</div>
23 <button id = "open">Open Dialog</button>
24 </body>
25 L </html>

Figure 4.19: Code for Using the dialog ( ) Method in jQuery

In figure 4.19, the <div> and <button> elements have their respective dialogs. For <div>, the
dialog () method has the autoOpen option set to false. This means that the dialog box will
not open when the page is loading. When a user clicks the button, the dialog () method with the
open parameter invokes the dialog box for the <div> element. This means that clicking the button
will create and display the dialog box with the content, J Query Dialog !.

Figure 4.20 shows the output upon clicking the button.

Open Dialog

jQuery Dialog!

Figure 4.20: Output of Code Using the dialog ( ) Method in jQuery


4.6 Datatable Plugin in jQuery
Datatable is an intuitive jQuery plugin that adds more functionality to the <table> element. It
makes a plain HTML table dynamic by easily including the pagination, sorting, and searching utilities
in it. This enables a developer to manage the display of huge quantity of data. Similarly, the plugin
also enables a user to access the desired data quickly. The plugin is quite flexible to facilitate user-
friendly interaction for an HTML table.
Developing Responsive W ebsites with Bootstrap and jQuery

Following are the salient feature of datatables:

• Free and open-source


• Support for any data source including AJAX
• Built-in utilities such as instant search, pagination, and column-based ordering
• Built-in extensions such as fixed columns and buttons
• Built-in options such as scrollY and order along with callback functions
• Completely internationalizable
• Comprehensive documentation
• Hundreds of examples

For using the plugin, a Web developer needs to include only two additional files in the intended
Webpage. They are the DataTables JS file and the DataTables CSS file. Web developers can either
download the files from the Official Website or refer to a CDN. Code Snippet 5 shows the CDN links
to these files, which a Web developer needs to add along with jQuery CDN link.

Code Snippet 5:
clink re1="stylesheet" type="text/css" href="//cdn.datatables.net/1.
10.13/css/j query.dataTables.min.css">
<script type="text/javascript" charset="utf8" src=”//cdn.datatables.
net/1 .10. 13/j s/j query.dataTables.min .Js" ></script>
Web developers can use datatables with a variety of data sources. A datatable can accept on the
data of an array, an HTML table, or AJAX-retrieved data.

Syntax
$ (selector) .dataTable () ;
In this syntax, the jQuery selector is usually a reference to an HTML table, which a Web developer
intends to enhance. The datatable () method can accept options as optional parameters, which
form a configuration object of the dataTable constructor. Code Snippet 6 shows the usage of some
of these options.

Code Snippet 6:
$('table').dataTable( {
paginate: true,
scrollY: 400
> );
In code snippet 6, pagination and scrolling both are enabled for the datatable.

Figure 4.21 shows how to use the datatable () method in jQuery.

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

< ! DOCTYP£ htal>


^ < h t m l xml na«" h t t p ://yww.w3 .o r y / 1 9 9 9 / x h t n l “>
3 < h e a d r u n « t » ‘'*crvor">
<titl«x/titlo>
Ocript
3rc--httpa.i /./coda j q u e r y i.con/^guery-2-t2 14
integ r i t y * " s h a 2 5 6 - B b h d l v Q f / x T Y 9 g j a 0 D q 3 H i w Q F 8 L a C R T X x Z K R u t e l T 4 4 * "
c r o s s o r i g i n " " a n o n y w o u s ,,> < / s c r i p t >
Ocript
arc-"httB»://code- iaaciy ■c<?n/ui/l,1 2 ,1/ jqv«ry-vu.nln, ji"
integrity-"sha256-VazP97ZCwtekAsvgPBSl/wPFKdrwD3unUfSGVYrahVqU-"
crossorigin-"anonymous"X/script>
< li n k rel»"stylesheet" type-"text/css"
hrcf-"http3i//cdHid&t&taklca.,ntt.t/l.lQil3/ca3./;ittucryl.dfttaIflbloa-.nlri^caa" />
O c r i p t arc*" h t t p s :/ / r>An djit a t a h l e s . n e t / 1 . 1 0 . 1 3 / ia/^auftry -n l n . ^ s ">
</script>
O c r i p t typ©»"text/javascript">
i(docusenc).ready(function () (
*<•♦datacabie*).dacaT&ble();
I);
</script>
</head>
< b o d y s t y l e » M£ o n t - £ a n i l y : A r i a l M>
<form id»"£ormlM run«t»"*erver">
< d i v 3 t y l e « "width: 500 p x ; b o r d e r : lpx s o l i d b l a c k ; padding: 5px">
<table id-"datatable">
<thead>
<tr>
<th>ID
</th>
<th>City
</th>
<th>Country
</th>
<th>Continent
</th>
</zr>
</thead>
<tbody>
<tr>
<td>l</td>
< td > M o n t e r i a < / td>
<td>Colombia</td>
<td>South America</td>
</tr>
<tr>
<td>2</td>
< t d > B i r m i n g h a m < / td>
<td>United Kingdom</td>
< t d > E u r o p c < / td>
</tr>
£j <tr>
<td>3</td>
< t d > B a n g a l o r e < /td>
<td>India</td>
<td>Asia</td>
</tr>
</tbody>
</table>
</div>
</forrn>
</body>
L</html>

Figure 4.21: Code for Using the d a t a t a b le ( ) Method in jQuery

In figure 4.21, the <head> tag includes CDN references to jQuery, jQuery Ul, and dataTables files.
Within the <script> tag, the datatable () method is associated with the HTML table whose id
is datatable. This table has three rows.

Figure 4.22 shows the output.

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

Show 10 v |entries Search:


ID A City Country Continent

1 MonterAa Colombia South America


2 Birmingham United Kingdom Europe
3 Bangalore India Asia

Showing 1 to 3 of 3 entries Previous 1 Next

Figure 4.22: Output of Code Using the datatable () Method in jQuery

In figure 4.22, the HTML table features the search, pagination, and scrolling utilities. It is no longer a
plain HTML table.

Quick Test 4.1

1. The autocom plete functionality is added directly in jQ uery.


True
False

2. A callback function waits for an effect to occur completely.

True
False
Developing Responsive W ebsites with Bootstrap and jQ uery

___
Sum m ary
V

>■ Built-in functions are methods that allow manipulating data values such as dates, numbers, and
strings.

> The live () method delegates event handlers to existing and future elements that match with the
selector.

>* The jQuery AJAX methods allow requesting data from a distant Web server via LOAD, GET, and
POST in different formats and load the same into the desired HTML element.

> A callback function runs once the current jQuery effect is over.

> The $ . get () method asks data of a resource from a Web server through a GET request.

> The $ . post ( ) method asks data of a resource from a Web server through a POST request.

>• The jQuery UI library offers the autocomplete () method to implment the autocomplete plugin.

> A widget refers to an object associated with an element on a Webpage for handling the lifespan,
interaction, state, and inheritance and other aspects with other JS objects or widgets.

> The jQuery UI widgets are special plugins that simplify the task of applying functionality to their
associated elements and offering some capabilities lacking in standard jQuery plugins.

>- The Datatable jQuery plugin makes a plain HTML table dynamic by easily including the pagination,
sorting, and searching utilities in it.
Developing Responsive Websites with Bootstrap and jQuery

f~
Check Your Progress
^ J

1. is a built-in iQuerv function.


a .sortstr ( )
b .pop ( )
c .pushstr ( )
d .tostr ( )
2. W hich of the follow ing param eters are of the live() method?
a .Event 1istener
b .data
c.Callback function
d .element
3. The object is a param eter of the loadO function.
a .$ .f n
b .HttpRequest
c .XMLHttpRequest
d .html ()
4. W hich of the following statem ents is true about $ . g e t ( ) m ethod?
a. It can load any type of data.
b. It always uses GET.
c. It can cache the requested data.
d. All of these.
5. W hich of the follow ing statem ents about jQ uery Ul is true?
a. It is built upon AJAX.
b. It offers the datatable functionality.
c. It provides widgets.
d. None of these.
Developing Responsive Websites with Bootstrap and jQuery

Answers to Check Your Progress


1. p o p ().
2. data.
3. X M L H ttp R e q i l e s t .
4. All of these.
5. It provides widgets.

Answers to Quick Test


Quick Test 4.1

1. False
2. True
Developing Responsive W ebsites with Bootstrap and jQuery

SESSION 5 - Creating Bootstrap


^Responsive Layout__________
Session Objectives:
This session introduces the Bootstrap responsive layout along with the elements that contribute to
it. It explains the responsive grid system and shows how to use it to create simple responsive
Webpages. The session also describes the usage of jumbotron component and various typography
classes in Bootstrap for transforming and styling text in HTML elements.

At the end of this session, you will be able to:

> Describe how bootstrap helps in achieving responsiveness


> Explain the grid system
> Outline the use o f Jumbotron component
> Describe the use of various typography classes
> Describe creation of simple responsiveness pages with Bootstrap

5.1 Bootstrap Responsive Layout


The increased usage of mobile devices such as smartphones and tablets has made it indispensable to
optimize Websites for them. In simple words, a Website should adjust to the screen size of any
device to ensure proper viewing of the page. This is exactly what a responsive Web design offers.

It refers to a design process for providing ease of access and smooth viewing experience to the users
regardless of the device in use. Such a design concept is desirable and an efficient way to display a
Website on a variety of devices with least efforts.

A responsive layout adapts its user interface components and perhaps even functionality to any
screen size on its own. This screen can be of a laptop, desktop, or a mobile phone. The width of the
browser does not matter, as the layout responds according to it, as shown in figure 5.1.

U J □ n □

Figure 5.1: Responsive Layout on Different Screens

In figure 5.1, there are four tabs in the middle in all devices, but its location differs as per the size of
the device's screen. Changing of the layout as per size of the target screen facilitates an optimal
viewing experience. This encompasses effortless reading and navigation on the target devices with
minimum resizing, scrolling, and rotating.

V1 .0© APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

A responsive Website adapts its layout to the viewing screen using three elements:

• Fluid, proportion-based grids


• Flexible or fluid images other multimedia
• CSS3 media queries (extension of @media rule) for applying suitable breaks to the page's
content

It is challenging to design a Website that can change its environment as per its requested Webpage.
This means that the grids and multimedia should be fluid and flexible. At this point, using media
queries becomes essential to display the right assets in the right manner on the targeted devices.

A fluid grid handles sizing of a page element in relative units such as percentages, instead of absolute
units such as points or pixels. Such relative sizes are also set for flexible multimedia so that they do
not move outside their container. Media queries apply different CSS style rules as per targeted
device's characteristics, more commonly being
the browser's width.

Bootstrap 3 handles all these elements to give a


solid foundation for designing and developing
responsive Web applications. With its mobile first
grid system, it has become easier for Web
developers to build responsive and mobile-
friendly applications.

Being mobile first means that the Bootstrap code There is no need of extra style
begins by focusing first on smaller screens of sheet for activating the responsive
devices such as tablets and smartphones. It then functionality in Bootstrap 3.
expands its components including the grids for
larger screens such as desktops and laptops.

Version 3 comes with four classes of grids. These


classes offer better control over the layout and over the manner in which the grid will render on
different devices. Bootstrap media queries allow showing, hiding, and moving content based on the
size of the viewport.

5.2 Working with Grids in Bootstrap


Bootstrap 3 comes with a robust mobile-first grid system for designing a responsive layout of any
size and shape. A grid in Bootstrap is a collection of HTML/CSS components. This collection enables a
Web developer to structure a Website and insert its contents easily in the intended locations.

An analogy of this grid system is a graph paper consisting of a series of vertical and horizontal lines.
These lines intersect each other such that they create rectangular or square boxes. The same
concept applies to the grid system that allows defining rows and columns to put the desired content
in the resulting boxes.
A Web developer can create only up to 12 columns for a Webpage regardless of the viewport, but
can have unlimited rows. This is why it is also known as a 12-grid system or 12-column layout, as
shown in figure 5.2.

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

sp an 1 sp an 1 span 1 sp an 1 sp an 1 sp an 1 span 1 span 1 sp an 1 sp an 1 sp an 1 sp an 1

sp an 4 sp an 4 sp an 4

sp an 4 sp an 8

sp a n 6 sp an 6

s p a n 12

Figure 5.2: 12-column Grid Layout

In figure 5.2, it is clear that each row can only have up to 12


columns. Each grid column holds the number out of 12 available
Note: If the number of columns
columns across which it should span. For example, each column
exceeds 12, the additional
in the second row of figure 5.2 spans up to four columns. This
columns shall stack irrespective
splits the row into a total of three columns, each holding four
of the viewport.
columns. I

The grid system in Bootstrap is responsive due to which the


columns tend to re-arrange as per the size of the screen. A layout with three columns looks better
on a big screen. Similarly, a layout with stacked items looks better on a small screen.
The grid system consists of a series of containers, rows, and columns for designing a layout and
aligning its content. The container element covers the content by setting the margins on the left and
right. In case of a fixed container, the width differs as per the targeted device, which is shown in
table 5.1.

Width of Device's Screen Width of Fixed Container


1200 pixels and beyond 1170 pixels
992 to 1199 pixels 970 pixels
768 to 991 pixels 750 pixels
Under 768 pixels Auto
Table 5.1: Different Fixed Widths

In case of a fluid container, its width is always equal to that of the targeted device. However, on the
right and left sides, both fixed and fluid containers feature padding of 15 pixels.

A row extends from left to right edge of a container and wraps content around the columns. It
eliminates the container's padding through a margin value of -15px on both sides. In simple words,
the text in a row touches the container's left edge. A Web developer can create a row by specifying
the . row class in a block-level element. For example, this element can be <div> within a
container. For columns, there are various class prefixes for different screen sizes.

5.2.1 Predefined Grid Classes


Bootstrap 3 provides predefined grid classes for designing responsive layouts quickly for different
devices. There are four such classes that form the four tiers of the grid system, which are as follows:

• xs, which is for extra small screens


• sm, which is for small screens
• md, which is for medium-sized screens
• lg, which is for large screens

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

A Web developer can user one or more of these classes to design a more dynamic and fluid layout. A
Web developer can now show a Website with a different grid as per the varying browser size. Table
5.2 shows the column specifications for varying browser sizes.

Column Definition Browser of Target Device Browser Size


.col-lg-* Large devices (desktops) 1200 pixels and up
.col-md-* Medium devices (desktops) 992 pixels and up
.col-sm-* Small devices (tablets) 768 pixels and up
.col-xs-* Extra small (mobile phones) < 768 pixels
Table 5.2: Column Specifications for Different Browser Sizes

In table 5.2, the * symbol represents the number of columns the resulting column in a row should
cover. For example, to cover four columns out of 14 in just one column, a Web developer needs to
specify . c o l - x s - 4 . Technically, each class cascades upwards. In simple words, if the widths for x s
and sm are same, the Web developer needs to mention only x s .

5.2.2 Rules of Bootstrap Grid System


Bootstrap 3 has few rules to follow while using its grid system. Following are these rules:

• Containers act as a means to middle-align the contents of your site.


• Rows are horizontal series of columns for properly aligning the columns. For aligning and
ensuring proper padding of rows, it is essential to place them within a container.
• Columns hold the content and only they can be the direct children of rows.
• Predefined grid classes for columns indicate the type of device and number of columns to
include out of 12 for each row. For example, for having four columns of equal width in a row,
a Web developer should specify <div> tags four times, each with . c o l- s m - 3 class. This
means that each column in this row shall span up to 3 columns to cover all 12.
• Grid tiers depend on minimum widths, which means they are applicable to all tiers lying
above the specified one. For example, applying . c o l- s m - * to an element affects its styling
even on medium and large devices even if their classes are not included. This means that a
column for smaller devices shall work in any device.
• Predefined grid classes for both rows and columns make grid layouts quickly.
• Columns have gaps between its content, which is known as gutters. They do so through
padding, which is neutralized for the first and last column in a row via negative margin.

Table 5.3 shows the different grid options that work across several devices.

Options/Devices Extra Small Small Devices Medium Large Devices


Devices Devices

Grid Behavior Always horizontal Collapsed, Collapsed, Collapsed,


horizontal over horizontal over horizontal over
the media query the media query the media query
breakpoints breakpoints breakpoints

Container Width Auto 750 970 1170


in Pixels

Class .col-xs-* .col-sm-* .col-md-* .col-lg-*

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

In figure 6.1, when the screen is smaller such as on a mobile device whose size is less than 768
pixels, each column expands to have a width of 100%.
Bootstrap defines its media queries in bootstrap-
responsive.css file located in the css folder under assets. It
Note: A Web developer can
specifies breakpoints in a grid system. Code Snippet 1 shows
insert several breakpoints as per
how bootstrap media queries implement the mobile-first
the requirements.
technology.

Code Snippet 1:
/* Portrait phones and smaller */
@med±a (max-width:480px) {}

/* Landscape phones and portrait tablets */


@media (max-width:767px) {}

/* Portrait tablets and small desktops */


@media (min-width:768px) and (max-width: 991px) {}

/* Landscape tablets and medium desktops */


@media (min-width:992px) and (max-width: 1199px) {}

/* Large desktops and laptops */


©media (min-width:1200px) {}
In Code Snippet 1, the media queries start by targeting the small devices or media before any other
devices. This is how mobile-first technology is implemented to display Webpages faster on smaller
screens.

Here, a media query contains the @media attribute and one or more width-based logical
expressions. The expression, when matches with the screen resolution of a specific device, returns
true or else it returns false. A Web developer can specify a block of CSS properties or rules,
which should apply only if the width condition is true.

The line stating @media (max-width: 480px) allows applying styles to layouts on devices
having 480 pixels as maximum width. Similarly, @media (min-width 768px) and (max-
width : 991 px) allows applying styles to layouts on devices whose screens have a width that is
equal to or more than 768 pixels and less than or equal to 991 pixels. In short, the style sheet shown
in Code Snippet 1 stores styles as per the minimum and maximum widths of the targeted screens
using two properties namely, min-width and max-width.
The benefit of this mechanism is that it facilitates targeting the different ranges of screen size
instead of a specific type of device. This means that when a new model of tablet or smartphone is
released, Web developers are sure that their Websites shall appear precisely on the new screen. This
is because the device's screen size exists in the covered range.

Figure 6.2 shows how to use a mobile-first media query within a Bootstrap application to deliver
device-specific styles.

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

Column Width in Auto 62 81 97


Pixels

Gutter Width in 30 (15 on each 30 (15 on each 30 (15 on each 30 (15 on each
Pixels side) side) side) side)

Nestable Yes Yes Yes Yes


Table 5.3: Grid Options

5.2.3 Grid's Basic Structure


A grid structure for any layout has one or more containers, rows, and columns. A Web developer
should start by defining a container that contains rows and columns. Then, within the container, the
code should define rows using the .row class. Next, within a row, the Web developer should define
columns using .col-xs-*, .col-sm-*, .col-md-*, and .col-lg-* classes. Finally, these
columns are where the Web developer can place the content. Code Snippet 1 shows the basic grid
structure in Bootstrap.
Code Snippet 1:
<div class="container">
<div class="row">
<div class="col-*-*"></div>
</div>
<div class="row">
<div class="col-*-*"></div>
<div class="col-*-*"></div>
<div class="col-*-*"></div>
</div>
<div class="row">

</div>
</div>
In code snippet 1, the code defines three rows within a container through <div class=’
'row">.
To each row, it adds the desired number of columns through suitable . col-*-* classes. The
numbers in . col-*-* for a row should total up to 12.

5.2.4 Grids for Different Devices


A grid system differs as per the devices in terms of layout. In simple words, for each type of
device, the grid system has a distinct split percentage for columns in a row. Following are the
four types of grids, each suitable for different devices:

• Stacked or horizontal
• Small
• Medium
• Large

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

Stacked or Horizontal Grid

This grid system loads as a stack on small devices such as mobile phones prior to being
horizontal on medium or large devices.

Figure 5.3 shows the code for a stacked-to-horizontal layout featuring two columns. These
columns will split in the percentage ratio of 50:50 on all screens. However, on extra small
screens, it will stack.
<1D0CTYPE html>
< h t m l l a n g » " e n H>
<head>
<meca charset«"utf-8">
< m e t a n a m e - " v i e w p o r t " c o n t e n t - " w i d t h - d e v i c e - w i d t h , i n i t i a l - s c a l e — l">
<link rei«"*tylesheet" href-"http>;//mflxgdn.kogtstgflggda, con/iregtatrflp/3,3. ?/c»/bqot>trflg.;nln. «»">
ocript arc-"httga;//•»jfts.ggpgloapls.cpm/ajax/lU?*/jqugry/3,2, Q/3quory.min.3a"x/acript>
< s c r i p t a r c « wh t t p s : / / m a x c d n .boots t r a p c d n .c o m / b o o t s t r a p / 3 ■3.7/ ^ a / b o o t s t r a p . m l n . j s " X / a c r i p t >
</head>
£j<body>

(3<div c l a a a » ”c o n t a i n e r " >


<hl>Orid System</hl>
< p > c o l - s m - 6 d i v i d e s t he p a g e i n t o t w o e q a u a l h a l v e s < / p >
< p > R e s c a l e the b r o w s e r t o s ee t he c h a n g e s < / p >
< d i v cla3s»'*row”>
< d i v c l a a a » " c o l - s m - 6 " s t y l e « " b a c k g r o u n d - c o l o r :g r e e n ;'•>
Bootstrap includes a powerful mobile-first flexbox gr i d system
f o r b u i l d i n g l a y o u t s o f a ll s h a p e s a n d sizes.
</div>
£] < d i v c l a 3 3 » ,,c o l - s m - 6 " 3 t y l e » " b a c k g r o u n d - c o l o r :red;">
R e s p o n s i v e W e b d e s i g n is a W e b d e s i g n a p p r o a c h a i m e d a t c r a f t i n g s i tes
to pr ov id e an optimal vi ewi ng experience
</div>
</div>
</div>

</body>
</html>

Figure 5.3: Code for Stacked-to-Horizontal Layout

Figure 5.4 shows the output wherein both the columns in a row are split in a percentage ratio of
50/50.
-
i I
( ) ( '■/) | -1' C V.pps\6fid.htm l P • 6 | j g C:\Appa\Grid.html

Grid System
coi-sfn-6 divides Itie page in to tw o cqauul halves

Rescale U*e browser to see the changes

Figure 5.4: Output of Code for Stacked-to-Horizontal Layout

Grid Layout for Small Devices


Small devices possess a screen whose width is between 768 and 991 pixels. For these devices, Web
developers should use the . col-sm- * classes. Assuming a layout having only two columns, a Web
developer can split them into the percentage ratio of 75/25 or 25/75. Figure 5.5 shows 75/25 split.

V1.0© APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

<! DOCTYPE html>


<htmL lang="en">
<head>
<meta charset="utf-8">
<meta name-"viewport" content“"width—device-width, initial-scalc—l">
< l i n k r e l = " s t y l e s h e e t " h r e f = " h t t p s : / / m a x c d n . b o o t s t r a p c d n .c o m / b o o t s t r a p / 3 . 3.7/ a s s / b o o t s t r a p . m i n .a s s "
<script 9rc="h.t.tpa.;//aiax».go.fligleflpia.»..g.Qm/a3ax/liba/iquiery/3..2,Q/^guery,nln,jg"></3cripr>
< s c r i p t a r c - " h t t p s : / / m a x c d n . b o o t s t r a p c d n . c o m / b o o t s t r a p / 3 . 3 .7 / i s / b o o t s t r a p . m i n . ~is" > < / s c r i p t >
</head>
[)3<body>
11
12 !<div c l a s s = " c o n t a i n e r " >
<hl>Grid System</hl>
<p>col-sm-9 col-ssi-3 divides the page in to two 75:25 ratio</p>
<p>Rescale the browser to see the changes</p>
<d£v cla3s="rovf">
< d i v c l a s 3 - " c o l - s m - 9 " 3 t y l e » " b a c k g r o u n d - a o l o r :g r e e n ; " >
Bootstrap includes a powerful mobile-first flexbox grid system
for building layouts of all shapes and si-zes.
</div>
<div class="col-sm-3" style="background-color:red;">
Responsive Web design is a Web design approach aimed at crafting sites
to provide an optimal viewing experience
</div>
</div>
</div>

</body>
</hrml>

Figure 5.5: Code for Grid Layout for Small Devices


Figure 5.6 shows the output.

ft * O

Grid System
col-sm-9 col-sm-3 divides the page In to two 75:25 ratio

Rescale the browser to see the changes

Figure 5.6: Output of Code for Grid Layout for Small Devices

Grid Layout for Medium Devices

Although a split of 25/75 for two columns looks fine for small devices, it is not an ideal choice for
medium devices. For them, a split of 50/50 results in a better look, as they possess a screen whose
width is between 992 and 1199 pixels. For these devices, a Web developer should specify the
.col-md-* classes. Code Snippet 2 shows how to specify column widths for medium devices.
Code Snippet 2:
<div class=”container-fluid">
<hl>Hello World!</hl>
<div class="row">
<div class="col-sm-3 col-md-6" style="background-color:yellow;">
<p>Medium Devices left.,</p>
</div>
<div class="col-sm-9 col-md-6" style="background-color:pink;">
<p>Medium Devices Right.</p>
</div>
</div>

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

</div>

In code snippet 2, for a two-column layout on medium devices, the code specifies <div
class=”col-sm-3 col-md-6"> and <div class="col-sm-9 col-md-6">. These
lines convey that sm is for display on small devices and md is for display on medium devices. The
snippet creates a percentage split of 25/75 on small devices, as shown in figure 5.7 and 50/50 split
on both large and medium ones. This layout stacks automatically on extra small devices.

I g C\Appi\God.h<ml P -C | Q C:\Appt\0ntfWml ft * a

Hello World!
Medium Devices left. Medium Devices Right.

Figure 5.7: Output of Medium Grid Split on Small Devices

If a Web developer specifies only . col-md-6 in both tags, the two columns will split in the ratio of
1:1 on medium and large devices. This is due to the scaling effect. On the other hand, on extra small
devices, the layout shall vertically stack to have 100% width, as shown in figure 5.8.

Hello World!
Medium Devices left..

Medium Devices Right.

Figure 5.8: Output of Medium Grid Split on Extra Small Devices


Grid Layout for Large Devices

While 25/75 percentage split is for small devices and 50/50 split is for medium devices, a split of
33/66 is ideal for large devices. This is perhaps because the width of their screens is at least 1200
pixels. For these devices, a Web developer should specify the . col-lg-* classes. Code Snippet 3
shows how to specify column widths for large devices.

Code Snippet 3:
<div class="container-fluid">
<hl>Hello World!</hl>
<div class="row">
<div class="col-sm-3 col-md-6 col-lg-4" style="background-
color :yellow;">
<p>Large Devices</p>
</div>
<div class="col-sm-9 col-md-6 col-lg-8" style="background-
color :pink;">
<p>Large Devices</p>

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

</div>
</div>
</div>
In code snippet 3, for a two-column layout on large devices, the <div> tags contain three classes,
col-sm-3, col-md-6 , and col-lg-4. The presence of these classes conveys that the page
is set for display on all three types of devices. The snippet creates a percentage split of 25/75 on
small devices, 50/50 on medium ones, and 33/66 on large ones.

In case a Web developer specifies only . col-lg-6 class in both <div> tags, the two columns will
split in the ratio of 1:1 on large devices. However, on small and medium devices, the layout shall
vertically stack to have 100% width.

5.3 Working with Headers in Bootstrap


The page header layout component adds a header to a page. It separates it from the rest of the
content by inserting a horizontal line under the heading. However, using this component would be
insufficient for highlighting the heading text
to grab the attention of visitors. In this
situation, using the jumbotron component is
a better option.

As the name suggest, this layout component


allows increasing the size of heading text. It
also allows adding much space to the content
of a landing page. The component displays
content in a big grey box featuring corners in
the round shape for grabbing attention to
some special details.

Jumbotron is a flexible and lightweight


component that can extend over the whole
viewport to highlight key informative content
on a site.

To create jumbotron, a Web developer should specify the .j umbotron class in a <div> element.
A Web developer simply needs to wrap the special content such as a description or a heading in
<div> and apply this class to it. A <div> tag should contain the . container or . container-
fluid class for appropriate padding as well as alignment.
There are two ways to use this component:

• Inserting it inside <div class=”container"> for preventing it to extend up to the


edges of the screen
• Inserting it outside <div class=" container ” > for extending it up to the edges of the
screen or for having a full-width jumbotron
Figure 5.9 shows the code for preventing the jumbotron to extend up to the screen's edges.

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

<!30CTYPE htal>
<html lang-"en">
<head>
<meta charset»"utf-8">
<meta name«"viewport'* content-"width“device-width, initial-saale-l*’>
<link re 1-"stylesheet” href-"ht.tp3 ;//nftxg<to,.b9Ptg£gflpsdn,gQ??/bg9 satrap/3,3.,7/c«/bggtg.trap.t:nlnL,cag”>
<scri.pt src-"http>;//ajax,g<?<s>glgaplarrcgra/ajax/libs/jquery/3,2,Q/jqucry,nlii,jg,,x/script>
<script src-”https ;//maxcdn.bootstrapcdn.com/boots trap/3,3.7/js/bootstrap .mln.js"X/acript>
-</head>
H <body>

!<div class-"container">
I <div class*"jx«nbotron’'>
<hl>Bootstrap henders</hl>
<p>Bootstrap Header text.</p>
</div>
<p>Normal paratagl</p>
<p>Noraml paratag2</p>
</div>

</body>
</html>

Figure 5.9: Code for Placing Jumbotron inside <div>

In figure 5.9, the <div> element holding the .Jumbotron class is placed inside the <div>
element that holds the . container class. This means that the jumbotron will be displayed inside
this fixed container.

Figure 5.10 shows the output.

Bootstrap headers
Bootstrap Header text.

Normal paratagl
Noraml paratag2

Figure 5.10: Output of Code Placing Jumbotron inside <div>

In figure 5.10, the <div> element within the container aligns the jumbotron to the Webpage. The
jumbotron is inside the fixed container due to which it does not extend up to the edges of the
screen. This is evident from the gap between the left side of the browser and jumbotron.

Figure 5.11 shows the code for extending the jumbotron up to the screen's edges.

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

1 <! D0CTYPE hzxl>


2 E]<html lang«"en">
3 H<head>
4 <meta charset="utf-8">
5 <meta narae="viewport" content="width=device-width, initial-scale=l">
6 <link rel»"stylesheet" href""https://maxcdn.bootstrapcdn.con/bootstrap/3.3.1/css/bootstrap.min.css">
7 <script src="https://ajax.gooqleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js,lX/script>
8 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/is/bootstrap.min.js"></3cript>
9 </head>
10 P<body>
11
12 j<div class="jumbotron">
13 <hl>Bootstrap Header outside container</hl>
14 <p>Bootstrap Header text.</p>
15 </div>
16 |<div class="container">
17 <p>Nomal para tagl</p>
18 <p>Normal para tag2</p>
19 </div>
20
21
22 </body>
23 </html>

Figure 5.11: Code for Placing iumbotron Outside <div>

In figure 5.11, the jumbotron is placed outside and before the container. Thus, it will extend up to
the edges. Figure 5.12 shows the output.

Bootstrap Header outside container


Bootstrap Header text.

Normal para tagi


Normal para tag2

Figure 5.12: Output of Code Placing Jumbotron Outside <div>


5.4 Typography in Bootstrap
Bootstrap offers typography classes and elements that style a few HTML elements in a slightly
different way from the browsers. These are customized typography options available for making text
in headings, body, and lists more stylish.

By default, the size of font in Bootstrap is 14 pixels with 1.428 as the height of a line. These global
settings are applicable to <body> and <p> elements. Moreover, all paragraphs possess a bottom
margin that is half of their line height. Their bottom margin comes to 10 pixels by default.

5.4.1 Headings
For all headings of HTML, Bootstrap has corresponding . h 1to . h6 classes. These classes are useful
for matching a heading's font style and accommodate inline text besides the heading text.

Figure 5.13 shows how Bootstrap styles the HTML headings.

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset»"iitf-8">
<met a n ame="viewport" conrent="width=device-width, i n i t i a l - s c a l e = l ">
<link rel«"stylesheet" hrcf»"https://.maxcdn.bootstrapcdn.com/bootatrap/3.3.7/css/bootstrap.min.css"
<script 3rc="https.://ajax-.gQogleapis:.
som/ajag/libs/jquery/.3.«2 =0/j.guery .min, jg,,x/script>
<script 3rc="https :/ /maxcdn. boo tstrapcdn. com/boots trap/3.3 .7/is/bootstrap.min. is"X/script:>
9 < /head>
10 < b ody >
11
12 < d i v c l a s 3 = "container">
13 <hl>hl Text Transformation (36px)</hl>
14 <h2>h2 Text Transformation (30px)</h2>
15 <h3>h3 Text Transformation (24px)</h3>
16 <h4>h4 Text Transformation (18px)</h4>
17 <h5>h5 Text Transformation (14px)</h5>
18 <h6>h6 Text Tremsformation (12px)</h6>
19 < / div>
20

< /body >


-</html>

Figure 5.13: Code for Styling HTML Headings

In figure 5.13, the code includes all H I to H6 headings just as a Web developer specifies in HTML.
Each of these headings is set as per its pixel size.

Figure 5.14 shows the output.

h i T ext T ransform a tion (36px)


h2 Text Transformation (30px)
h3 Text Transformation (24px)
h4 Text Transformation (18px)
h5 Text Transformation (I4 p x )
h6 Text Transformation (12px)

Figure 5.14: Output of Code for Styling HTML Headings

In any of these headings, a Web developer can insert an


inline sub-heading using the . small class. An inline
sub-heading allows displaying secondary text in smaller
size and lighter color. Code Snippet 4 shows the use of
.small class.

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

Code Snippet 4:
<div class="container">
<h1>h1 Text Transformation <smal1>stibord inate textc/smallx/h 1>
<h2>h2 Text Transformation <small>subordinate text</smal lx/h2>
<h3>h3 Text Transformation <sma11>snbordinate text</smallx/h3>
<h4>h4 Text Transformation <smal1>subordinate text</smallx/h4>
<h5>h5 Text Transformation <smal1>subord inate textc/smallx/h5>
<h6>h6 Text Transformation <smal1>subo rd inate text</smal lx/h6>
</div>
Figure 5.15 shows how .small class renders its style.

h i Text T ra n s fo rm a tio n subordinate text

h2 T e xt T ra n s fo rm a tio n subordinate text

h3 Text T ra n s fo rm a tio n subordinate text


h4 Text Transform ation subordinate text
h5 Text Transformation subordinate text
h6 Te xt Tran sfo rm a tio n subordo^te sex:

Figure 5.15: Usage of small Class

5.4.2 Highlighting, Abbreviating, and Referencing Text


Bootstrap also styles the <mark>, <abbr>, and <blockquote> elements of HTML. Figure 5.16
shows how it styles these elements.

1 <!DOCTYPE html>
2 E <html lang»"en">
3 []<head>
4 <meta char3et«"utf-8">
5 <meta name="viewport" content*"width=device-width, initial-scale=l">
6 <link rel="stvlesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap .min.css">
7 <script 3rc="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
8 <scriDt src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"X/script>
9 -</head>
io []<body>
li E1<mark>
12 G]<div class*"container11>
13 <hl>Highlighting Text</hl>
14 <p>Mark element is used to <mark>point-out</inark> specific section</p>
15 -</div>
16 E]<abbr>
17 El<div class="container">
18 <hl>Abbreviations</hl>
19 <p>The abbr element is used to mark up an abbreviation or acronym:</p>
20 <p>The <abbr title*"Indian Space Research Organisation">ISRO</abbr> was founded in 1969.</p>
21 </div>
22 E]<blockquote>
23 E]<div class="container">
24 <h1>Blockquotes< /h 1>
25 <p>The blockquote element is used to present content from another source:</p>
26 ] <blockquote>
27 [] <p>The Indian Space Research Organisation is the space agency of the Government of India
28 headquartered in the city of Bengaluru</p>
29 <footer>From ISRO's website</footer>
30 </blockquote>
31 -</div>
32 -</body>
33 -</html>

Figure 5.16: Code for Highlighting, Abbreviating, and Referencing Text in Bootstrap

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

In figure 5.16, the codes uses the <mark>, <abbr>, and <blockquote> as Web developers use
them in a standard HTML file. Figure 5.17 shows the output.

Highlight Text
U se the mark elem ent to highlight text

Abbreviations
| Wto.Sp««to««d.0.9«ft<licn [ ^ ^ ^ Mm W <m.
T he ISRO w as founded in 1969

Blockquotes
The blockquote element is used to present content from another source:

The Indian Space Research Organisation is the space agency of the Government of India headquartered In the city of Bengaluru
— From iSRCXs website

Code covering Mar1< Abbreviations Blockquotes_______________________________________________________________________________________

Figure 5.17: Output of Code for Highlighting, Abbreviating, and Referencing Text in Bootstrap

In figure 5.17, the output shows the highlighted text that is in the <mark> tag. It highlights the text
using a background color, which is in a different shade than in HTML.

Similarly, the text in <abbr> is displayed with a dotted underline, unlike in HTML. When the user
scrolls over the abbreviation, the full form given in the title attribute is displayed. Unlike in HTML,
Bootstrap shows the help cursor when the user points it to the underlined text. The help cursor is a
standard cursor with a small icon of question mark.

The text in <blockquote> is referenced by the text mentioned in <footer>. This is different
from the standard HTML output wherein there is no footer.

5.4.3 Styling Description Lists, Inline Code Snippets, and Keyboard Input Text
Bootstrap also styles the <dl>, <code>, and <kbd> elements of HTML. Figure 5.18 shows how it
styles these elements.
< I'DOCTYPE htsl>
2 3<htral lang-"en">
3 l<head>
4 <meta choraet-”utf-8”>
5 <neta name»"vie«port" content»"width-device-width, initial-scale-l">
6 <link rel-" style sheet” href-"bttps://mAX<2dnb»9ts.ttajM;da,.59a/k9».ti.tj:QpZ2a.3,7/csi/be.<?.ta.ti.fl$uaiii2-ess">
7 o c r i p t arc-"httj?a;//fti^-.ac^lciUJiaj.eGn/aiflLx/liha/isiuery/S.2.0/jouery >nvi.Q.i a " x / a cript>
<acrict src«"httD* ://naxedn .boots traDcdn.con/boo ts trao/3.3. 7/is/bootstrao.min. ■is"X/script>
9 -</head>
10 3<body>
n ]<dl>
12 3<div claas«"container”>
13 <hl>Description Listing</hl>
14 3 <dl>
IS <dt>lndia</dt>
16 <dd>- A country</dd>
17 <dt>Asi«</dt>
16 <dd>- A Continont</dd>
19 </dl>
20 </div>
21 ]<div claas-"container">
22 <hi>Keyboard Inputs</hl>
23 <p>To show which control is to be entered through keyboard, place them in kbd tag</p>
24 <p>li a e <kbd>etrl ♦ *</kbd> to undo</p>
25 </div>
26 j<div cl&aa-"container">
27 <hl>Code Kighlighting</hl>
23 <p>Code elements which are to be highlighted, place them in code tag</p>
23 <p>The following oops attributes: <code>elass</code>, <code>variable</code>, and < code >dynamio</code > specifies keyword in Java, C#</p>
30 ■</div>
31 J<kbd>
32 </body>
-</html>

Figure 5.18: Code for Styling a Description List, Inline Snippet, and a Keyboard Input

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

Figure 5.19 shows the output.

Description Listing
India
- A country
Asia
- A Continent

Keyboard Inputs
To show which control is to be entered through keyboard, place them in kbd tag

Use to undo

Code Highlighting
code elements wmcn are to oe nignngnted, place tnem in code tag

The following oops attributes: c la ss, variable, and dynamic specifies keyword in Java, C#

Figure 5.19: Output of Code for Styling a Description List, Inline Snippet, and a Keyboard Input

In figure 5.19, Bootstrap styles the <dl> element and its content by applying the bold style to the
content in <dt>. This is something that HTML does not do. Similarly, unlike in HTML, Bootstrap
highlights the text in <code> by giving it a background color. It also changes its font, which is visible
even in a standard HTML output. Similarly, the keyboard input text in <kbd> gets a new font, black
background color, and white text color. In HTML output, only the font is changed.

5.4.4 Transforming Text Through Text Transformation Classes


Bootstrap provides three text transformation classes for changing the case of text in components,
which are as follows:

• .text-uppercase: Renders each letter in a text in upper case.


• .text-lowercase: Renders each letter in a text in lower case.
• .text-capitallze: Renders a text in which the first letter of each word is in upper
case.

Figure 5.20 shows how to use these classes in Bootstrap.

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

1 < ! DXIYPE hO lQ
2 EKhtml lang="en">
3 <head>
4 <title>Bootstrap Example</title>
5 <meta charset="utf-8">
6 <meta name="viewport" content="width=device-width, initial-soale=r'>
7 <link rel="stylesheet" href="https://maxcdn.bootstrapodn.com/bootstrap/3.3.7/css/bootstrap.min.css">
8 <script 3rc-"https://aiax.crooaleapis.com/aiax/libs/iquerv/3.2.0/iquerv.!nin.is"></3cript>
9 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/is/bootstrap.min.is"X/3cript>
10 -</head>
11 |<body>
12
13 [<div cla33="container">
14 <p clas3="text-lowercase">CONVERT IN TO LOWERCASE.</p>
15 <p class="text-uppercase">convert in to uppercase</p>
16 <p class="text-capitalize">capitalise me.</p>
17 </div>
18
19 </body>
20 L</html>

Figure 5.20: Code for Using Text Transformation Classes

In figure 5.20, the text transformation classes are used within <p> tags.

Figure 5.21 shows the output.

convert in to lowercase.

CONVERT IN TO UPPERCASE

Capitalise Me.

Figure 5.21: Output of Code for Using Text Transformation Classes


5.5 Responsive Web Designing in Bootstrap
Bootstrap uses the concept of grids to fit a Webpage properly on different devices for ensuring a
consistent browsing experience. Let's now use the grid system along with some components to
create a simple and responsive Webpage in Bootstrap.
Figure 5.22 shows a responsive Webpage that uses predefined grid classes and components such as
navbar, jumbotron inside a container, and footer.

V1 .0© APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

feutlSj
R < h t « l lsn g »"e n “ >

< neta c h * r n t » * u t £ * 8 , >


< M t t http- eq\»iv»"Z- UA- Co«patlblo" co 6 '.*nt«*IE-<wl 9 o M>
<®eto n * » e » “ v ie w p o r t * c o n te n t - 'w id t h - d o v ic o 'ir id th . in i t ia l- a c a le - l“ >
clink rel--atylo»heef .-,rg?-"b,tVg«://najrednJfe^Attags^»jCflnlfcaa.£» U w > / 3 .3,.7/c j j c o p .nJia..caa" integrity-
"»ha384 BVTiiSireKldOvTRAfcycuKAMRg32<>*i.>cww7on3RYdg4Va*:P,
nSTs*/K6#vbdElh4u* cross or igir.-■'anonyr*o«j»->
c l i n k ro i- "sty lesh oet- h r o f - " t a t p j ^ / / n < ^ ^ .b g g t a U f l g c d n ., c q n / b g g t A U A g /3 «jL ,.J iflll/J ^ U L U J iP .lU lfla C .ia X D ...C M " inte gr ity-
Msh a3 84 -rHyoKliRaV/V4nDI>JutlnGaslCJuC7tjw}<HiH$»SVrLvRTooPp2b»fYg*gJ<}l/wl/sp* cro ss o r ig in »"an o n y r*o u »">

<s c r i p t s r c » " h t t g « ; //n t t X « ia iiK K > L » lm K 2d a ^c < e i/iK K > taU A p/ia 3 * 1 / j a / h o Q U U f l g . n l n . in te g rity
" »h a 38 4 -To51 Qlb0?7<jvy ) SMf M JOMaLk £UWVxZxUPnCJA71 ?nCWN IpG?HOCX>8 wON! c POT T ita “ c r o ss o r ig i n « " a n o n y r * o u a "X /s e r i p t >
• < /h « * d >
3< b o d y >
■;<n«v i l ^ 'n y H a v b A r ' c l t » * ’ n a v b «r navbar- d e f a u l t nav b ar * in v e r s e n avb ar- fixe d- top" ro le- "navl< ;ation“ >
< d iv c l a * » * " o o n t a i n « r ’ >
< d iv class-*navbar- header~ >
cfcuttcn t y p e »*b u tt o n * c l a » ••"n a v b a r - t o g g l e * d e t a - t c g g le «,-c o l la p s e " data- targe?- *#navberCol lapse~>
Csp-an c l a s s - " s r -only"> T o g g le n a v i g a t io n < /s p *n >
cspen c l a s s « " i c o n ~ b a r * x / « p a n >
if <span c l a S 3 » " i c o n - b a r * X / ’»pan>
< »p en c l s s s » " i c o n - b a r * x /a p e n >
:: < /b u t to n >
<a c la * F»"rvavbar-brand” h r * f » “ #~> W eb»ite c r e a t e d w it h D o o t s t r a p C /a >
:: < /d iv >
?4 <!- - C o lle c t the nev l i n k s , form s, an d o t h e r c o n t e n t fo r t o g g lin g *->
fS E < d iv c l a 9 s- 'co l la p s e nav b ar - c o llap s e * id » *n a v b a r C o lla p s e *>
;* 0 <ul c l s s s » " n a v navbar-nav*>
< l i c l * » a - * a c t i v e " X a h r e f * * " t a r g e t « * _ b l a n k " > H o e * e < /a X /l i >
< l i x a h r e f*"" t i n * * .* ’ b l a n k "> A b o u t < /s x /l i >
< l i X a h r e f- "" t * r g e t « “ _ b l a n k " > C o n t * c t c / a X / l i >
>5 < /o l>
< /d iv»
c/div>
</aar>
•;<dit cla»t**oo«tainer*>
*] <dif e l»tt«‘ )(fibolroD’ >
<h;>8esponslve Mebslte</hl>
<pxa blank*X/a>Kesp©nsive treb design la a process of designing and building websites to provide better
accessibility and optimal viewing experience to the uaer. </p>
<p><i tsi ;«*.»* blank* >.1 »■>.*-"bln btn-swocess btn- lg">Laarn M ore< /aX /p >
</div>
<div clsss-"ro*“ >
<div cl»J»«’ c « l - w 4 ool wd 4 ool*lg-?">
<h2>Jte*otre<K^h2>
<p>A )w b o t r o « indicates a big box for calling extra attention to scne speolal content or information. A )v*>botron is displayed
aa a grey boa with rounded corners. It also enlarges the font sices of the text inside it.< /p>
</di*>
<di» eie 9**“eol-a»-6 ool-r*d-4 col-lg-2” >
Ch2>Xevigetor</h2>
<p>A navigation bar is a navigation header that la placed at the top of the pege</p>
</div>
<(U» cla»*«”clearfix vlsible-sn-blockax / d i v >
<div clas*«~col-sn-4 ool-wd-4 col-lg-?'>
<h*>Headar</h2>
<p>A page header is like a section divider. The .page-header class adds a horizontal line under the heading (♦ adda sone extra
space * round the ele»ent)</p>
</div>
<div clasr«*clearfix vlslble*nd-blocfc"X/div>
<4iv e:»«ss~eol*s>i*6 ool*nd*4 eel*lg*?*>
<h2>Badges</ fuj>
<p>Dadges are numerical indicators of how many items are associated with a link</p>
</dit>
<hr>
<div clstj»*row*>
0 <div cl«»s-*ool-«-12“>
u £ < fo o te r>
<p>footer Text</p>
41 i <^f©ot*r>
*5 I </div>
« » </diT>
r -</diT>
I! -</body>
(1 •

Figure 5.22: Bootstrap Code for Responsive Webpage

In figure 5.22, the code creates a default navbar containing Home, About, and Contact links.
Then, it defines a container holding the jumbotron component with a large, successful-style button.
These button attributes are as per the btn-success and btn-lg classes. Inside the container,
.row class creates a row that is split into four columns. The value col-sm-6 col-md-4 col-
lg-2 for each of the four columns spans across 12 columns (6 + 4 + 2). These numbers represent a
portion of the total width of a div. In other words, col-sm-6 spans up to 6 columns out of 12,
col-md-2 spans up to 4, out of 12, and col-lg-2 spans up to 2 columns out of 12. Each row
has a header and a paragraph. One more row spanning across all 12 columns defines a footer text.

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

Figure 5.23 shows the output.

1 " V
1
c.‘ C \Appj\R«ponir.t html

Website created with Bootstrap Home About co n ta ct

Responsive Website
R espo nsive w eb design is a process of designing and building w ebsites to provide better accessibility and
optimal view ing experience to the user.

I ' " 1 “e3m, ;o'11

Jumbotron Navigator Header Badges


A jumbotron indicates a A navigation bar is a A page header is like a B adges are numerical
big box (or calling extra navigation header that is section divider indicators or how many
attention to som e special placed a t the top or the The page-header class item s are associated with
contentortnform aiion A page a dds a honzontai «ne a link
jumbotron is displayed a s under the heading (+ adds
a grey box with rounded som e extra sp a ce around
corners it also enlarges the elem ent)
the font siz es or the text
inside it

Footer Text

Figure 5.23: Output of Code for Responsive Webpage

In figure 5.23, out of four columns, the third and fourth one in the row use the . clearf ix class to
prevent uneven wrapping on medium devices. Figure 5.24 shows uneven wrapping on medium
devices.

Website created with Bootstrap H om e About C ontact

atte n tio n to s o m e sp e cial c o n te n t o r inform ation A a t th e to p of th e p a g e


ju m b o tro n is disp la y ed a s a grey box with ro u n d ed
c o r n e rs it a lso e n la r g e s th e font s iz e s of th e text
inside it Header
A p a g e h e a d e r is like a section divider T h e p a g e -
h e a d e r c la s s a d d s a horizontal bne u n d e r th e h ead in g
(+ a d d s s o m e ex tra s p a c e a ro u n d th e e le m e n t)

Badges
B a d g e s a re num erical indicators of how m any item s
a r e a s s o c ia te d with a link

F o o te r Text

Figure 5.24: Output of Code for Responsive Webpage

Figure 5.25 shows how . clearf ix class organizes the content on a medium-sized device.

W e b s ite c r e a te d w ith B o o t s tr a p Home About Contact

Jumbotron Navigator
A jumbotron indicates a big box for calling extra A navigation bar is a navigation header that is placed
attention to som e special content o r information. A at the top o f the page
jum botron is displayed as a grey box with rounded
com ers, it also enlarges the font sizes o r the text
inside it.

Header Badges
A page header is like a section divider The page Badges are numerical indicators o t how m any eems
header class adds a horizontal line under the heading are associated with a link
adds som e extra space around the element)

Footer Text

Figure 5.25: Output of Using clearf ix on Medium Devices

V1.0 © APTECH LIMITED


Developing Responsive Websites with Bootstrap and jQuery

In figure 5.22, the third and fourth columns in the first row also use the . visible-sm-block
and . visible-md-block classes. Well, these are responsive utilities useful for showing the
content through media queries as per the targeted device. The . visible-sm responsive utility
makes the content visible on small devices. On the other hand, . visible-md ensures the same on
the screens of medium devices. The block part displays the style of display:block (CSS
property). Similarly, there are . visible-xs and . visible-lg classes. A Web developer can
use one or more of these utilities for toggling content across different viewport breakpoints defined
by media queries.

Figure 5.26 shows the output on a small device in absence of . visible-sm-block.

Website created with Bootstrap Home About Contact

A jumbotron indicates a big box for calling extra A navigation bar is a navigation header that is placed
attention to some special content or information A at the top of the page
jumbotron is displayed as a grey box with rounded
corners. It also enlarges the font sizes of the text
inside it.

Header
A page header is like a section divider The page-
header class adds a horizontal line under the heading
(+ adds some extra space around the element)

Badges
Figure 5.26: Output on a Small Device in Absence of .visible-sm-block

Figure 5.27 shows the output on a medium device in absence of . visible-md-block.

Website created with Bootstrap Home About contact

Jumbotron Navigator
A jumbotron indicates a A navigation bar is a
big box for calling extra navigation header that is
attention to some special placed at the top of the
content or information. A page
jumbotron is displayed as
a grey box with rounded
corners. It also enlarges
the font sizes of the text
inside it.

Header
A page heaaer is like a
section divider The
page-header class adds

Figure 5.27: Output on a Medium Device in Absence of .visible-md-block

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

Quick Test 5.1

1. There can be unlimited rows as well as column in a Bootstrap layout.

True
False

2. Bootstrap allows capitalizing all letters in a text.

True
False
Developing Responsive W ebsites with Bootstrap and jQuery

5s- A responsive layout adapts its user interface components and perhaps even functionality to any
screen size on its own.

> A responsive Website adapts its layout to the viewing screen using three elements namely, fluid
grids, flexible multimedia, and CSS3 media queries.

> Bootstrap 3 mobile first technology allows the code to focus first on smaller screens and then,
expand for fitting on larger screens.

> A grid in Bootstrap is a collection of HTML/CSS components that enable a Web developer to
structure a Website and insert its contents easily in the intended locations.

> Bootstrap provides only up to 12 columns for a Webpage regardless of the viewport, but can have
unlimited rows.
>■ The grid system consists of a series of containers, rows, and columns for designing a layout and
aligning its content. The container element covers the content by setting the margins on the left
and right.
>- Bootstrap offers four predefined classes namely, xs, sm, md, and lg for designing responsive
layouts quickly as per the targeted devices.

>■ The jumbotron component allows increasing the size of heading and other text for grabbing quick
attention of visitors.
> Inserting jumbotron inside a <div> tag prevents it to extend up to the edges of the screen, while
placing it outside extends it up to the edges.
> Bootstrap offers . h 1 to . h6 classes for styling heading text and accommodating inline text.
>■ Bootstrap provides .text-uppercase, .text-lowercase, and . text-capitallze
classes for transforming the case of words in any piece of text.
Developing Responsive W ebsites with Bootstrap and jQuery

Check Your Progress

1. Which of the following values of the class attribute in div class will result in three columns spanning
up to 12 columns in a row?
a .co l-x s-5 ,.co l-x s-4 ,.co l-x s-5
b .co l-x s-5 ,.co l-x s-5 ,.co l-x s-2
c .c o l-x s -4 , . c o l- x s -4 , . co l-xs-2
d. None of these
2. Which of the following statements is true about a responsive layout in Bootstrap?
a. It has predefined classes.
b. Columns tend to hold the content.
c. It comes with media queries for hiding content as per the viewport's size.
d. All of these.
3. The . c o l - m d - * class targets_____________ .
a Medium devices of size 1000 pixels and up
b Medium devices of size 950 pixels and up
c Medium devices of size 900 pixels and up
4. The jumbotron component can extend over___________ .
a. Any element
b. whole viewport
c. Any text
d. Modal
5. Which of the following elements allows adding an inline text in a .h i header?
a . < s m a l l>
b. < a b b r>
c . < d l>
d. None of these
Developing Responsive W ebsites with Bootstrap and jQuery

Answers to Check Your Progress


1. col-xs-5, .col-xs-5, .col-xs-2
2. All of these
3. Medium devices of size 992 pixels and up
4. whole viewport
5. <small>

Answers to Quick Test


Quick Test 5.1

1. False
2. True
Developing Responsive W ebsites with Bootstrap and jQuery

SESSION 6-Creating Responsive Webpages


Using Bootstrap and jQuery
Session Objectives:
This session introduces the role of media queries in making a Bootstrap Webpage responsive. It also
explains how to use Bootstrap tables and wells for organizing the content with the desired custom
styles. The session also describes how to customize Bootstrap by overriding its default CSS and how
to use both jQuery and Bootstrap for making dynamic Webpages.

At the end of this session, you will be able to:

> Describe the role of media queries in achieving responsiveness in Bootstrap


> Understand the use tables in Bootstrap
> Understand the use tabs in a well in Bootstrap
> Describe how to customize Bootstrap
> Explain how to create a Website using Bootstrap and jQuery

6.1 Role of Media Queries in Responsive Layouts


A media query defines a style rule for displaying a Webpage on a specific type of device (media)
without changing the markups. It helps in adding responsive CSS to a Bootstrap application. In CSS2,
it allows specifying styles for computer screens, TV-type gadgets, handheld devices, and printers. In
CSS3, media queries extend the concept of CSS2 media types. They now focus on the characteristics
of the targeted media instead of focusing on its type. The queries are useful in determining the
device type displaying a Webpage as well as its physical properties, which are:

• Viewport's and device's width and height


• Screen resolution
• Orientation such as portrait or landscape display

Using media queries allows rendering a custom style sheet on a tablet, Android phone, or iPhone. In
short, they help in rendering a device-specific style sheet. Visibly, media queries define the
breakpoint for the media's width from where the layout changes on a specific screen. The
breakpoint is the pixel width at which the Webpage's layout needs to adjust for a better display on
the targeted screen, as shown in figure 6.1.

Figure 6.1: Effect of a Breakpoint on a Mobile Screen

V1 .0© APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

<!D0CTYPE htsl>
2 B<htad lang-"en">
|<head>
<raeta charflet«"utf-8">
<meta name»"viewport" content»"width»device-width, initial-scale"l">
<link rel»"stylesheet" href ■"https://maxcdn.bootstrapcdn.con/bootstrap/3.3.7/css/bootstrap.nln.css,,>
<script 3rc«"https://ajax.googleapis.com/ajax/libs/jquery/3■2.0/jquery.min.js"X/3cript>
<script src-',http3://maxcdn.boQt3tEai?cdn.co!n/bQotstrap/3.3.7/1s/boot5trap.mn.is',></9cript>
■</head>
10 9 <style>
body {
background-color: lightyellow;
)
9media only screen and (min-width: 768px) (
body (
background-color: lightpink;
}
)
</style>
21 -</head>
22 El<body>
<p>Rescale the browser window. Lightpink is displayed when width of the screen is 768px and lightyellow is displayed in other cases.</p>
24 L</body>
25 </htal>

Figure 6.2: Code for Using a Mobile-first Media Query in Bootstrap


In figure 6.2, the @media attribute contains a media type value set to screen and a media query
or expression within parentheses. This query is a logical expression for checking whether the width
of the user's current screen is less than or equal to 768 pixels. It displays the background in light
yellow when the width is less than 768 pixels and light pink when it is 768 pixels or beyond.
Figure 6.3 shows the output on a small device.

R e sc a le the browser window. Lightpink is displayed when width of the scre e n is 768px
and lightyellow Is displayed in other case s.

Figure 6.3: Output of Mobile-first Media Query on a Small Device


Figure 6.4 shows the output on a large device.

Figure 6.4: Output of Mobile-first Media Query on a Large Device


Instead of changing styles, once the width becomes smaller than 768 pixels, Web developers change
the layout and once the width becomes bigger than 768 pixels. This is how this Webpage renders
quickly on a mobile device, as the processing of media query takes place only on wider screens.

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

A Web developer can include styles for different devices within a single Webpage. Each of these
styles has its own media queryfor displaying the Webpage differently as per the changing
resolutions.

Usually, specifying three blocks of ©media attribute is common: One for mobile phones and tablets
(sm), one for lower-resolution desktops (md), and one for higher-resolution screens (Ig). The code in
figure 6.2 would apply the light pink background color to all devices having a resolution greater than
768 pixels. So, this is an ideal example of how to have a single block of style for devices with bigger
screens.

A Web developer can also deliver a device-specific style sheet using a media query. Code Snippet 2
shows how to do so.

Code Snippet 2:
clink. rel="stylesheet" media="screen and (max-width: 768px)”
href="mobile-devices.css">
clink rel="stylesheet" media="screen and (min-width: 768px)"
href="large-devices.css">
This is how you can add a style sheet link for each device type to a Webpage, each with its own
media query. The style sheet in Code Snippet 2 would be used on all devices having a resolution
smaller than 768 pixels. Thus, this is an ideal example of how to target mobile and tablet devices
with a single style sheet, and large devices such as desktops with a different style sheet.

6.2 Tables in Bootstrap


An HTML table displays data in a grid layout that consists of rows and columns. Bootstrap helps in
improving the appearance of an HTML table by providing built-in CSS classes. A basic Bootstrap table
features distinct appearance in terms of only horizontal splitters and slight padding of 8 pixels. For
applying this basic style, Bootstrap offers the . table class.

Figure 6.5 shows the basic Bootstrap table.

£ • C 1£ C •;

Basic Bootstrap Table


F irstnam e Lastnam e City

Stella Mark smark@example.com

Josie Fernandes josief@ example.com

Jack Doe jdoe@ example com

Figure 6.5: Basic Bootstrap Layout

Bootstrap provides a clean layout for creating a table. Table 6.1 lists the table elements that
Bootstrap supports.

Element Description
ctable> Is a wrapper for displaying data in rows and columns.
cthead> Is a container holding the table's column headers in single or

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

Element Description
multiple <tr> tags.
<tbody> Is a container holding the table's body in single or multiple <tr>
tags.
<tr> Is a container defining a row, which holds one or more table cells
created through <td> or <th>.
<td> Is a standard table cell with text that is left-aligned.
<th> Is a special cell having header data that is middle-aligned and bold. It
exists only within <thead>.
<caption> Describes a caption for a table or a summary of what the table has. It
must come immediately after <table>. Only one caption can exist
in a table.
Table 6.1: Supported Table Elements

The standard order of table tags is <table> -> <tbody> -> <tr> -> <td>. In case of
column headers, the order shall be <thead> -> <tr> -> <th>.

6.2.1 Striped Rows in a Bootstrap Table

A Web developer can create a table with alternate rows having a background color differing from its
previous one. It gives an appearance of zebra stripes. To give this effect to a table, Bootstrap offers
the . table-striped class, which a Web developer needs to add to the . table base class.

Figure 6.6 shows the code for creating a table with striped rows.
< ! DOCTYFE h t x i>
: B<htxnl l«n9«MenM>
3 R<head>

Cneta naae>**viewport" cont«nt«”width~de vice-width, initial-»oale-l">


clink rel-"*tylo»he«t- href-"httB»i//jwutc<ilnJag.g.t»tiaggdn.<i9n/ll>Bg t»txag/3..3....7/g»»/teffgJJtxap.,.i3iD..ca»"
O c r i p t »rc»"httga;//ala&..<n>c8lgflgi»...gca/tt3<m/jLU«/jgu<iry/3..2.0/lguoxy .ain.l»"x/acript>

f
1C
\ <acript atc-"h t t m : / / M x c d n . boot»trapodn.c<m./bopt»trap/3 ■3.7/W b o o t j t r a n . rain. 1a"X/acript>
</h«ad>
^3<body>
:i B<C«blt claa»«“table table-»triped~>
12 f-J <thead>
<tr>
N <th>«l no</th>
<th>Car Narve</th>
<th>Manufacturer Narve</th>
<th>Y«ar r%anufactur«d</th>
</tr>
> |* </thaad>
<tbody>
2: Q <tr>
<td>l</td>
2! <td>Swift</td>
<td>Harutl</td>
2$ <td>2008</td>
</tr>
0 <tr>
2« <td>2</td>
<td>Polo</td>
<td>VolksHagon</td>
<td>2009</td>
</tt>
<tr>
<td>3</td>
<td>Du»t«r</td>
<td>ftenault, c/td>
<td>2012</td>
</tr>
</tbody>
</tabl#>
</body>
</html>

Figure 6.6: Code for Table with Striped Rows

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

In figure 6.6, the value of class in <table> is set to table table-striped. This transforms a
basic Bootstrap table into a striped format.

Figure 6.7 shows the output.

Figure 6.7: Output of Code for Table with Striped Rows

6.2.2 Bordered Tables

By default, a Bootstrap table only has horizontal dividers. This means that there are only horizontal
borders. However, Bootstrap enables adding borders on all sides of a table. It does so by offering the
.table-bordered class, which should be added to the base class.
Figure 6.8 shows a table with a border on all sides.

Bordered Table
Firstname Lastname Email

Stella Mark smark@example.com

Josie Fernandes josief@example.com

Jack Doe jdoe@example com

Figure 6.8: Table with a Border on All Sides

6.2.3 Hover Effect on Rows

Bootstrap allows Web developers to apply a hover effect to table rows. The row on which a user
moves the mouse shows a gray background. To apply a hover effect, Bootstrap offers the . table-
hover class, which should be added to the base class.
Figure 6.9 shows a table with rows showing the hovering effect.

Hover Effect on a Table


Firstname Lastname Email

Stella Mark smark@example.com

Josie Fernandes josief@example.com

Jack Doe jdoe@example.com

Figure 6.9: Table with Hovering Effect on a Row

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

6.2.4 Condensed or Com pact Tables

Bootstrap allows making a table more condensed by reducing cell padding by half. This saves space
around the cells. To make a table more compact, Bootstrap offers the . table-condensed class,
which should be added to the base class.

Figure 6.10 shows a compact table.

Compact Table
Firstname Lastname Email

Stella Mark smark@example.com

Josie Fernandes josief@example.com

Jack Doe jdoe@example.com

Figure 6.10: Compact Table

6.2.5 Emphasis on Table Rows

Bootstrap offers a few contextual classes for emphasizing a cell or a complete row. They indicate
success, warning, info, or danger by changing the color of the background of a row or a cell. Table
6.2 lists the contextual classes, which are also known as <tr>, <th>, and <td> classes, as they
color the cells or rows.

Contextual Background Description


Class Color
.active Gray Applies the hover color to a cell or row.
.success Green Denotes a successful action.
.info Blue Denotes informative text or neutral action.
.warning Yellow Denotes a warning to grab quick attention.
.danger Red Denotes a harmful action.
Table 6.2: Contextual Classes for Tables
Figure 6.11 shows how to use contextual classes in a table.

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

<l9ocrot &»;>
2 >
:• £ < h e «d >
< <m u charNta*utf*l*>
< « :• v ie w p o r t " co nt*nt- “ w ldth- dow ic«- w idth, i n i t i a l - * e * l c - l *>
<1 ink r * l » "* t y l e » h « « 5 t * h r « f » * h t t p » ; //r**Kodr>. b o o t a t r a p o d n . o o n /b o o t » t r a p /3 ■3 ■7 / c » » / b o o t at r a p , n l n . c » » ">
oerlpt ’ rc-'huatijiyal»x.ass>ala*BlM. sco/iiu JlU itliv u tp iiJJiJtJlX M n . a U . ^»~x/»cript>
<»cript >rc-'htt8»://nMgiln.taittum»«iii.ca8'/bgamj:»»/3J3J2/jj/l?ggt»un>.i3jLa.3»*x/»eript>
- < /h «*d>
<body>
< div cl»»a**b »- «x«y ^ > lc ">
< t « b l « c l * « r » "t a M « » * >
< tk M d >
<tr>
<r.h>Tra(fio Signals >1 no:</th>
< th > Co lor< /th >
<th>St*tu*</th>
</tr>
< /t h M d >
<tbody>
21 ft < tr c l « » » * " * u c c « » * * >
<td>l</td>
;j < t d X J r *« n < /t d >
< td > F r«e to 9 < x /t d >
}S < /t r >
•< P- < tc c l * » » « " w » m l r * g * >
< td > 2 < /td>
< t d > T o llo »< /t d >
<t d>K a 11 fo r Cre«n<-'Cd>
< /t r >
Ji L < tr c i * 5 ? » “ <Un«jor">
13 < td > 3 < /t d >
<td>Jtod</td>
3« < t d > S t © j X /t d >
J» </«>
</tfeody>
31 < /t a b l « >
!• - </div>
3» -</b©4y>
4: ^ < /h t m l>

Figure 6.11: Code for Using Contextual Classes in a Table

Figure 6.12 shows the output.

Traffic Signals si no: Color Status

1 Green Free to go

2 Yellow Wait Tor Green

3 Red Stop

Figure 6.12: Output of Code Using Contextual Classes in a Table

6.2.6 Responsive Tables

In Bootstrap 3, a Web developer can quickly create a responsive table. In other words, Bootstrap 3
activates horizontal scrolling on a small device whose screen width is not more than 768 pixels.
Nevertheless, the same table on other devices with a larger screen will not show any difference.

Bootstrap offers the . table-responsive class for making a table responsive. Figure 6.13 shows
how to create a responsive table.

V1 .0© APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

<{ooenrc itai>
2 p<ht*l
3 "<he»d>
4 <neta chars*:.-”utf-8">
S <n*ta http-*q\iiT-*Z-UA-Cor|>atible’ content-"lE-edgo1^
1 <aeta r.aae-'viowport" content-*width-device-width, initial-scale-l*>
Clink rel-"stvlesb©et" integrity-
"sha384-8VYiiSireKldanJRAkycuMA>{Rg320nUcww7on3RYdg4Va*PnSTsz/K68vbdEjh4u" crossorigin-"anonyr»ous*>
i clink rel-"stylesh«set" hre£-“https://maxodn.bootstrapcdn.con/bootstrap/3.3.7/css/bootstrap-theme.nin.css" integrity-
-sha384-rKyoNliRsV/V4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp?bWYgmgJQlZwl/Sp" crossorigin-"anonymous*>
) Caeript sre»"https: //ajax .googleapis.oom/a^ax/1 ibs/)query/l.12.4/jquery .min.ji*X/script>
10 <script src-"https ://maxcdn.bootstrapcdn. con/boot strap/3.3.7/^s/bootst rap.min. }s" integrity-
"ah*384-Tc5lQib027<pryj$MfH)CKaLkfuHVx2xVPnCJA71?nCWIpC9nOCl>8wCNIcro7Txa" cro9»origin-'anonynou*“X/*cript>
•</he«d>
’<body>
13 ><div clasn-"bs-ex.vmple">
3 <div class-”table-responsive->
~ <table class*"table cable-bordered">
It <thead>
17 3 <tr>
1! <th>Rotr</th>
:» <th>Course NaneC/th>
2: <th>Developed Byc/th>
21 <th>Pr«faoe</th>
22 </tr>
23 </th*ad>
2* <tbody>
;s <tr>
24 <td>l</td>
2? ctd>Javac/td>
21 <td>Janes Gosling</td>
2) <td>Java was originally developed by Janes Gosling at Sun Microsystems and released in 199$ as a core oonponent o£ Sun
Microsystems' Java platfom.</td>
<tr>
32 <td>2</td>
33 ctd>Rubyc/td>
H <td>Tukhiro Mat*</td>
35 <td>Ruby is a dynamic, reflective, object-oriented, general-purpose programing language. It was designed and developed
in the aid*1990s by Yukihiro "Katz* Hatsumoto in Japan.</td>
}C </tr>
37 <tr>
31 <td>3</td>
)> <td>Python</td>
<0 CtdXJuido vaan RossiriC/td>
4'. <td>Python was conceived in the late 1980*, and its implementation began in December 1989 by Guido van Rossvm at Centnw
Hiskunde i Infomatica (CHI)</td>
12 </tr>
<3 </tbody>
(I </t*ble>
4S </div>
4f </div>
47 •</body>
4! -c/ht*l>

Figure 6.13: Code for Creating a Responsive Table

In figure 6.13, the <div> tag has . table-responsive class to make the table responsive. With
it, another <div> tag is defined with the . table-bordered class, which is added to the base
class. This gives a border on all sides of the responsive table.

Figure 6.14 shows the output on a small screen having a horizontal scroll bar.

I d C\Appt\T«b4w.ttfml______ P ~ C | 3 C:\App»\T*bWrKml

-l
R ow C o u rse Name D e ve lo p e d By Preface

1 Java James Gosling Java was originally develop

2 Ruby Yukhiro Matz Ruby is a dynamic, reflectiv

3 Python Guido vaan Rossum Python was conceived in th


< tmtm ► -

Figure 6.14: Output of a Responsive Table on a Small Screen


Figure 6.15 shows the output on a big screen.
Course
Row Name Developed By Preface

Java James Gosling Java was originally developed by James Gosling at Sun Microsystems and released in 1995 as a core
component of Sun Microsystems' Java platform

2 Ruby Yukhiro Matz Ruby is a dynamic, reflective, object-oriented, general-purpose programming language It was designed and
developed in the mid-1990s by Yukihiro "Matz" Matsumoto in Japan.

3 Python Guido vaan Python was conceived in the late 1980s and its implementation began in December 1989 by Guido van Rossum
Rossum at Centrum Wiskunde & Informatica (CWI)

Figure 6.15: Output of a Responsive Table on a Big Screen


6.3 Customizing Bootstrap
Twitter Bootstrap is now a popular CSS framework for developing Web applications, as it saves much
time of Web developers. However, most developers do not make adequate efforts to customize
their Bootstrap sites. This results in similar looking Bootstrap Websites.

In fact, it is easy to make a Bootstrap Website stand out from using a few premium themes. These
themes do not retain the defaults; they contain custom components. Instead of paying for these
premium themes, why not put some effort to customize a Website and make it stand apart?

The Official Website of Bootstrap offers a custom builder for generating a personal Bootstrap
package. It also offers the LESS and SASS versions for compiling the CSS file as per the requirements.
However, these options do not suit all Web developers, as it involves tracking all possible changes.
Well, this is an additional as well as a tedious job, especially while upgrading to the latest version.

Instead of messing up with the core files, it is more efficient to override the CSS file to code the
desired styles. This is how a Web developer can also prevent customizations from blending with the
original code. This mechanism of customizing Bootstrap not only prevents deviation from the normal
workflow but also facilitates hassle-free upgradation.

Figure 6.16 shows how to customize Bootstrap by overriding CSS.


Developing Responsive W ebsites with Bootstrap and jQuery

0 < h t a l l*n g » "e n “ >


<ht*d>
<m :« c h » r M '» * u t f - 8 " >
< M U h ttp- e ^ji vA-Cc»-f>atlble“ c o o t e o t » ’ IB - e d g e ^
<m m r.u k « * v i e w p o r t ” c- OGter.t- 'w idtb- devlce- w idth, i n i t i a l - s c a l e - 1 ">
< ii r .x i * : . * » t y i « » h « c r h r o f - " h ^ i ;/ / n A j i o d n .> w ? t « t r f l g g d a « f i g 3 / b o 9 t i U a p / 3 ,3 <
.7 /c < i /b g o i m f t p .,n A n .g « i " i n t e g r i t y
~ s h a 3 8 4 - t > V Y ii$ !r e M c k > v r H A k y c u X A K R g 3 ? O n U c w w 7 o n 3 R Y d g 4 V A *P n S T s 3 /X 6 8 v b d £ )h 4 u * c r o » s o r i g i n * ~ a n o n y ? » u s * >
< i ir.k r o l - 's t y l e s h e e t ’ h r e f ■ * M t p s : / / t v n f y f a . bo o t * t r a p o d n . eo- t/boots t r s p / 3 . 3 . 7 / o s s / b o o t s t r a p - t W » e ? ii n . o » t * i n t e g r i t y
*i)u t 38 4 - r K y o M liR a V /V ln D O J u t In G a ilC J u C 7u w Jd u t(9 &V rL v )lT o o r|> ?b ir T q n 9JQ t/u tl/S p ’ e r o i » » r i 9 i n « ' * n o n p o u i >>
<s c r ip t » r c » " h i n ,g i ;//i J m .a g g s J l f l i g i J .c g n /f t i a x /l J J & « /i g w c n r /l > 1 2 .l /A w x Y .n i i i a j j r x /» c r i p t >
< s c r i p t a n . - h r t p i • /A u u t o d n h r o t s t r a p o d n . c o n / b o o t s t r a p / 3 . 3 ^ ? / ) s /b o o t s t r a p .? \ l n . j s * i n t e g r i t y
*sha384- T cS IQ lbO ?7< firy }SM fH )C »«kL kfu M V x£ x U I> nC JA 71?n C K N Ip({9n O C D8w O N toP07Tx a‘> c r o * » 3 r igifi-'a»o<iynous * X / s c r i p t >
$ < » t y l « type- ” t e x t / c s s * >
body (
p w k U iv g : 1Jpx ;
>
table (
bo rder- o ollapse: separate;
bo rd er- spao lo g : 0 ip x ;
>
body (
b ack g ro u nd - co lor: lig h tb lue;
»
P i
a fo nt- fan lly: calib rl;
f o n t - w e ig h t : bold;
n 1
»
thead th <
back ground- color: #006DCC;
co lor: y ellow ;
I
tb o d y td (
back gro und- co lor: > R K R g lZ |
)
tr t d :f ir s t - c h i l d ,
tr t h :f ir s t - c h i l d (
bo rd er- to p- left- rad ius: 6px;
b o rd e r - b o tto n - le ft- r a d iu s : 6px;
1
tr t d :l a a t - c h l l d .
tr t h :l a s t - o h il d (
border- to p- righ t- radiu s: 6px;
b o r d e r - b o t t o n - r i g h t -r a d i u s : 6px;
}
)
» < /h e a d >
u 3<body>
. < d iv -; * • • • ” b s - e x a m f> le '>
H < d i v c l a s s * * t e b l e - r e s p o n s i v e a*>
< t a b l e c l « s s * mt a b l e table- bo rdered*>
17 0 <thead>
<tr>
< th > R o w < /t.h >
< t>.> C ourse N a n e < / l h >
< '.h > D ev e lo p «d B y < /t h >
< t h > P r e f e c e < /t h >
< /t r >
< /t h e a d >
<tbody>
<tr>
< t d > l < /t d >
< td > Ja v a < /td >
< t d x p > j«n s s O o s l i n g < /p x /t d >
< t d> < p> J*v » was o r i g i n a l l y d e v e l o p e d by <J«n«s O o s l i n g at S un H ioro*yst«- »* a n d r e l e a s e d i n 1 M 5 a s a c o re M a p o a e n t o f
S u n H l o r o s f s t e n s ’ Ja v a p l a t f o m . < / p X / c d >
’I <txw>
7J < *r>
< t d > » < /td >
< td > R u b y < /:d >
<td><p>T«khl ro H a t s < / p X / t d >
< fl> - ; •Jtxilty
i s a d y n s n l o , r e f l e c t i v a . o b ) s o t - o r U a t « d , ga n a r a l- p u r p o se programming la n g u a g e . It was d e s i g n e d an d
d a r s l o p s d in t h e n i d ' l M O s b y Y u k i h l r o ’ M a t s " K t t a u n o l o i n J a p a n . < /p > < /t 4 >
</t»>
•* <er>
<td>J</td>
<t d> rython< / 1 d>
< td><pXX>ldo v u n l t o * t i* » < /p X /t d >
<td><p>ryt.*von w sa c o n o s i r s d i n t h e l a t a 1 4 8 0 s , and it s i n p lessen ta t io n be gan i n D s o s n b s r IM 9 b y O u i d o v an Rossis* at
C e n t r u n Misicunde I
In fo m a tlc a (O t I)< /p X /t d >
< /t r >
< /t b o d y >
< /t a b l e >
< /d l v >
■</dlv>
< /b o d y >
-</ht*l>

Figure 6.16: Code for Customizing Bootstrap

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

In figure 6.16, the code overrides the default Bootstrap CSS by defining custom styles for body, p,
and table elements. The : first-child selector selects the mentioned selector, only if it is the
first child of its parent. Similarly, the : last-child selector matches each element that is the last
child of its parent. By retrieving the first and last child elements, we are assigning specific CSS
attributes to different elements.

Figure 6.17 shows the output.

ft ★ $

1 Jav a Jam es G osling Java w a s originally d e v elo p e d b y Ja m es G oslin; a t Sun M icrosystem s a n d re le a s e d in 199S a s a c o te c o m p o n e n t o f Sun M icrosystem s' Java p latform .

2 Ruby Yukhiro M atz Ruby is a d y n am ic, reflectiv e, o b je ct-o rien ted , gen eral-p u rp o se p rogram m ing la nguage. It w a s d e signed a n d d e v elo p e d in t h e m id -19 90 s b y Yukihiro " M at/" M a tsu m o to in
Jap an .

3 Python G uido v a an Py th o n w a s con ceiv ed in t h e la te 1 9 8 0 s, a n d its im p lem e n ta tio n b e g a n in D ecem ber 1 9 8 9 by G uido v a n R ossum a t C entrum W iskund e & In fo rm a tk a (CWI)
Rossum

Figure 6.17: Output of Code for Customizing Bootstrap


6.4 Bootstrap Wells
In Bootstrap, a well is a container component to apply an inset style to a block-level element or
sunken effect to its content. It is useful when a Web developer intends to insert content inside a box
such that it stands apart from the other contents on that Webpage.

To define a well, a Web developer needs to wrap the content with a <div> containing the .well
class. This class applies a rounded border with some padding and a gray background color.

It is also possible to change the well's size by controlling its padding. This is done with the help of
two modifier classes namely, . well-lg and
.well-sm. These optional classes work by
modifying the default padding and size of the
base class, . well. They render a well smaller or
larger depending on the class a Web developer
specifies with the base class. Code Snippet 3
shows the use of the modifier and base well
classes.

Code Snippet 3:
<div class="container">
<h2>Wells</h2>
<div class="well well-sm">SMALL
WELL with reduced padding and
radius</div>
<div class="well">DEFAULT WELL with default padding and
radius</div>
<div class="well well-lg">A LARGE WELL with increased padding and
radius</div>
</div>
Figure 6.18 shows a smaller, default, and larger well.

V l.O © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

SMALL WELL with reduced padding and radius

DEFAULT WELL with default padding and radius

A LARGE WELL with increased padding and radius

Figure 6.18: Wells of Different Sizes

Figure 6.19 shows how to place form controls in a well.


< i :octype fttalg
2 E3<htod lang»"on">
R<h«ad>
<title>Bootstrap Exanple</title>
<aet# charset»”utf-8'’>
<aet« n4ae»"vl«wportH content»Mwidth-<Usvie«*wi<ith< initial-scale*l">
clinX hr«f»-http»://naxc<tn.boot»tr«podn.cor'/boot»trtti>/3.3.7/c»»/booc.»tr«B. win ■<:»»">
<acripe ; //oiaa.gooalBapjL.a^.soa/aiax/JLlba/jgucry/3. 2 . 0 / jg u c t y .n l o ■la " > < / acript>
<script »rc--http»://r*mottn.boot»trapodn.oon/hoot»trap/3.3 . 7 / W boot»tr«p.y>in. '»" X / « c r i p t >
10 •</head>
11 0<body>
12 B < d i v clas3-"well we 11 -sn">
<h3>Login P o m < / h 3 >
14 <hr />
<£or» class»Mform-horizontal~>
<div cla®»-',fortn-group”>
< label i c r-“inputUsorNane" cia-a**’control - label col sn-2H>Usorruime</Ubel>
<div c 1s s »-"g o 1-sm-10“>
<input class*’'form-oontrol" placeholder-"Login Usernarve"
type-"text" id-"inputUserNarve" />
</div>
</div>
<div class»"fojnn-group">
<label for-"inputPassword" claos»Mcontrol-label ool-sr»-2M>Password</label>
<div clasa-"col-sm-10">
<input class-"Corm-control* placeholder»“Login Password"
type***password" id*"inputPassword” />
</div>
</diT>
<div class»"form-groupM>
<div c l * n » “col-fn-of(s«t-2 col-a?n-10H>
<buttor. type»"subcnit" class*"btn btn-default">Login</button>
</div>
</div>
</form>

</htal>

Figure 6.19: Code for Placing Form Controls in a Well

In figure 6.19, the code includes a horizontal form and its controls with a div that contains the
.well-sm class. This means that the form shall appear in a well of smaller size than the default

Figure 6.20 shows the output.

Login Form

U sern a m e Login U scmaine

P a ssw o rd Login Password

Login

Figure 6.20: Output of Code for Placing a Form in a Well

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

In figure 6.20, it is clear that a smaller well features lesser round corners. The text also appears
sunken inside a well.

6.4.1 Tabs in a Bootstrap Well


Let's now see one more example of using wells. A Web developer can put a tabbed interface within
a well to make it stand out from the rest of the content on a Webpage. A tabbed interface contains a
series of tabs, drop-down menus, or a combination of both.

To create a tabbed interface, Bootstrap offers the . nav-tabs class, which should be added to the
.nav base class in <ul>. Figure 6.21 shows how to create a tabbed interface using data attributes
and place it within a well.

<! DOCTYPE hcml>


2 Er!<html lang="en">
3 E:<head>
4 <meta char3et="utf-8">
5 <meta name*"viewport" content="width=device-width, initial-scale=l">
6 Clink rel»"stylesheet" href-"h ttps://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
7 <script src="h t tps://aiax.aooaleapis.com/aiax/libs/iquery/3 .2.0/jquery.min.i s " X / s c r i p t >
3 <scriot src="httos://maxcdn.bootstraocdn.com/bootstrao/3.3.7/is/bootstrap.min.i s " X / s c r i D t >
9 -</head>
10 E ]<body>
11 <br />
12 [ <div class="well well-sm class">
13
14 E <div class-"row">
15 E <div clasa»"col-xs-6">
16
17 [ <ul class="nav nav-tabs">
18 E <li cla3s="active">
19 <a href-"#homeTab" data-toggle»"tab”>Home</a>
20 - </li>
21 [3 <li>
22 <a href="#contactTab" data-toggle="tab">Contact</a>
23 - </li>
24 E <li cla3 3="dropdown">
25 [ <a href="#" data-toggle="dropdown" clas3="dropdown-toggle">
26 Locations <b class="caret"></b>
27 - </a>
28 E1 <ul cla33»"dropdown-menu">
29 <li><a href="#indiaTab" data-toggle="tab">India</a></li>
30 < l i X a href="#usaTab" data-toggle="tab">USA</aX/li>
31 - </ul>
32 - </li>
33 - </ul>
34 [ <div clas3="tab-content">
35 E <div id="homeTab" cla33="tab-pane active">
36 <h3>Home</h3>
37 <p>Home page content</p>
38 - </div>
39 E3 <div id="contactTab" clas3="tab-pane">
40 <h3>Contact</h3>
41 <p>Contact page content</p>
42 - </div>
43 E3 <div id="indiaTab" cla3s="tab-pane">
44 <h3>India</h3>
45 <p>India Location Details</p>
46 - </div>
47 E3 <div id="usaTab" cla3s="tab-pane">
48 <h3>USA</h3>
49 <p>USA Location Details</p>
50 - </div>
51 - </div>
52
53 - </div>
54 - </div>
55 </div>
56 -</body>
57 -</html>

Figure 6.21: Code for Placing a Tabbed Interface in a Well

V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery

In figure 6.21, .well-sm class is used to define a small well in a grid layout defined for extra small
devices. The . nav-tabs class is used to define the tabs in a navbar. There are two tabs namely,
Home and Contact and one drop-down menu named Locations with India and USA in its
drop-down list. For tabs, the data-toggle attribute is set to tab. Similarly, for a drop-down
menu, the attribute is set to dropdown. The . caret class produces a caret arrow icon, which
denotes that the tab is a drop-down menu. The . tab-content and . tab-pane classes are used
to define the content that will be displayed when a user clicks the respective tabs.

Figure 6.22 shows the output.

Home page content

Figure 6.22: Output of a Tabbed Interface in a Well

6.5 Building a Website Using Bootstrap and jQuery


jQuery is used in Bootstrap for designing more robust and dynamic Webpages by extending their
HTML and JavaScript functionalities. It makes it simpler to use and quicker to design Webpages that
are compatible across a multitude of browsers.

Figure 6.23 shows how to design a Webpage using Bootstrap components and jQuery library.
Developing Responsive W ebsites with Bootstrap and jQuery

< IDOCIYPE hc:nl>


;<html lang="en">
;<head>
< m e t a c h a r 3 e t - " u t f -8">
C m e r a naiRe-"viewport" c o n t e n t - " w i d t h = d e v i a e - w i d t h , i n i t i a l - s a a l e = l M>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.coin/bootstrap/3.3.7/css/bootstrap.min.css"
<script 3rc=''https ;//ajax.googleapis.cora/ajax/libs/jquery/3,2,0/jquery.win.js"></script>
< s c r i p t 3rc-"h t t p s :/ /maxed
/maxcdn.b o o t s t r a p c d n . c o m / b o o t s t r a p / 3 .3.7/i s / b o o t s t r a p .nii.ii. 'is"></3cript>
<acript type-"text/javascript"
$ (document).ready(function () {
«C#cMJi'j>rPa?swc: ) .click(function () {
SC 4txtPcrr. _: j ).attrC , $ (this).is (’:checked ’) ? : 'paaav.:_j’);
)>;
14 $ (' input [rare-" language". ') .click(function () (
15 getSelectedCheckBoxes (' lcr.rjur.j-') ;
»;
var getSelectedCheck3oxes - function (grouplTane) {
var result = 5(' input [r.air.e-' groupKame ]:checked');
if (result.length > 0) {
var resultString » result.length + ’ language is) checked<br/>";
result.each(function () {
resultString += i (this) .val () + '<br.'>";
}>;
$('=-- ' ♦ groupName).htnl (resultString);
}
else {
$('#div’ + groupNane) .htnl (".Jc checkbox checked”);

);
)>;
</script>
</head>
'<body>
<div clas3*"aontainer">
<h2>Login P a g e < /h 2 >
I <form>
<div cla33“"fom-g r o u p " >
<label for-"email">Einail:</label>
<input type="email" cla33="form-oontrol" id="email" placeholder="Enter email">
</div>
<div cla33="£orm-group">
<label for-"pwd">Password:</label>
<13 <input type="password" cla3s="form-control" id="txtPassword" placeholder="Enter password">
44 </div>
<div class-"checkbox">
<label><input type-"checkbox" id-"cbShowPassword"> Show Password</label>
</div>
I <div cla33="form-group">
<button type="submit" cla33="btn btn-default">Subniit</button>
</div>
51 [- <div cla3s="form-group">-
Known Languages:
<div cla33="checkbox">
<label><input t^ypc-"checkbox" name-"language" value-"English" />English</label>
<br / X b r />
<label> <input type="checkbox" nanve="language" value="German" /X5erman</label>
</div>
Selected Languages:<br />
<label> <div id-’'divlanguage"></div> </label>
<br />
</div>
</form>
</div>
</body>
</html>

Figure 6.23: Code for Using Bootstrap and jQuery

In figure 6.23, the code includes Bootstrap components such as container, form, and form controls
such as buttons and input controls. It integrates jQuery functionality into Bootstrap by including a
script. In this example, we are using jQuery to display the characters of a typed password whenever
the user selects the Show Password check box. The jQuery library is also used to display the
number of languages selected along with their names. The click event is raised and is handled
through jQuery. The script uses the attr () method associated with id selector to fetch the typed
password characters only when the cbShowPassword check box is selected. The ternary operator
checks whether the check box is selected or not. For fetching the selected languages, the code
defines an anonymous function getSelectedcheckBoxes. The function iterates through each
selected check box to count the total number of selected check boxes and fetch the corresponding
language names.

V 1 .0© APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery

Figure 6.24 shows the output before clicking the Submit button.

1
Login Page
Email:

tonystark

P assw ord:

....i

□ S how P assword

Subm it

Known Languages

□ English

□ Germ an

Selected Languages

Figure 6.24: Output before Submitting the Form

Figure 6.25 shows the output after clicking the Submit button.

Login Page
E m a il:

tonystark

P assw o rd :

iron

0 S h ow P a ssw ord

S ubm it

K now n Languages

0 English

□ Germ an

S e lec te d L a nguages
1 la n g u a g e s ) c h e ck e d
E nglish

Figure 6.25: Output after Submitting the Form

Quick Test 6.1

1. Bootstrap 3 allows including device-specific styles in a single Webpage.

a. True
b. False

2. There is a custom builder for building one's own Bootstrap version.

a. True
b. False

V1.0 © APTECH LIMITED


Developing Responsive W ebsites with Bootstrap and jQuery
/ \
----- K
—^ Summary

>- A media query defines styles for displaying a Webpage on a specific type of device without
modifying the markups.
»- Media queries are useful in determining the device's physical properties namely, viewport's and
device's width and height, screen resolution, and orientation.

>- Media queries define the breakpoint for the media's width from where the layout changes on a
specific screen.

»- Web developers can define device-specific style sheets in Bootstrap and include all in a single
Webpage.

> A basic Bootstrap table features distinct appearance in terms of only horizontal splitters and slight
padding of 8 pixels.

>- A Bootstrap table can have striped rows, borders on all sides, a hovering effect on rows, and
emphasized effect on rows or cells.
>■ The emphasized effect on rows and cells comes from one or more contextual classes namely
.active, . success, . info, . danger, and . warning.
> Bootstrap 3 activates horizontal scrolling on a small device whose screen width is not more than
768 pixels.

>■ Instead of messing up with the core files, it is more efficient to override the default CSS file in
Bootstrap.
> A well is a container component to apply an inset style to a block-level element or sunken effect to
its content.
>- It is also possible to change the well's size by controlling its padding through the modifier classes.
Developing Responsive W ebsites with Bootstrap and jQuery

^ ■ ^ ^ C h e c k Yo u r P ro gre ss
I J

1. Which of the following properties does a media query helps in determining in Bootstrap 3?
a. Viewport's width
b. Screen's resolution
c. Device's height
d. All of these
2. Which of the following classes is not added to the base . t a b l e class?
a ..t a b le -b o r d e r e d
b . . t a b le - h o v e r
c . . t a b le - r e s p o n s iv e
d. None of these
3. The class is used to make a compact Bootstrap table.
a . . t a b le - c o m p a c t
b. .t a b le - c o n d e n s e d
c . .t a b le - s m
d. . t a b l e - l s
4. Which of the following statements is true about customizing Bootstrap?
a. The SASS version allows compiling custom CSS
b. It allows changing the core CSS
c. It allows overriding the core CSS
d. All of these
5. Which of the following effect is well suited to the content of a Webpage?
a. Round borders
b. Gray background
c. Borders on all sides
d. Collapsed text
Developing Responsive W ebsites with Bootstrap and jQuery

Answers to Check Your Progress


1. All of these.
2. .table-responsive
3. .table-condensed
4. All of these
5. Round borders

Answers to Quick Test


Quick Test 6.1

1. True
2. True

You might also like