P Elcteive 2 (Web Systems and Technolgies HTML-css-javascript-And-jquery
P Elcteive 2 (Web Systems and Technolgies HTML-css-javascript-And-jquery
in
P Elective 2
Web Systems and Technologies
This Computer Laboratory manual is designed for use of the subject P Elective 2 111 Web
Development of the course Bachelor of Science in Information Technology (BSIT) of the College of
Technology in CEBU TECHNOLOGICAL UNIVERSITY – Main Campus. This course is designed for knowledge and
skills-based processes and operations needed for the fundamentals of Web Development on HTML, CSS,
In class, you will receive information at an expounded, comprehensive and other varied method to have
better understanding of the different approaches applicable to each specific topic. For best results, study and
practice your technical knowledge in Web Development between class sessions, and use of this manual for
1. Comprehensive (25%)
1.1 Laboratory Session (10%) - The presence of the student in the computer laboratory must be
productive to mold his/her consciousness regarding the importance of the subject in terms of
skills, theory and attitude.
Laboratory performance refers to how the student maximizes time to achieve each specific
task/activities in terms of correct attitude towards learning.
Proper use of Computer Facilities refers to the proper way of utilizing the different basic
programming fundamentals that the students must learn in order to achieve efficiency in
programming skills.
Behavior refers to the concept that knowledge will be best applied if good behavior and
attitude in performing the laboratory activities are observed.
1.2 Quiz (15%) - Short quizzes will be accumulated per term.
2 Performance (60%)
2.1 Laboratory Activities
Performance activities are prepared for skills application and assessment of each topic
during laboratory session. An evaluation scorecard will serve as basis for rating each
performance of students in the laboratory as presented in evaluation procedure. If a student
fails to perform below 40% of the required worksheets/plates/performance activities (due to
unexcused absences, unsatisfactory works, etc.), he/she will automatically get a grade of 5.0.
Administration Jobs related to the course are considered a project/performance of a student.
STUDENT’S AGREEMENT
I have carefully read and understood the recommended general rules and practices while I
am in the Computer Laboratory. I agree to follow them and any other Computer Laboratory rules
my instructor will specify for my safety and success of each and every activity that I am going to
undertake.
I understand that irresponsible behavior has no place in the Computer Laboratory. The
potential effect posed of such behavior is of great value in my professional development.
I recognize my responsibility to follow these practices and precautions while I am inside the
laboratory.
Conforme:
________________________________
Signature over Printed Name/Date
________________________________
Course, Year & Section/Class Schedule
Noted by:
Title Page i
Foreword ii
Acknowledgement iii
Grading System iv
Students Agreement v
Table of Contents vi
Vision, Mission, Goals and Objectives of the University 1
Laboratory Safety Precautions 2
Combining selectors 68
Multiple selectors 68
Attribute selector 69
1.1 Introduction
In this chapter, various component of HTML are discussed to design a web page.
The basic structure for an HTML page is shown below.
• Entries inside the /< ... /> are known as tags. Most of the tags has an opening and closing
e.g. <head>(opening head) and </head> (closing head). Some of the tags do not have closing
tags e.g. <!DOCTYPE ...> and <br />. We need to write the HTML codes inside the tags.
• The comments are written between ‘<!–’ and ‘–>’.
• Here Line 1 gives the details of the ‘HTML version’ to the web-browser. The ‘html’ tells it is
version 5.
• The ‘head’ tag (Lines 3-5) contains the header related tags e.g. ‘title for the page’ and ‘links
for the css files’etc.
• The ‘body’ tag (7-11) contains the actual HTML code which is displayed on the web-browser.
Also, we add all the JavaScript related codes just before the closing body tag (</body>).
<!DOCTYPE html> <!-- tells browser above the html version -->
<html> <!-- beginning of the html document -->
<head>
<!-- header related tags e.g. title, links etc. -->
</head>
<body>
<!-- actual html document here -->
<!-- add JavaScript files here -->
</body>
</html>
In below code, the message “HTML Lesson” is displayed on the HTML page. The Fig. 1.1 is the
resultant HTML page.
6
• The Table 1.1 shows the list of tags which are required for writing the basic ‘HTML’ codes i.e.
without any style e.g. bold, italics and numbering etc.
Note: All the new codes are added below the previous codes in the ‘body’ tag. Therefore only newly
added codes are shown in the tutorial.
<div style="color:blue;">
<--The 'div' tag can be used for formatting the tags inside it at once using 'style' and 'classes'␣
˓→
etc.--->
</div>
<center>
<h3> Heading 3 is centered</h3>
<p><span> Centered span inside the paragraph.</span><p>
</center>
<pre> 'pre' tag preserve the formatting (good for writing codes)
# Python code
x=2y
=3
print(x+y)
1.4 Attributes
In Fig. 1.2, we saw an example of attribute (i.e. style) which changed the color of all the elements to
‘blue’ inside the ‘div’ tag.
• Attribute is defined inside the opening part of a ‘tag’. For example, in the below code, the
attribute ‘style’ is defined inside the ‘div’ tag.
<div style=”color:blue”>
</div>
An attribute has two parts i.e. ‘name’ and ‘value’. For example, in the above code, name and
value of the attribute are ‘style’ and ‘blue’ respectively.
1.4.2 Core attributes
Below are the three core attributes which are used frequently in web design.
• id : The ‘id’ is the unique name which can be given to any tag. This is very useful in
distinguishing the element with other elements.
Note: Above three attributes are used with ‘CSS (cascading style sheet)’ and JavaScript/jQuery, which
are the very handy tools to enhance the look and functionalities of the web-page respectively. The
CSS is discussed in Chapter 2, whereas JavaScript and jQuery are discussed in Chapter 4 and Chapter
5 respectively.
• Also we can define multiple attributes for one tag as shown below,
10
In this section, we will learn to draw tables along with some attributes which are discussed in Table 1.2.
Table 1.3 shows the list of tags available to create the table, which are used in Listing 1.1.
11
<html>
<!-- border-color, width and height -->
<table border="1" bordercolor="black" width="450" height="100">
<caption>Table 1 : Various tags of table</caption>
<tr bgcolor="red" > <!-- row -->
<th>Column 1</th> <!-- header -->
<th>Column 2</th>
<th>Column 3</th>
</tr>
</table>
12
In this section, we will see some of the text formatting options (see Table 1.4) e.g. bold, italic, subscript
and strike etc.
• Below are the some of the examples of text formatting, whose results are shown in Fig. 1.4,
<html>
<!-- Text formatting -->
<p>This is <b>bold</b> text</p>
<p>This is <strike>striked</strike> text</p>
<p>This is <sub>subscript</sub> text</p>
<p>This is <i>Italic</sub> text</p>
13
1.7 Images
Image tag has two important attribues i.e. ‘src’ and ‘alt’ as described below,
• src : tells the location of ‘image’ file e.g. in Line 2 the image ‘logo.jpg’ will be searched inside the
folder
‘img’.
• alt : is the ‘alternate text’ which is displayed if image is not found. For example, in Line 6, the
name of the image is incorrectly written i.e. ‘logoa’ (instead of ‘logo’), therefore the value of ‘alt’
i.e. ‘Missing Logo.jpg’ will be displayed as shown in Fig. 1.5.
<html>
<!-- Images -->
<img src="profile.jpg" alt="profile.jpg" width="50%"/>
<br/> <br/>
<img src="Picture1.png" alt="Picture1.png" width="20%"/>
14
</html>
Note: We can use other attributes as well e.g. ‘height’, ‘align’ and ‘border’ etc.
1.8 Lists
15
1.9 Links
16
17
Fig 1.7
Note: We can change the color of the links using ‘alink (active link)’, ‘link’ and ‘vlink (visited link’, by
defining these attributes in the ‘body tag’ as shown below,
<body alink="green" link="blue" vlink="red">
1.10 Forms
Forms can have different types of controls to collect the input-data from users, which are listed
below and shown in Table 1.5,
• Text input
• Text area
• Radio button
• Checkbox
• Select box
• File select
• Buttons
• Submit and reset buttons
• Hidden input
Input : hidden type hidden will not display on html, but can be
used
for sending information to server
Text area rows, cols numeric value number of rows and cols
name user-defined name send to server
• Below are the exmaple of the control inputs described in Table 1.5
<!-- Forms -->
<form>
<h4>Text input </h4>
Name : <input type="text" name="user_name" size="4" value="e.g. meher21"
maxlength="10"><br> Password : <input type="password" name="user_pass" ><br>
</form>
Fig. 1.7 is the output of above code,
• Below is the code which shows the working of various buttons. Note that method and action are
defined in this form, which will be triggered on ‘submit’ button. Lastly, ‘hidden’ option is used in
this example.
<form method="get|post" action="jquery.html">
<h4> Buttons and Hidden</h4>
<html>
<head>
<title>
Map individual Profiling
</title>
</head>
<body>
<p>
map location
</div class="mapouter">
<div class="gmap_canvas">
<iframe width="400" height="400"
id="gmap_canvas"
src="https://maps.google.com/maps
?q=Deca Homes Tisa t%20of
%20cebu%20carbon
market&t=&z=13&ie=UTF8&iwloc=&
output=embed" frameborder="0"
scrolling="no" marginheight="0"
marginwidth="0">
</iframe>
</div>
<style>.mapouter{position:relative;t
ext-
align:right;height:600px;width:700px
;}.gmap_canvas
{overflow:hidden;background:none!
important;height:500px;width:600px
;}
</style>
<form>
<input type="radio">
Enter your username:
<input type="text">
<br>
<input type="checkbox">
Enter your password:
<input type="password">
</br>
<br>
<select>
<option>Icecream with
lugaw</option>
<option>Icecream with
mongos</option>
<option>Icecream with prito nga
pancit</option>
Instructional Module created by : Leodivino A. Lawas
<option>Icecream with mango nga
pikas nga buwad</option>
</br>
</select>
<br>
Komentaryo mo ni sir here
</br>
<textarea rows="10" cols="15">
</textarea>
</br>
<input type="submit">
<input type="reset">
</br>
</p>
<table width="190" border="1"
cellpadding="7">
<tr>
<th rowspan="3"></th>
<th rowspan="3"></th>
<th rowspan="3"></th>
<th rowspan="3"></th>
</tr>
</table>
</form>
</body>
</html>
25
Instructional Module created by : Leodivino A. Lawas
Chapter 2
2.1 Introduction
CSS is used to enhance the look of the web page. In Section 1.4.2, we saw the attribute ‘style’, which is
used for changing the color of the text. Let’s rewrite the example of ‘style’ as shown in next section.
CSS Syntax
Each declaration includes a CSS property name and a value, separated by a colon.
Multiple CSS declarations are separated with semicolons, and declaration blocks are
surrounded by curly braces.
26
Instructional Module created by : Leodivino A. Lawas
Example :
p {
color: red;
text-align: center;
}
Example Explained
p is a selector in CSS (it points to the HTML element you want to style: <p>).
color is a property, and red is the property value
text-align is a property, and center is the property value
• Below code is an example of ‘inline CSS’, where the styles are defined inside the individual tags.
<!DOCTYPE html>
<html>
<head>
<title>CSS Tutorial</title>
</head>
<body>
</body>
</html>
27
Instructional Module created by : Leodivino A. Lawas
In the above code, we have three ‘headings’ with font-color as ‘blue’. Suppose, we want to change the
color to red, then we must go to to individual ‘h3’ tag and then change the color. This is easy in this case,
but if we have 100 headings in 5 different ‘html’ files, then this process is not very handy. In such cases,
CSS can be quite useful as shown in next section. Another Example Below
<!DOCTYPE html>
<html>
<body>
<h1 style="color:blue;text-align:center;">This is a heading</h1>
<p style="color:red;">This is a paragraph.</p>
</body>
</html>
28
Instructional Module created by : Leodivino A. Lawas
2.1.2 Embedded CSS
In the below code, the style is embedded inside the ‘style’ tag as shown in Lines 8-17. Here, we have
defined two classes i.e. ‘h3_blue (Lines 21-23)’ and ‘h3_red (Lines 26-28)’. Then, the selectors at Lines 9
and 13 targets the class ‘h3_blue’ & ‘h3_red’, and change the color to blue and red respectively. In this
chapter, we will discuss the selectors (e.g. h3.h3_blue) in more details.
Note:
• In CSS, the comments are written between /* and */.
<!DOCTYPE html>
<html>
<head>
<title>CSS Tutorial</title>
<style type="text/css"> h3.h3_blue{
/*change color to blue*/ color:
blue;
}
29
Instructional Module created by : Leodivino A. Lawas
</body>
</html>
1
• Below is the output of above code,
Fig.
2.1: Embedded CSS
We can write the ‘CSS’ code in different file and then import the file into ‘html’ document as shown in
this section. In this way, we can manage the files easily.
• The ‘CSS’ code is saved in the file ‘my_css.css’ which is saved inside the folder ‘asset/css’.
/* asset/css/my_css.css */
h3.h3_blue{ col
or: blue;
}
h3.h3_red{ color:r
ed;
}
• Next, we need to import the CSS file into the ‘html’ file as shown in Line 7.
30
Instructional Module created by : Leodivino A. Lawas
<!DOCTYPE html>
<html>
<head>
<title>CSS Tutorial</title>
<link rel="stylesheet" type="text/css" href="mycss.css">
</head>
<body>
</body>
</html>
31
Instructional Module created by : Leodivino A. Lawas
2.2 Basic CSS Selectors
<!DOCTYPE html>
<html>
<head>
<title>CSS Selectors</title>
<link rel="stylesheet" type="text/css" href="asset/css/my_css.css">
</head>
<body>
<h3>CSS Selectors</h3>
</body>
</html>
• Below code shows the example of different selectors, and the output is shown in Fig. 2.2
/* asset/css/my_css.css */
/*element
selection*/
h3 {
color:
blue; }
/*class selection*/
.c_head{ font-family:
cursive; color: orange; }
32
Instructional Module created by : Leodivino A. Lawas
/*id selection*/
#i_head{ font-variant:
small-caps; color: red;
}
2.3 Hierarchy
In previous section, we saw the example of selectors. In this section, we will understand the hierarchy of
the styling-operations.
</body>
</html>
Below is the CSS code. Let’s understand the formatting of all three ‘p’ tags individually. The results are
shown in Fig. 2.3.
• ‘p’ tag at Line 13 of html : Since, ‘id’ has highest priority, therefore CSS rule for #i_head’ (Line
12) will not be overridden by Line 24; hence the color is red. Line 13 has ‘p’ tag, therefore ‘font-
variant’ rule will be applied by Line 17. Also, this tag has class ‘c_head’, therefore ‘font’ will be
set to ‘cursive’. Hence, the line is “all-caps with font-cursive in red color”.
• ‘p’ tag at Line 12 of html : Similarly, the ‘head’ tag has higher priority than ‘element’ therefore
color of this line is oranage and font-family is ‘cursive’. Also, Line 17 will make it all caps
• ‘p’ tag at Line 10 of html : Color defined at Line 18 will be overridden by Line 24; hence the color
will be blue. Also, Line 17 will make it all caps.
/* my_css.css */
/*class selection*/
.c_head{ font-family:
cursive;
color: orange; /*override the blue color*/
}
/*id selection*/
#i_head{ color
: red;
}
/*element selection*/
p{
font-variant: small-caps;
color: blue;
}
34
Instructional Module created by : Leodivino A. Lawas
2.4. More selectors
/*element selection*/
p{
color: green;
}
The id of an element is unique within a page, so the id selector is used to select one
unique element!
To select an element with a specific id, write a hash (#) character, followed by the id of
the element.
Example
The CSS rule below will be applied to the HTML element with id="para1":
#para1 {
text-align: center;
color: red;
}
35
Instructional Module created by : Leodivino A. Lawas
The CSS class Selector
The class selector selects HTML elements with a specific class attribute.
To select elements with a specific class, write a period (.) character, followed by the
class name.
Example
In this example all HTML elements with class="center" will be red and center-aligned:
.center {
text-align: center;
color: red;
}
<!DOCTYPE html>
<html>
<head>
<style>
p.center {
text-align: center;
color: red;
}
</style>
</head>
<body>
</body>
</html>
Example
The CSS rule below will affect every HTML element on the page:
36
Instructional Module created by : Leodivino A. Lawas
* {
text-align: center;
color: blue;
}
Look at the following CSS code (the h1, h2, and p elements have the same style
definitions):
h1 {
text-align: center;
color: red;
}
h2 {
text-align: center;
color: red;
}
p {
text-align: center;
color: red;
}
Example
In this example we have grouped the selectors from the code above:
37
Instructional Module created by : Leodivino A. Lawas
Table 2.1 shows the combinations of selectors to target the various elements of the HTML. Also, some of
the example of ‘Attribute selector’ is shown in this section.
• Add below code at the end of the html file. In these lines ‘custom attributes’ are added (i.e.
my_id).
<!-- css.html -->
<span my_id='m_span'> Span with attribute 'my_id' with value 'm_span' </span> <br>
<span my_id='m_span2'> Span with attribute 'my_id' with value 'm_span2' </span>
38
Instructional Module created by : Leodivino A. Lawas
2.5 More properties
Table 2.2 shows the some more important properties which can be used in CSS,
2em 2*font-size
a:visited
a:active
word-spacing 10 px
border-bottom-style
border-left-style
border-right-style
Padding padding (top, bottom, left, ‘10px 10px 2px 2px’ or ‘10px 2px’
right)
padding-right, padding-left
etc.
40
Instructional Module created by : Leodivino A. Lawas
CSS Backgrounds
❮ PreviousNext ❯
The CSS background properties are used to add background effects for elements.
In these chapters, you will learn about the following CSS background properties:
background-color
background-image
background-repeat
background-attachment
background-position
background (shorthand property)
CSS background-color
The background-color property specifies the background color of an element.
Example
The background color of a page is set like this:
body {
background-color: lightblue;
}
Try it Yourself »
Example
Here, the <h1>, <p>, and <div> elements will have different background colors:
h1 {
background-color: green;
}
div {
background-color: lightblue;
}
p {
background-color: yellow;
}
CSS Background Image
❮ PreviousNext ❯
CSS background-image
The background-image property specifies an image to use as the background of an
element.
Example
Set the background image for a page:
body {
background-image: url("paper.gif");
}
Instructional Module created by : Leodivino A. Lawas
Try it Yourself »
Example
This example shows a bad combination of text and background image. The text is
hardly readable:
body {
background-image: url("bgdesert.jpg");
}
Try it Yourself »
Note: When using a background image, use an image that does not disturb the text.
The background image can also be set for specific elements, like the <p> element:
Example
p {
background-image: url("paper.gif");
}
Try it Yourself »
CSS background-repeat
By default, the background-image property repeats an image both horizontally and
vertically.
Some images should be repeated only horizontally or vertically, or they will look
strange, like this:
Example
body {
background-image: url("gradient_bg.png");
}
Example
body {
background-image: url("gradient_bg.png");
background-repeat: repeat-x;
}
CSS Background Attachment
❮ PreviousNext ❯
CSS background-attachment
The background-attachment property specifies whether the background image should scroll
or be fixed (will not scroll with the rest of the page):
Example
Specify that the background image should be fixed:
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
background-attachment: fixed;
}
Try it Yourself »
Example
Specify that the background image should scroll with the rest of the page:
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
Instructional Module created by : Leodivino A. Lawas
background-attachment: scroll;
}
Instead of writing:
body {
background-color: #ffffff;
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
}
Example
Use the shorthand property to set the background properties in one declaration:
body {
background: #ffffff url("img_tree.png") no-repeat right top;
}
Try it Yourself »
When using the shorthand property the order of the property values is:
background-color
background-image
background-repeat
background-attachment
background-position
It does not matter if one of the property values is missing, as long as the other ones
are in this order. Note that we do not use the background-attachment property in the
examples above, as it does not have a value.
Property Description
The CSS border properties allow you to specify the style, width, and color of an
element's border.
The border-style property can have from one to four values (for the top border, right
border, bottom border, and the left border).
Example
Demonstration of the different border styles:
p.dotted {border-style: dotted;}
p.dashed {border-style: dashed;}
p.solid {border-style: solid;}
p.double {border-style: double;}
p.groove {border-style: groove;}
p.ridge {border-style: ridge;}
p.inset {border-style: inset;}
p.outset {border-style: outset;}
p.none {border-style: none;}
p.hidden {border-style: hidden;}
p.mix {border-style: dotted dashed solid double;}
Result:
A dotted border.
A dashed border.
A solid border.
A double border.
No border.
A hidden border.
Try it Yourself »
CSS Border Width
❮ PreviousNext ❯
The width can be set as a specific size (in px, pt, cm, em, etc) or by using one of the
three pre-defined values: thin, medium, or thick:
Example
Demonstration of the different border widths:
p.one {
border-style: solid;
border-width: 5px;
}
p.two {
border-style: solid;
border-width: medium;
}
p.three {
border-style: dotted;
border-width: 2px;
}
p.four {
border-style: dotted;
border-width: thick;
}
Result:
CSS Border Color
❮ PreviousNext ❯
Example
Demonstration of the different border colors:
p.one {
border-style: solid;
border-color: red;
}
p.two {
border-style: solid;
border-color: green;
}
p.three {
border-style: dotted;
border-color: blue;
}
In CSS, there are also properties for specifying each of the borders (top, right, bottom,
and left):
Example
p {
border-top-style: dotted;
border-right-style: solid;
border-bottom-style: dotted;
border-left-style: solid;
}
Margins are used to create space around elements, outside of any defined borders.
Try it Yourself »
CSS Margins
The CSS margin properties are used to create space around elements, outside of any
defined borders.
With CSS, you have full control over the margins. There are properties for setting the
margin for each side of an element (top, right, bottom, and left).
margin-top
Example
Set different margins for all four sides of a <p> element:
p {
margin-top: 100px;
margin-bottom: 100px;
margin-right: 150px;
margin-left: 80px;
}
Try it Yourself »
margin-top
margin-right
margin-bottom
margin-left
Example
Use the margin shorthand property with four values:
p {
margin: 25px 50px 75px 100px;
}
Try it Yourself »
Example
Use the margin shorthand property with three values:
p {
margin: 25px 50px 75px;
}
Try it Yourself »
Example
Use the margin shorthand property with two values:
p {
margin: 25px 50px;
}
Try it Yourself »
margin: 25px;
o all four margins are 25px
Example
Use the margin shorthand property with one value:
p {
margin: 25px;
}
Try it Yourself »
The element will then take up the specified width, and the remaining space will be split
equally between the left and right margins.
Example
Use margin: auto:
div {
width: 300px;
margin: auto;
border: 1px solid red;
}
Try it Yourself »
div {
border: 1px solid red;
margin-left: 100px;
}
p.ex1 {
margin-left: inherit;
}
CSS Padding
❮ PreviousNext ❯
Padding is used to create space around an element's content, inside of any defined
borders.
Try it Yourself »
CSS Padding
The CSS padding properties are used to generate space around an element's content,
inside of any defined borders.
With CSS, you have full control over the padding. There are properties for setting the
padding for each side of an element (top, right, bottom, and left).
padding-top
padding-right
padding-bottom
padding-left
Example
Set different padding for all four sides of a <div> element:
div {
padding-top: 50px;
padding-right: 30px;
padding-bottom: 50px;
padding-left: 80px;
}
Try it Yourself »
padding-top
padding-right
padding-bottom
padding-left
Example
Use the padding shorthand property with four values:
div {
padding: 25px 50px 75px 100px;
}
Try it Yourself »
Example
Use the padding shorthand property with three values:
div {
padding: 25px 50px 75px;
}
Try it Yourself »
Example
Use the padding shorthand property with two values:
padding: 25px;
o all four paddings are 25px
Example
Use the padding shorthand property with one value:
div {
padding: 25px;
}
Try it Yourself »
So, if an element has a specified width, the padding added to that element will be
added to the total width of the element. This is often an undesirable result.
Example
Here, the <div> element is given a width of 300px. However, the actual width of the
<div> element will be 350px (300px + 25px of left padding + 25px of right padding):
div {
width: 300px;
padding: 25px;
}
Try it Yourself »
To keep the width at 300px, no matter the amount of padding, you can use the box-
sizing property. This causes the element to maintain its actual width; if you increase the
padding, the available content space will decrease.
div {
width: 300px;
padding: 25px;
box-sizing: border-box;
}
Try it Yourself »
Try it Yourself »
The height and width properties do not include padding, borders, or margins. It sets the
height/width of the area inside the padding, border, and margin of the element.
auto - This is default. The browser calculates the height and width
length - Defines the height/width in px, cm etc.
% - Defines the height/width in percent of the containing block
initial - Sets the height/width to its default value
inherit - The height/width will be inherited from its parent value
Example
Set the height and width of a <div> element:
div {
height: 200px;
width: 50%;
background-color: powderblue;
}
The CSS box model is essentially a box that wraps around every HTML element. It
consists of: margins, borders, padding, and the actual content. The image below
illustrates the box model:
Content - The content of the box, where text and images appear
Padding - Clears an area around the content. The padding is transparent
Border - A border that goes around the padding and content
Margin - Clears an area outside the border. The margin is transparent
The box model allows us to add a border around elements, and to define space between
elements.
div {
width: 300px;
border: 15px solid green;
padding: 50px;
margin: 20px;
}
CSS Text
❮ PreviousNext ❯
TEXT FORMATTING
This text is styled with some of the text formatting
properties. The heading uses the text-align, text-transform,
and color properties. The paragraph is indented, aligned, and
the space between characters is specified. The underline is
removed from this colored "Try it Yourself" link.
Try it Yourself »
Text Color
The color property is used to set the color of the text. The color is specified by:
The default text color for a page is defined in the body selector.
Example
body {
color: blue;
}
h1 {
color: green;
}
Try it Yourself »
CSS Icons
❮ PreviousNext ❯
Icons can easily be added to your HTML page, by using an icon library.
Add the name of the specified icon class to any inline HTML element (like <i> or <span>).
All the icons in the icon libraries below, are scalable vectors that can be customized with
CSS (size, color, shadow, etc.)
Instructional Module created by : Leodivino A. Lawas
Font Awesome Icons
To use the Font Awesome icons, go to fontawesome.com, sign in, and get a code to add
in the <head> section of your HTML page:
Read more about how to get started with Font Awesome in our Font Awesome 5
tutorial.
Example
<!DOCTYPE html>
<html>
<head>
<script src="https://kit.fontawesome.com/a076d05399.js" crossorigin="anonymous"><
/script>
</head>
<body>
<i class="fas fa-cloud"></i>
<i class="fas fa-heart"></i>
<i class="fas fa-car"></i>
<i class="fas fa-file"></i>
<i class="fas fa-bars"></i>
</body>
</html>
Styling Links
Links can be styled with any CSS property (e.g. color, font-family, background, etc.).
Example
a {
color: hotpink;
}
Try it Yourself »
Example
/* unvisited link */
a:link {
color: red;
}
/* visited link */
a:visited {
color: green;
}
/* selected link */
a:active {
color: blue;
}
Try it Yourself »
unordered lists (<ul>) - the list items are marked with bullets
ordered lists (<ol>) - the list items are marked with numbers or letters
The following example shows some of the available list item markers:
Example
ul.a {
list-style-type: circle;
}
ul.b {
list-style-type: square;
}
ol.c {
list-style-type: upper-roman;
}
ol.d {
list-style-type: lower-alpha;
}
Try it Yourself »
CSS Tables
❮ PreviousNext ❯
Company Contact
Try it Yourself »
Table Borders
To specify table borders in CSS, use the border property.
The example below specifies a black border for <table>, <th>, and <td> elements:
Example
table, th, td {
border: 1px solid black;
}
Try it Yourself »
Full-Width Table
The table above might seem small in some cases. If you need a table that should span
the entire screen (full-width), add width: 100% to the <table> element:
Example
table {
width: 100%;
}
Try it Yourself »
Double Borders
Notice that the table in the examples above have double borders. This is because both
the table and the <th> and <td> elements have separate borders.
Instructional Module created by : Leodivino A. Lawas
To remove double borders, take a look at the example below.
Example
table {
border-collapse: collapse;
}
Try it Yourself »
If you only want a border around the table, only specify the border property for
<table>:
Example
table {
border: 1px solid black;
}
Try it Yourself »
CSS Layout - The
display Property
❮ PreviousNext ❯
Every HTML element has a default display value depending on what type of element it
is. The default display value for most elements is block or inline.
Block-level Elements
A block-level element always starts on a new line and takes up the full width available
(stretches out to the left and right as far as it can).
<div>
<h1> - <h6>
<p>
<form>
<header>
<footer>
<section>
Inline Elements
An inline element does not start on a new line and only takes up as much width as
necessary.
<span>
<a>
Display: none;
display: none; is commonly used with JavaScript to hide and show elements without
deleting and recreating them. Take a look at our last example on this page if you want
to know how this can be achieved.
Changing an inline element to a block element, or vice versa, can be useful for making
the page look a specific way, and still follow the web standards.
Example
li {
display: inline;
}
Try it Yourself »
Example
span {
display: block;
}
Instructional Module created by : Leodivino A. Lawas
Try it Yourself »
Example
a {
display: block;
}
Try it Yourself »
Remove
Instructional Module created by : Leodivino A. Lawas
visibility:hidden
Hide
Reset
CSS Navigation Bar
❮ PreviousNext ❯
Home
News
Contact
About
Home
News
Contact
About
Home
News
Contact
About
Navigation Bars
Having easy-to-use navigation is important for any web site.
With CSS you can transform boring HTML menus into good-looking navigation bars.
In our examples we will build the navigation bar from a standard HTML list.
A navigation bar is basically a list of links, so using the <ul> and <li> elements makes
perfect sense:
Example
<ul>
<li><a href="default.asp">Home</a></li>
<li><a href="news.asp">News</a></li>
<li><a href="contact.asp">Contact</a></li>
<li><a href="about.asp">About</a></li>
</ul>
Now let's remove the bullets and the margins and padding from the list:
Example
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
To build a vertical navigation bar, you can style the <a> elements inside the list, in
addition to the code from the previous page:
Example
li a {
display: block;
width: 60px;
}
Try it Yourself »
Example explained:
display: block; - Displaying the links as block elements makes the whole link area
clickable (not just the text), and it allows us to specify the width (and padding,
margin, height, etc. if you want)
width: 60px; - Block elements take up the full width available by default. We want
to specify a 60 pixels width
Instructional Module created by : Leodivino A. Lawas
You can also set the width of <ul>, and remove the width of <a>, as they will take up
the full width available when displayed as block elements. This will produce the same
result as our previous example:
Example
ul {
list-style-type: none;
margin: 0;
padding: 0;
width: 60px;
}
li a {
display: block;
}
Try it Yourself »
Home
News
Contact
About
Example
ul {
list-style-type: none;
margin: 0;
padding: 0;
width: 200px;
background-color: #f1f1f1;
}
li a {
display: block;
color: #000;
padding: 8px 16px;
text-decoration: none;
}
Home
News
Contact
About
Example
.active {
background-color: #04AA6D;
color: white;
}
Try it Yourself »
Add the border property to <ul> add a border around the navbar. If you also want
borders inside the navbar, add a border-bottom to all <li> elements, except for the last
one:
Home
News
Contact
About
Example
ul {
border: 1px solid #555;
}
li:last-child {
border-bottom: none;
}
Try it Yourself »
About
Example
li {
display: inline;
}
Try it Yourself »
Example explained:
display: inline; - By default, <li> elements are block elements. Here, we remove
the line breaks before and after each list item, to display them on one line
a {
display: block;
padding: 8px;
background-color: #dddddd;
}
Try it Yourself »
Example explained:
float: left; - Use float to get block elements to float next to each other
display: block; - Allows us to specify padding (and height, width, margins, etc. if
you want)
padding: 8px; - Specify some padding between each <a> element, to make them
look good
background-color: #dddddd; - Add a gray background-color to each <a> element
Tip: Add the background-color to <ul> instead of each <a> element if you want a full-
width background color:
Example
ul {
background-color: #dddddd;
}
Try it Yourself »
Home
News
Contact
About
li {
float: left;
}
li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
Home
News
Contact
About
Example
.active {
background-color: #04AA6D;
}
Try it Yourself »
Home
News
Contact
About
Example
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li style="float:right"><a class="active" href="#about">About</a></li>
</ul>
Try it Yourself »
Border Dividers
Add the border-right property to <li> to create link dividers:
Home
News
Contact
About
Example
/* Add a gray right border to all list items, except the last item (last-child)
*/
li {
border-right: 1px solid #bbb;
}
li:last-child {
border-right: none;
}
Basic Dropdown
Create a dropdown box that appears when the user moves the mouse over an element.
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
padding: 12px 16px;
z-index: 1;
}
.dropdown:hover .dropdown-content {
display: block;
}
</style>
<div class="dropdown">
<span>Mouse over me</span>
<div class="dropdown-content">
<p>Hello World!</p>
</div>
</div>
Try it Yourself »
Example Explained
HTML) Use any element to open the dropdown content, e.g. a <span>, or a <button>
element.
Use a container element (like <div>) to create the dropdown content and add whatever
you want inside of it.
Wrap a <div> element around the elements to position the dropdown content correctly
with CSS.
The :hover selector is used to show the dropdown menu when the user moves the
mouse over the dropdown button.
ADVERTISEMENT
Dropdown Menu
Create a dropdown menu that allows the user to choose an option from a list:
Dropdown Menu
This example is similar to the previous one, except that we add links inside the
dropdown box and style them to fit a styled dropdown button:
Example
<style>
/* Style The Dropdown Button */
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
/* Change the background color of the dropdown button when the dropdown content
is shown */
.dropdown:hover .dropbtn {
background-color: #3e8e41;
}
</style>
<div class="dropdown">
<button class="dropbtn">Dropdown</button>
<div class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
Try it Yourself »
Example
.dropdown-content {
right: 0;
}
Try it Yourself »
More Examples
Dropdown Image
How to add an image and other content inside the dropdown box.
Try it Yourself »
Dropdown Navbar
How to add a dropdown menu inside a navigation bar.
CSS Image Gallery
❮ PreviousNext ❯
Image Gallery
The following image gallery is created with CSS:
Example
<html>
<head>
<style>
div.gallery {
margin: 5px;
border: 1px solid #ccc;
float: left;
width: 180px;
}
div.gallery:hover {
border: 1px solid #777;
}
div.gallery img {
width: 100%;
height: auto;
}
div.desc {
padding: 15px;
text-align: center;
}
Instructional Module created by : Leodivino A. Lawas
</style>
</head>
<body>
<div class="gallery">
<a target="_blank" href="img_5terre.jpg">
<img src="img_5terre.jpg" alt="Cinque Terre" width="600" height="400">
</a>
<div class="desc">Add a description of the image here</div>
</div>
<div class="gallery">
<a target="_blank" href="img_forest.jpg">
<img src="img_forest.jpg" alt="Forest" width="600" height="400">
</a>
<div class="desc">Add a description of the image here</div>
</div>
<div class="gallery">
<a target="_blank" href="img_lights.jpg">
<img src="img_lights.jpg" alt="Northern Lights" width="600" height="400">
</a>
<div class="desc">Add a description of the image here</div>
</div>
<div class="gallery">
<a target="_blank" href="img_mountains.jpg">
<img src="img_mountains.jpg" alt="Mountains" width="600" height="400">
</a>
<div class="desc">Add a description of the image here</div>
</div>
</body>
</html>
Try it Yourself »
More Examples
Responsive Image Gallery
How to use CSS media queries to create a responsive image gallery that will look good
on desktops, tablets and smart phones.
With CSS, we can show just the part of the image we need.
In the following example the CSS specifies which part of the "img_navsprites.gif" image
to show:
Example
#home {
width: 46px;
height: 44px;
background: url(img_navsprites.gif) 0 0;
}
Try it Yourself »
Example explained:
This is the easiest way to use image sprites, now we want to expand it by using links
and hover effects.
We will use an HTML list, because it can be a link and also supports a background
image:
Example
#navlist {
position: relative;
}
#navlist li {
margin: 0;
padding: 0;
list-style: none;
position: absolute;
top: 0;
}
#home {
left: 0px;
width: 46px;
background: url('img_navsprites.gif') 0 0;
}
#prev {
left: 63px;
width: 43px;
background: url('img_navsprites.gif') -47px 0;
}
#next {
Instructional Module created by : Leodivino A. Lawas
left: 129px;
width: 43px;
background: url('img_navsprites.gif') -91px 0;
}
Try it Yourself »
Example explained:
#home {left:0px;width:46px;} - Positioned all the way to the left, and the width
of the image is 46px
#home {background:url(img_navsprites.gif) 0 0;} - Defines the background
image and its position (left 0px, top 0px)
#prev {left:63px;width:43px;} - Positioned 63px to the right (#home width 46px
+ some extra space between items), and the width is 43px.
#prev {background:url('img_navsprites.gif') -47px 0;} - Defines the background
image 47px to the right (#home width 46px + 1px line divider)
#next {left:129px;width:43px;}- Positioned 129px to the right (start of #prev is
63px + #prev width 43px + extra space), and the width is 43px.
#next {background:url('img_navsprites.gif') -91px 0;} - Defines the background
image 91px to the right (#home width 46px + 1px line divider + #prev width
43px + 1px line divider )
Example
#home a:hover {
background: url('img_navsprites_hover.gif') 0 -45px;
}
#prev a:hover {
background: url('img_navsprites_hover.gif') -47px -45px;
}
#next a:hover {
background: url('img_navsprites_hover.gif') -91px -45px;
}
Try it Yourself »
CSS Attribute Selectors
❮ PreviousNext ❯
The following example selects all <a> elements with a target attribute:
Example
a[target] {
background-color: yellow;
}
Try it Yourself »
The following example selects all <a> elements with a target="_blank" attribute:
Example
a[target="_blank"] {
background-color: yellow;
}
Try it Yourself »
The following example selects all elements with a title attribute that contains a space-
separated list of words, one of which is "flower":
CSS Forms
❮ PreviousNext ❯
First Name
Example
input {
width: 100%;
}
Try it Yourself »
The example above applies to all <input> elements. If you only want to style a specific
input type, you can use attribute selectors:
Tip: When you have many inputs after each other, you might also want to add
some margin, to add more space outside of them:
Example
input[type=text] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
}
Try it Yourself »
Note that we have set the box-sizing property to border-box. This makes sure that the
padding and eventually borders are included in the total width and height of the
elements.
Read more about the box-sizing property in our CSS Box Sizing chapter.
Bordered Inputs
Use the border property to change the border size and color, and use the border-
radius property to add rounded corners:
First Name
Example
input[type=text] {
border: 2px solid red;
border-radius: 4px;
}
Try it Yourself »
First Name
Colored Inputs
Use the background-color property to add a background color to the input, and
the color property to change the text color:
Example
input[type=text] {
background-color: #3CBC8D;
color: white;
}
Try it Yourself »
Focused Inputs
By default, some browsers will add a blue outline around the input when it gets focus
(clicked on). You can remove this behavior by adding outline: none; to the input.
Use the :focus selector to do something with the input field when it gets focus:
Example
input[type=text]:focus {
background-color: lightblue;
}
Try it Yourself »
Example
input[type=text]:focus {
border: 3px solid #555;
}
Instructional Module created by : Leodivino A. Lawas
Try it Yourself »
Example
input[type=text] {
background-color: white;
background-image: url('searchicon.png');
background-position: 10px 10px;
background-repeat: no-repeat;
padding-left: 40px;
}
Try it Yourself »
Example
input[type=text] {
transition: width 0.4s ease-in-out;
}
input[type=text]:focus {
width: 100%;
}
Try it Yourself »
Example
textarea {
width: 100%;
height: 150px;
padding: 12px 20px;
box-sizing: border-box;
border: 2px solid #ccc;
border-radius: 4px;
background-color: #f8f8f8;
resize: none;
}
Try it Yourself »
Example
select {
width: 100%;
padding: 16px 20px;
border: none;
border-radius: 4px;
background-color: #f1f1f1;
}
Try it Yourself »
For more information about how to style buttons with CSS, read our CSS Buttons
Tutorial.
Responsive Form
Resize the browser window to see the effect. When the screen is less than 600px wide,
make the two columns stack on top of each other instead of next to each other.
Try it Yourself »
Chapter 3
JavaScript
4.1 Introduction
• JavaScript is a dynamic language which is used for designing the web pages on the client side.
• It is case sensitive language.
• It is untyped language i.e. a variable can hold any type of value.
• // is used for comments.
• ; i used for line termination.
• JavaScript code should be added at the end i.e. just above the closing-body-tag.
• It is better to write the JavaScript code in separate file as shown in next section.
The JavaScript code can be written in the ‘html’ file or in the separate ‘JavaScript file (.js)’ as shown in
this
section,
In HTML file, the JavaScript codes can be written inside the ‘script’ tag as shown in Lines 11-13 of below
code. The code will write the message “Hello World from JavaScript!” on the web page. Open the
‘js.html’ in the browser to see the message.
<!-- js.html -->
<!DOCTYPE html>
• <html>
<head>
<title>JavaScript</title>
</head>
<body>
<script type="text/javascript">
document.write("Hello World from JavaScript!
<br>"); </script>
</body>
</html>
• The JavaScript code is saved in the file ‘my_javascript.js’ which is located inside the folders
‘asset/js’. Notethat, no ‘script tag’ is used here.
// asset/js/my_javascript.js
<!DOCTYPE html>
• <html>
<head>
<title>JavaScript</title>
</head>
<body>
</body>
</html>
Now, open the ‘js.html’ file in the browser and it will display the message.
4.3.1 Keywords
• Below are the reserved keywords in the JavaScript which can not be used as ‘variable’ and
‘function’ names etc.
4.3.3 Variables
Variables can be define using keyword ‘var’. Further, JavaScript is untyped language i.e. a variable can
hold any type of value.
• In the below HTML, ‘p’ tag with id ‘p_name’ is defined at Line 10. This id will be used to write
some text using JavaScript,
• <!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<p id='p_name'></p>
<!-- import JavaScript files here -->
<script src="asset/js/my_javascript.js"></script>
</body>
</html>
Two variables are defined at Lines 9-10 of type ‘string’ and ‘float’ respectively. Then ‘getElementById’
is used to locate the tag with id ‘p_name’ and the text is inserted as shown in Line 11. Lastly, the ‘+’
// asset/js/my_javascript
// variable example
var your_name =
"Meher"; var age = 20;
document.getElementById("p_name").innerHTML= "Hello "+ your_name + "<br>Age : " + age;
sign is used to concatenate the values as Line 11.
• Below is the output of above codes. Note that the message ‘Hello World from JavaScript!’ is added at
theend as ‘JavaScript’ file is imported at the end.
Warning: If we import the ‘JavaScript’ file between the ‘ending-head-tag’ and ‘start-body-tag’,
then Message ‘Hello Meher ...’ will not be displayed as ‘JavaScript’ will execute before the loading
of the page; and JavaScript can not find the id ‘p_name’.
Hello Meher
Age : 20
Note: All the JavaScript/HTML codes will be added below the existing codes, therefore only the newly
added code will be shown in the rest of the tutorial.
// prompt
var x = prompt("enter a number"); document.write("2 * ", x, " = ", 2*x +
"<br>");
A pop-up window will appear due to prompt. If we provide the input value as 3, then below output will
be
generated,
2*3=6
Note: The ‘,’ and ‘+’ can be used to combine various outputs as shown in above example
4.3.4 Operators
Various operators are shown in this section. The usage of some of these operators are shown in Section
4.4.
• +
• -• *
• /
• % : modulus i.e remainder of the division
• ++ (increment)
• – (decrement)
4.3.4.2 Assignment operators
• =
• +=
• -=
• *=
• /=
• %=
• ?:
e.g. ‘( (a > b) ? a/b : b/a) )’ i.e if ‘a>b’ then do ‘a/b’ else do ‘b/a’
• & (and)
• | (or)
• ^ (xor)
• ~ (not)
The ‘parseFloat’ or ‘Number’ can be used to convert the value into float values.
document.write("2 + parseFloat('3.4') = ", 2 + parseFloat("3.4"), "<br>"); // parseFloat
Instructional Module created by : Leodivino A. Lawas
105
Chapter 4. JavaScript
4.3.8 Math
4.3.9 String
w = "Krishna"
document.write(w.toLowerCase(), "<br>") // lowercase
document.write(w.small(), "<br>") // small
document.write(w.bold(), "<br>") // bold
document.write(w.strike(), "<br>") // strike
document.write(w.fontsize("5em"), "<br>") // strike
document.write(w.link("http://pythondsp.readthedocs.io"), "<br>") // link
document.write(w.fontcolor("red").fontsize("12em"), "<br>") // multiple
The outputs are shown in Fig. 4.1
4.3.10 Arrays
In JavaScript, the arrays can store different types of values as shown in below code,
// arrays
arr = [15, 30, "Meher"] for(a in
arr) document.write(arr[a], "
");
document.write("<br>");
4.4.1 If-else
In the below code, three conditions are checked for the variable ‘age’; and corresponding message is
printed.
// asset/js/my_javascript
// if-else age = 10; if (age > 3 && age < 6){ document.write("Age :
" + age + "<b> go to kindergarten</b>");
}
else if ( age >=6 && age < 18){ document.write("Age : " +
Instructional Module created by : Leodivino A. Lawas
107
Chapter 4. JavaScript
}
document.write("<br>");
• Since age is 10, therefore ‘else if’ statement is satisfied and we will get below output,
Age : 10 go to school
4.4.2 Switch-case-default
// switch-case
var grade = 'A';
document.write("Grade " + grade + " : ");
switch(grade){ case 'A':
document.write("Very good grade!");
break;
case 'B': document.write("Good
grade!"); break;
default: // if grade is neither 'A' nor 'B'
document.write("Enter correct grade");
}
document.write("<br>
");
• Below is the output of above code,
Grade A : Very good grade!
x++; }
document.write("<br
>");
4.4.5 do-while
The ‘for-in’ loop can be used to iterate over the array as shown below,
// for-in loop
arr = [10, 12, 31]; // array for (a
in arr){ document.write(arr[a] +
" ");
}
document.write("<br>
");
4.4.7 Continue and break
Continue and break statements are used inside the ‘loop’ statements.
• Continue will skip the loop and go to next iteration, if the condition is met. In the below code, 3
will not be printed at the output.
// continue for (i=5;
i>=0; i--){ if (i==3){ //
skip 3
continue;
}
document.write(i + " ");
}
document.write("<br>
");
Below is the output where 3 is not printed in the output.
54210
• ‘Break’ statement will quit the loop if the condition is met. In the below code, the for loop will
be terminated at ‘i=3’, therefore only 5 and 4 will be printed,
// break
Instructional Module created by : Leodivino A. Lawas
110
Chapter 4. JavaScript
4.4.8 Functions
In the below code a function ‘add2Num’ is defined which adds the two numbers and returns the result.
// function
function add2Num(num1, num2){ // function definition return num1 + num2;
}
sum = add2Num(2, 3); // function call document.write("2 + 3 = " + sum);
document.write("<br>");
One of the main usage of JavaScript is ‘event handling’. “Mouse click” and ‘pressing keys on keyboard’
are the example of ‘events’. With the help of JavaScript, we can perform certain actions at the
occurrence of the events, as shown below.
• ‘alert’ is used to display message in the ‘pop up’ window.
function alertMessage(message){ alert(message)
}
• In Line 13, message ‘Hello’ is shown in the pop-up window on the event ‘onclick’. Note that
“JavaScript:void(0)” is used here, which does not refresh the page.
• Line 15 is same as Line 13, but “JavaScript:void(0)” is not used, therefore page will be refreshed.
• Line 17 calls the function ‘alertMessage’ to display the mesage, which is defined in the above
code.
• Lines 19-25 use different events i.e. ‘onmouseover’, ‘onmouseleave’, ‘onmouseup’ and
‘onmousedown’; andthe color and the text of the string changes based on these operations.
<!DOCTYPE html>
4.6 <html> onmouseover="this.style.color='red'",
onmouseleave="this.style.color='blue'",
<head>
onmouseup="this.text='Not
<title>JavaScript</title> clicked'",
onmousedown="this.text='You clicked
</head>
me'"> Not clicked </a><br>
<body>
<!-- import JavaScript files here -->
<p id='p_name'></p>
<script src="asset/js/my_javascript.js"></script>
<a href="JavaScript:void(0)", onclick="alert('Hello')">Say Hello</a><br> <!-- do not reload the page␣
˓→-->
</body>
</html>
<a href="", onclick="alert('Hello')">Say Bye</a><br> <!-- reload the page -->
<a href="JavaScript:void(0)",
Conclusion
In this tutorial, we have selected the element with certain ‘id’ using ‘getElementById’. Also, we saw the
example of ‘event handling’ Although, we can use JavaScript for these operations, but it is better to use
jQuery for these purposes, which is discussed in Chapter 5. A good approach is use to the jQuery for
‘selectors’ & ‘event handling’ and then use various features of JavaScript which are described in Section
4.4 to implement the logics.
jQuery
5.1 Introduction
5.1.1 Requirements
• First create a file ‘jQuery.html’. Next, we need three files, i.e. one CSS (Line 9) and two Javascipt
(Lines 23-24), for using the jQuery in this tutorial. These files are saved inside the folder ‘asset’,
which can be downloaded from the repository. Lines 9 and 24 are the bootstrap files, whereas
Line 23 is the actual ‘jQuery’ file which is required to use the jQuery.
<!DOCTYPE html>
<html>
<head>
<title>jQuery</title>
</head>
<body>
• If we open this html file in the browser, the a blank page will be displayed with header
‘jQuery’.
Next add one jumbotron (Line 15-19) and few labels (Lines 21-26) in the html file as shown in
Fig. 5.1.
<!DOCTYPE html>
<html>
<head>
<title>jQuery</title>
</head>
<body>
<div class="jumbotron">
<div class="col-md-offset-4 container">
<h1><b>jQuery</b></h1>
</div>
</div>
</body>
</html>
Now, we can add the jQuery code as shown in Lines 36-40. Please note the following part,
• $ sign is used to hit the jQuery. In the simple words, we can say that it execute the jQuery.
• The code is written between the following block. This block stops the jQuery to execute until the
whole pageis loaded, i.e. jQuery will be executed after completion of the page-download.
$(function() {
// write code here
});
• The above block is a shorthand for below,
$(document).ready(function() { // write code here
});
Note: We can use multiple blocks, if we want to separate the codes; or we can write all the jQueries
within one block.
• Lastly, the below line hides the id “l_default” after 1000 ms, i.e. ‘Default’ label will not be
displayed after
1000 ms as shown in Fig. 5.2
$("#l_default").hide(1000); // hide id = 'l_default' using # operator after 300 ms
Instructional Module created by : Leodivino A. Lawas
115
Chapter 5. jQuery
<!DOCTYPE html>
<html>
<head>
<title>jQuery</title>
</head>
<body>
<div class="jumbotron">
<div class="col-md-offset-4 container">
<h1><b>jQuery</b></h1>
</div>
</div>
Note: ‘#” is used to select the ‘id’; whereas ‘.’ is sued to access the ‘class’.
• In the below code, the label ‘Danger’ is removed; and “opacity=‘0.5’” is set for rest of the labels.
Here, ‘.label’ selects all the classes which have the name ‘label’ in it. Since all the entries have
classes with name ‘label’, therefore all are selected and faded according to ‘opacity=‘0.5’, as
shown in Fig. 5.3.
<!DOCTYPE html>
<html>
<head>
<title>jQuery</title>
</head>
<body>
<div class="jumbotron">
<div class="col-md-offset-4 container">
<h1><b>jQuery</b></h1>
</div>
</div>
<script type="text/javascript">
$(function() {
$("#l_default").hide(1000); // hide id = 'l_default' using # operator after 300 ms
$(".label-danger").hide(); // hide class = 'label' using . operator
Instructional$(".label").css({opacity:'0.5'});
Module created by : Leodivino // A.
addLawas
opacity to all classes with name 'label'
});
117
</script>
</body>
</html>
Chapter 5. jQuery
It is better to write the jQuery in the separate files, therefore the codes are more manageable.
• For this, first write the code in the separate file ‘my_jquery.js’ as below,
Note: ‘html’ is used to change the content of the ‘id’ as shown in Line 5 below listing (see Fig.
5.4)
// asset/js/my_jquery.js
$(function() {
$("#l_default").hide(1000); // hide id = 'l_default' using # operator after 300 ms
$(".label-danger").html("Shark is dangerous"); // change content using 'html'
});
<!DOCTYPE html>
<html>
</head>
<head>
<body>
<title>jQuery</title>
<!--<div
CSSclass="jumbotron">
-->
<div class="col-md-offset-4 container">
<link href="asset/css/bootstrap.min.css" rel="stylesheet">
<h1><b>jQuery</b></h1>
<!-- Add Custom styles below -->
</div>
</div>
Below is the complete html code, which we will use in this section,
<!DOCTYPE html>
<html>
<head>
<title>jQuery</title>
</head>
<body>
<div class="jumbotron">
<div class="col-md-offset-4 container">
<h1><b>jQuery</b></h1>
</div>
</div>
<br><br>
<span class="btn btn-sm btn-warning" id="b_warning">Toggle Warning Label</span>
<br><br>
<!-- label_id is custom attribute whouse values are set according to id of above labels-->
<span class="btn btn-sm btn-default label-btn" label_id='l_default'>Toggle Default Label</span>
<span class="btn btn-sm btn-primary label-btn" label_id='l_primary'>Toggle Primary
Label</span>
<span class="btn btn-sm btn-success label-btn" label_id='l_success'>Toggle Success
Label</span>
<span class="btn btn-sm btn-info label-btn" label_id='l_info'>Toggle Info Label</span>
<span class="btn btn-sm btn-warning label-btn" label_id='l_warning'>Toggle Warning
Label</span>
<span class="btn btn-sm btn-danger label-btn" label_id='l_danger'>Toggle Danger Label</span>
</body>
</html>
5.2.3.1 Toggle label on mouse click
In this section, the ‘mouse click’ on the button ‘Toggle Warning Label (Line 29)’ is read; and then the
label ‘warning’ is toggled.
• The method ‘on’ waits for user’s input ‘click (i.e. mouse click)’.
• On mouse-click next query i.e. ‘toggle’ is executed which hides/unhide the ‘warning label’ as shown
in Fig.
5.5 - Fig. 5.6.
// asset/js/my_jquery.js
In previous section, we wrote the code which can toggle only one label. In this section, we will toggle
multiple labels by writing one-generalized-jQuery as shown in Fig. 5.7.
• Lines 21-26 and 31-38 of Listing 5.1 are used for this section,
• Custom attributes “label_id=...” are added in each button which has the value which
corresponds to oneof the ‘label’s id’. e.g. ‘label_id’ for Line 33 (i.e. l_default) is same as ‘id’ at
Line 21.
• Next, in the below jQuery, we saved the ‘label_id’ in a variable (see Line 21) and then the
variable is usedto toggle the labels.
// asset/js/my_jquery.js
// toggle 'warning label' based on click on the button 'Toggle Warning Label' $
(function() {
$('#b_warning').on('click', function(){ $('#l_warning').toggle();
});
});
// toggle panels according to the clicked-buttons
$(function(){
$('.label-btn').on('click', function(){ // select class 'label-btn' var labelId = $
(this).attr('label_id'); // store the attribute value of 'label_id'
(continues on next page)
5.3 Selectors
In this section, we will use following HTML to understand the various combination of the selectors which
are summarized in Table 5.1,
<!DOCTYPE html>
<html>
<head>
<title>jQuery Selectors</title>
</head>
<body>
<p>jQuery Selectors</p>
<p id="bar">Paragraph with ID. <span class="foo">Span with class and inside the paragraph-
with-id.</
˓→span></p>
<div>
<p my-id="my_para">Paragraph (with custom id) inside the div</p>
<p my-id="my_para2"><span>Span inside the paragraph (with custom id) inside the
div</span></p>
</div>
</body>
</html>
Note:
• Press ‘ctrl+shift+k’ (or go to Tools->Web Developer->Web Console) to open the web-console in
Firefox and click on ‘console’ and type the ‘jQuery’ commands there.
• Press ‘ctrl+shift+J’ (or go to Tools->Javascript Console) in ‘Chrome’ and type the jQuery
commands there.
• In this tutorial, the output of the ‘Firefox’ are shown.
HTML elements, e.g. div, p, span and table etc., can be selected by writing them with the quotation mark
as shown in below codes.
• Here, ‘$(‘p’) is the command, whereas the lines below it are the outputs.
• The outputs show the ‘selected elements’; and the total number of selected elements i.e.
‘length: 6’.
• If we put the cursor to one of the outputs, then it will highlight the corresponding elements in
the html asshown in Fig. 5.8.
$('p') {...}
0: <p>
1: <p class="foo">
2: <p>
3: <p id="bar">
4: <p my-
id="my_para"> 5: <p
my-id="my_para2">
length: 6
Class can be selected using ‘.’ operator. In below code, class ‘foo’ is selected.
$(".foo")
{...}
0: <p class="foo"> 1: <span class="foo"> length: 2
5.3.1.3 Select ID
ID can be selected using ‘#’ operator. In the below code, id ‘bar’ is selected.
$('#bar')
[...]
0: <p id="bar"> length: 1
We can select a element with specific class name using ‘.’ operator as shown in below code. Here
element ‘span’ with class ‘foo’ is selected,
$("span.foo")
{...}
0: <span class="foo"> length: 1
Use ‘,’ to select different types of elements. In the below code, “paragraph with id ‘bar’” and “elements
with class ‘foo’” are selected ,
$('p#bar, .foo')
{...}
0: <p class="foo">
1: <p id="bar"> 2: <span class="foo"> length: 3
Select ‘span’ inside the ‘p’ (use space between ‘span’ and ‘p’),
$('p span')
{...}
0: <span>
1: <span class="foo">
2: <span>
length: 3
5.3.1.7 Select child element
Note: There is one element inside ‘div’ but it’s path is ‘div->p->span’ therefore ‘span’ is a child of ‘p’ (not
of ‘div’). But tgis ‘span’ is the descendant of ‘div’ therefore can be accessed using space,
$('div span')
{...}
0: <span> length: 1
$('p[class = foo]')
{...}
0: <p class="foo">
length: 1
5.3.2 Filters
Various filter options (e.g. filter, first, last and has etc.) can be used after ‘:’ as shown below,
$('p:first') // select first element
{...}
0: p
my-id="my_para2">
length: 3
{...}
0: <p class="foo">
1: <p id="bar">
length: 2
0: <p>
1: <p id="bar"> 2: <p
my-id="my_para2">
length: 3
In Listing 5.2 we saw one example of event handling, where certain operations are performed on the
event ‘mouse click’. Table 5.2 shows a list of some more events.
Instructional Module created by : Leodivino A. Lawas
128
Chapter 5. jQuery
Web References:
https://www.w3schools.com/
https://devdocs.io/
https://www.freecodecamp.org/news/
https://developer.mozilla.org/en-US/docs/Web
https://tympanus.net/codrops/css_reference/
https://stackoverflow.com/
Beginning CSS: Cascading Style Sheets for Web Design, 2nd Edition
ISBN: 978-0-470-09697-0
This comprehensive introduction clearly shows you how to combine Cascading Style Sheets (CSS) with
HTML, XHTML, or XML to create rich, aesthetically compelling web designs. Packed with detailed
Instructional Module created by : Leodivino A. Lawas
129
Chapter 5. jQuery
examples in syntax-colored code and showing the resulting web pages in color, the second edition will
help you discover how and why CSS works.