Bootstrap and J Query
Bootstrap and J Query
Code ^ jQ uer/
<>html</> Q J B o o tstra p
m
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.
• 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.
• 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.
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
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.
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.
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.
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
+- - glyphicons-halflings-regular.woff2
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.
• 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:
V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery
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>
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.
c © file:///C:/Users/dbollojx/Desktop/p.html
Hello, w orld!
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">
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).
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.
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>.
<!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>
In figure 1.6, the <div> tag contains the container class to indicate that its content will come in
a fixed-width container.
C © file:///C:/Users/dboHojx/Desktop/p.html
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>.
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>
• 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.
< ! 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>
</div>
</body>
</html>
In figure 1.8, the <div> tag contains the container-fluid class to indicate that its content will
come in a fluid container.
C © filey//C:/Users/dbollOjx/Desk?op/p.html
My Bootstrap Page
This part ts ms«e a contamer-ftuM class
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.
Data Attributes
Web developers can utilize all Bootstrap plugins via the markup Application Programming Interface
(API).
• 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.
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.
V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery
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.
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.
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.
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>
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.
V 1 .0 © APTECH LIMITED
Developing Responsive Websites with Bootstrap and jQuery
Blog Search
P a g e H eading Secondary Text Q.
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.
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 »
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’
* * * * « 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<*
★ ★ ★ ★ <r Anonymew*
rve *een tome Defter f a n n t c m not al v n pnc« i recommend r « *
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.
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.
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.----------
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.
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,
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>
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.
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>
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.
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>
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.
Basic Navbar
A navigation bar is a navigation header that s placed at the top of the page
V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery
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.
• 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.
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.
x
A
Ted llta n m M « « Jr*
[WMmKMoxm Q
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>
Pagination
The pagination class provides pagination links:
1 2 3 4 5 6
</body>
</html>
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.
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>
Badges
Hello O
World Q
Folks
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.
In figure 2.15, the . panel-default sub-class retains the default color style for the panel.
D em o Panel
A B asic Panel
Figure 2.17 shows the code for creating a list group with badges on the right.
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>
Folks o
• Default
• Striped
• Animated
• Stacked
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
Progress bars in Bootstrap implement CSS3 animations as well as transitions for a few effects.
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>
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-
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.
Collapsible Example
Collapsible
Collapsibles are useful when you want to hide and show large amount of 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.
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>
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
• 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>
. Re-mefnt** me
SuCkth;
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>
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.
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>
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!!
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
1. False
2. True
Developing Responsive W ebsites with Bootstrap and jQuery
> 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
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'.
• 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.
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
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.
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.
});
OR
$ (function()//Alternate syntax
{
// Code JQuery functions here.
});
Where,
Code Snippet 2:
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
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.
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
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.
Basic Way:800
Function as Variable Name 800
Self Invoking Function, Hello! I called myself
Message from webpage
Funtions in jQuery
Click Me
• 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,
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
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>
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
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,
<!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>
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
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>
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.
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.
submit
1 checkboxe(s) checked
Germany
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.
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.
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"}
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.
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.
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.
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>
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: Output of Code for Fetching Data from a JSON Object
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.
V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery
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>
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}]
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>
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
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.
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:
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.
• 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.
List Item l
List Item2
New List Item
1. The checked selector allows finding which radio buttons are selected.
a. True
b. False
> 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 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. True
2. True
Developing Responsive W ebsites with Bootstrap and jQuery
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>
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
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.
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 )>:
1«
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>
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
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
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.
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>
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.
V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery
• 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>
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.
OK
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.
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.
OK
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,
V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery
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.
The $ . get () method asks data of a resource from a Web server through a GET request.
Syntax
$.get(URL,callback);
where,
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.
OK
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 ()
Syntax
$.post(URL,data,callback);
where,
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 ().
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.
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:
• 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
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
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.
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.
Tags: d x
Germany
Ghana
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:
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
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:
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.
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
V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and 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 !.
Open Dialog
jQuery Dialog!
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.
V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and 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.
V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery
In figure 4.22, the HTML table features the search, pagination, and scrolling utilities. It is no longer a
plain HTML table.
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. False
2. True
Developing Responsive W ebsites with Bootstrap and jQuery
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 □
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.
A responsive Website adapts its layout to the viewing screen using three elements:
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.
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.
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.
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
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.
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.
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 .
Table 5.3 shows the different grid options that work across several devices.
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) {}
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
Gutter Width in 30 (15 on each 30 (15 on each 30 (15 on each 30 (15 on each
Pixels side) side) side) side)
</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.
• Stacked or horizontal
• Small
• Medium
• Large
V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery
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>
</body>
</html>
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
</body>
</hrml>
ft * O
Grid System
col-sm-9 col-sm-3 divides the page In to two 75:25 ratio
Figure 5.6: Output of Code for Grid Layout for Small 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.
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..
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.
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:
<!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>
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.
Bootstrap headers
Bootstrap Header text.
Normal paratagl
Noraml paratag2
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
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.
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.
<!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
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.
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.
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
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
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.
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>
In figure 5.20, the text transformation classes are used within <p> tags.
convert in to lowercase.
CONVERT IN TO UPPERCASE
Capitalise Me.
feutlSj
R < h t « l lsn g »"e n “ >
<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 •
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.
1 " V
1
c.‘ C \Appj\R«ponir.t html
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.
Footer Text
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.
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.25 shows how . clearf ix class organizes the content on a medium-sized device.
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
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.
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
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
V 1 .0 © APTECH LIMITED
Developing Responsive W ebsites with Bootstrap and jQuery
True
False
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
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
1. False
2. True
Developing Responsive W ebsites with Bootstrap and jQuery
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.
<!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>
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.
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.
£ • C 1£ C •;
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>.
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>
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>
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.
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
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.
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.
Compact Table
Firstname Lastname Email
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.
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>
1 Green Free to go
3 Red Stop
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.
<{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>
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
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)
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.
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.
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
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.
</htal>
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
Login Form
Login
In figure 6.20, it is clear that a smaller well features lesser round corners. The text also appears
sunken inside a well.
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.
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.23 shows how to design a Webpage using Bootstrap components and jQuery library.
Developing Responsive W ebsites with Bootstrap and jQuery
);
)>;
</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>
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.
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.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
a. True
b. False
a. True
b. False
>- 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
1. True
2. True