Midterm
Midterm
A. Course Description
This course is design to master one of the most important advance areas of Web Development:
Cascading Style Sheets (CSS) and Server-side Scripting with Php Hypertext Preprocessor (PHP), which
allow the students to set the formatting and positioning of Web pages in standards based and robust way,
and also to develop dynamic content webpages with the use of MySQL database Technology. Using the
current standard web page language, students will be instructed on creating and maintaining a simple web
site.
B. Course Learning Outcomes
At the end of the course, the students should be able to:
1. Know the fundamentals in web-based application architectures and processes;
2. Use CSS, XAMPP, CMS and related technologies in developing complete dynamic web-based
applications;
3. Learn how to test, verify, and debug web-based applications.
4. Develop a database driven web-based application.
C. Module Topics
These are the topics to be covered for the whole course:
PRELIM
Module 1. Introduction and Web Page Building Blocks
Module 2. DOCTYPE
Module 3. Building practical web pages using HTML
Module 4. Cascading Style Sheet
MIDTERM
Module 5. CSS3
Module 6. JS Basic
Module 7. Javascript
Module 8. Javascript Objects
FINALS
Module 9. Introduction to PHP Programming
IT ELEC 1|1
Module 10. PHP Logical Statements
Module 11. PHP and MySQL
Module 12. MySQL Database
Module 13. Limit Data
III. STUDY GUIDE/LEARNING INSTRUCTIONS (This should be tackled during Orientation-1st meeting)
Welcome, and wish everyone is feeling good!
You are reminded to prepare yourselves by observing the following:
Manage your time well.
Wear proper uniform during online synchronous classes (previous prescribed uniforms
should be followed except for first year students who should look simple and smart)
IV. REFERENCES
Shelly, Gary B., Denise M. Woods, Denise M., and William J. Dorin. HTML5 and CSS:
Comprehensive. 7th ed., Cengage Learning, 2012.
Course Technology. 2013.
Brian P. Hogan - HTML5 and CSS3: Develop with Tomorrow's Standard Today, 2010 The
Pragmatic Bookshelf, Dalas Texas
Woods, Denise M., and William J. Dorin. HTML5 and CSS: Comprehensive. 7th ed., Cengage
Learning, 2012.
Vaswani, Vikram– How to Do Everything with PHP and MySQL, 2005 McGraw-Hill/Osborne
Spurlock, Jake. Bootstrap: Responsive Web Development. O'Reilly Media, 2013.
IT ELEC 1|2
College of Information Technology
First Semester, A.Y. 2020-2021
MODULE 5
CSS3
Introduction
This module entitled CSS3 is about designed with complex layouts, unique fonts, and customized
color schemes. This course will show you the basics of Cascading Style Sheets (CSS3). The emphasis
will be on learning how to write CSS rules, how to test code, and how to establish good programming
habits.
Date and Time Allotment
I. Objectives
At the end of the end of this module, students should be able to:
1. Identify the web standards and W3C recommendation
2. Learn HTML
3. Use the different html tags in building a web page.
II. Lecture
CSS 3
The History of CSS 3
Instead of defining all features in a single, large specification like CSS 2, CSS 3 is divided into several
separate documents called "modules". Each module adds new capability or extends features defined in
IT ELEC 1|3
CSS 2, over preserving backward compatibility. Work on CSS level 3 started around the time of
publication of the original CSS 2 recommendation. The earliest CSS 3 drafts were published in June 1999.
Definition
Stands for "Cascading Style Sheet." Cascading style sheets are used to format the layout of Web
pages. They can be used to define text styles, table sizes, and other aspects of Web pages that previously
could only be defined in a page's HTML.
Examples.
body {
background-color: lightblue;
}
h1 {
color: white;
text-align: center;
}
p{
font-family: verdana;
font-size: 20px;
}
Rounded Corner
Definition. With the CSS border-radius property, you can give any element "rounded corners".
#corner {
border-radius: 25px;
background: #73AD21;
padding: 20px;
IT ELEC 1|4
width: 200px;
height: 150px;
}
Border Image
Definition. The border-image property allows you to specify an image to be used as the border around an
element.
Example. Specify an image as the border around an element:
#borderimg {
border: 10px solid transparent;
padding: 15px;
border-image: url(border.png) 30 round;
}
Multi-Background
Definition. CSS allows you to add multiple background images for an element, through the background-
image property.
Example. The following example uses the background shorthand property (same result as example
above):
Here is the code:
#example {
background: url(img_flwr.gif) right bottom no-repeat, url(paper.gif) left top repeat;
}
IT ELEC 1|5
Color - The <color> CSS data type represents a color in the sRGB color space. A <color> may also
include an alpha-channel transparency value, indicating how the color should composite with its
background.
Gradient - CSS gradients let you display smooth transitions between two or more specified colors.
text-shadow
box-shadow
In its simplest use, you only specify the horizontal shadow (2px) and the vertical shadow (2px):
IT ELEC 1|6
Text shadow effect!
Example.
h1 {
text-shadow: 2px 2px 5px red;
}
The following example shows a white text with black shadow: effect!
Example.
h1 {
color: white;
text-shadow: 2px 2px 4px #000000;
}
Multiple Shadows
To add more than one shadow to the text, you can add a comma-separated list of shadows.
The following example shows a red and blue neon glow shadow:
The following example shows a white text with black, blue, and darkblue shadow:
Example.
h1 {
color: white;
IT ELEC 1|7
text-shadow: 1px 1px 2px black, 0 0 25px blue, 0 0 5px darkblue;
}
You can also use the text-shadow property to create a plain border around some text (without shadows):
The color property is used to set the color of the text. The color is specified by:
Look at CSS Color Values for a complete list of possible color values.
The default text color for a page is defined in the body selector.
Example.
body {
color: blue;
}
h1 {
color: green;
}
Text Color and Background Color
In this example, we define both the background-color property and the color property:
Example.
body {
background-color: lightgrey;
IT ELEC 1|8
color: blue;
}
h1 {
background-color: black;
color: white;
}
Web Font
The CSS @font-face Rule
Web fonts allow Web designers to use fonts that are not installed on the user's computer.
When you have found/bought the font you wish to use, just include the font file on your web server, and it
will be automatically downloaded to the user when needed.
Your "own" fonts are defined within the CSS @font-face rule.
TrueType is a font standard developed in the late 1980s, by Apple and Microsoft. TrueType is the most
common font format for both the Mac OS and Microsoft Windows operating systems.
OpenType is a format for scalable computer fonts. It was built on TrueType, and is a registered trademark
of Microsoft. OpenType fonts are used commonly today on the major computer platforms.
WOFF is a font format for use in web pages. It was developed in 2009, and is now a W3C
Recommendation. WOFF is essentially OpenType or TrueType with compression and additional
metadata. The goal is to support font distribution from a server to a client over a network with bandwidth
constraints.
SVG Fonts/Shapes
IT ELEC 1|9
SVG fonts allow SVG to be used as glyphs when displaying text. The SVG 1.1 specification define a font
module that allows the creation of fonts within an SVG document. You can also apply CSS to SVG
documents, and the @font-face rule can be applied to text in SVG documents.
EOT fonts are a compact form of OpenType fonts designed by Microsoft for use as embedded fonts on
web pages.
The numbers in the table specifies the first browser version that fully supports the font format.
EOT 6.0 Not supported Not supported Not supported Not supported
In the @font-face rule; first define a name for the font (e.g. myFirstFont) and then point to the font file.
To use the font for an HTML element, refer to the name of the font (myFirstFont) through the font-
family property:
Example.
@font-face {
font-family: myFirstFont;
src: url(sansation_light.woff);
}
IT ELEC 1|10
div {
font-family: myFirstFont;
}
You must add another @font-face rule containing descriptors for bold text:
Example.
@font-face {
font-family: myFirstFont;
src: url(sansation_bold.woff);
font-weight: bold;
}
2D & 3D Transform
CSS 2D Transforms
CSS transforms allow you to move, rotate, scale, and skew elements.
2D rotate
In this chapter you will learn about the following CSS property:
transform
Browser Support
The numbers in the table specify the first browser version that fully supports the property.
IT ELEC 1|11
CSS 2D Transforms Methods
With the CSS transform property you can use the following 2D transformation methods:
translate()
rotate()
scaleX()
scaleY()
scale()
skewX()
skewY()
skew()
matrix()
The translate() method moves an element from its current position (according to the parameters given for
the X-axis and the Y-axis).
The following example moves the <div> element 50 pixels to the right, and 100 pixels down from its
current position:
Example.
div {
transform: translate(50px, 100px);
}
IT ELEC 1|12
The rotate() method rotates an element clockwise or counter-clockwise according to a given degree.
The following example rotates the <div> element clockwise with 20 degrees:
Example.
div {
transform: rotate(20deg);
}
The following example rotates the <div> element counter-clockwise with 20 degrees:
Example.
div {
transform: rotate(-20deg);
}
The scale() method increases or decreases the size of an element (according to the parameters given for
the width and height).
The following example increases the <div> element to be two times of its original width, and three times of
its original height:
Example.
div {
transform: scale(2, 3);
}
The following example decreases the <div> element to be half of its original width and height:
IT ELEC 1|13
Example.
div {
transform: scale(0.5, 0.5);
}
The following example increases the <div> element to be two times of its original width:
Example.
div {
transform: scaleX(2);
}
The following example decreases the <div> element to be half of its original width:
Example.
div {
transform: scaleX(0.5);
}
The following example increases the <div> element to be three times of its original height:
Example.
div {
transform: scaleY(3);
}
The following example decreases the <div> element to be half of its original height:
IT ELEC 1|14
Example.
div {
transform: scaleY(0.5);
}
The skewX() method skews an element along the X-axis by the given angle.
The following example skews the <div> element 20 degrees along the X-axis:
Example.
div {
transform: skewX(20deg);
}
The skewY() method skews an element along the Y-axis by the given angle.
The following example skews the <div> element 20 degrees along the Y-axis:
Example.
div {
transform: skewY(20deg);
}
The skew() method skews an element along the X and Y-axis by the given angles.
The following example skews the <div> element 20 degrees along the X-axis, and 10 degrees along the
Y-axis:
Example.
div {
transform: skew(20deg, 10deg);
}
IT ELEC 1|15
If the second parameter is not specified, it has a zero value. So, the following example skews the <div>
element 20 degrees along the X-axis:
Example.
div {
transform: skew(20deg);
}
The matrix() Method
The matrix() method combines all the 2D transform methods into one.
The matrix() method take six parameters, containing mathematic functions, which allows you to rotate,
scale, move (translate), and skew elements.
Example.
div {
transform: matrix(1, -0.3, 0, 1, 0, 0);
}
CSS 3D Transforms
Mouse over the elements below to see the difference between a 2D and a 3D transformation:
2D rotate
3D rotate
In this chapter you will learn about the following CSS property:
IT ELEC 1|16
transform
Browser Support
The numbers in the table specify the first browser version that fully supports the property.
With the CSS transform property you can use the following 3D transformation methods:
rotateX()
rotateY()
rotateZ()
The rotateX() method rotates an element around its X-axis at a given degree:
Example.
#myDiv {
transform: rotateX(150deg);
}
The rotateY() Method
The rotateY() method rotates an element around its Y-axis at a given degree:
IT ELEC 1|17
Example.
#myDiv {
transform: rotateY(130deg);
}
The rotateZ() Method
The rotateZ() method rotates an element around its Z-axis at a given degree:
Example.
#myDiv {
transform: rotateZ(90deg);
}
Animation
CSS Animations
CSS
@keyframes
animation-name
animation-duration
animation-delay
animation-iteration-count
animation-direction
animation-timing-function
animation-fill-mode
animation
The numbers in the table specify the first browser version that fully supports the property.
IT ELEC 1|18
animation-name 43.0 10.0 16.0 9.0 30.0
You can change as many CSS properties you want, as many times you want.
To use CSS animation, you must first specify some keyframes for the animation.
Keyframes hold what styles the element will have at certain times.
When you specify CSS styles inside the @keyframes rule, the animation will gradually change from the
current style to the new style at certain times.
The following example binds the "example" animation to the <div> element. The animation will last for 4
seconds, and it will gradually change the background-color of the <div> element from "red" to "yellow":
IT ELEC 1|19
Example.
/* The animation code */
@keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
Multi-Columns
Definition. The CSS multi-column layout allows easy definition of multiple columns of text - just like in
newspapers
Example.
IT ELEC 1|20
CSS Create Multiple Columns
The column-count property specifies the number of columns an element should be divided into.
The following example will divide the text in the <div> element into 3 columns:
Example.
div {
column-count: 3;
}
Example.
div {
column-gap: 40px;
}
The column-rule-style property specifies the style of the rule between columns:
Example.
div {
column-rule-style: solid;
}
The column-rule-width property specifies the width of the rule between columns:
Example.
div {
column-rule-width: 1px;
}
The column-rule-color property specifies the color of the rule between columns:
IT ELEC 1|21
Example.
div {
column-rule-color: lightblue;
}
The column-rule property is a shorthand property for setting all the column-rule-* properties above.
The following example sets the width, style, and color of the rule between columns:
Example.
div {
column-rule: 1px solid lightblue;
}
The column-span property specifies how many columns an element should span across.
The following example specifies that the <h2> element should span across all columns:
Example.
h2 {
column-span: all;
}
Specify The Column Width
The column-width property specifies a suggested, optimal width for the columns.
The following example specifies that the suggested, optimal width for the columns should be 100px:
Example.
div {
column-width: 100px;
}
User Interface
IT ELEC 1|22
CSS user interface properties:
resize
outline-offset
CSS Resizing
The resize property specifies if (and how) an element should be resizable by the user.
The following example lets the user resize only the width of a <div> element:
Example.
div {
resize: horizontal;
overflow: auto;
}
The following example lets the user resize only the height of a <div> element:
Example.
div {
resize: vertical;
overflow: auto;
}
The following example lets the user resize both the height and width of a <div> element:
Example.
div {
resize: both;
overflow: auto;
}
IT ELEC 1|23
In many browsers, <textarea> is resizable by default. Here, we have used the resize property to disable
the resizability:
Example.
textarea {
resize: none;
}
The outline-offset property adds space between an outline and the edge or border of an element.
Example.
div.ex1 {
margin: 20px;
border: 1px solid black;
outline: 4px solid red;
outline-offset: 15px;
}
div.ex2 {
margin: 10px;
border: 1px solid black;
outline: 5px dashed blue;
outline-offset: 5px;
}
Box Sizing
Definition. The CSS box-sizing property allows us to include the padding and border in an element's
total width and height.
The box-sizing property allows us to include the padding and border in an element's total width and
height.
If you set box-sizing: border-box; on an element, padding and border are included in the width and height:
IT ELEC 1|24
Here is the same example as above, with box-sizing: border-box; added to both <div> elements:
Example.
.div1 {
width: 300px;
height: 100px;
border: 1px solid blue;
box-sizing: border-box;
}
.div2 {
width: 300px;
height: 100px;
padding: 50px;
border: 1px solid red;
box-sizing: border-box;
}
IT ELEC 1|25
College of Information Technology
First Semester, A.Y. 2020-2021
MODULE 6&7
Javascript
Introduction
This module entitled Javascript is about client-side scripting languages for the web. Most
browsers support the language by default, so you can get started using JavaScript and HTML with a
simple text editor and browser for testing. Dynamic languages make web pages dynamic without making
calls to your web servers for every button click, character typed, or mouse movement. The JavaScript
language is so popular that hundreds of developers have made customized libraries that make
development easier for other programmers and web designers. If you design web pages, you'll certainly
need to know JavaScript to make a custom UI (user interface).
Date and Time Allotment
I. Objectives
IT ELEC 1|26
At the end of the end of this module, students should be able to:
1. Identify the web standards and W3C recommendation
2. Learn HTML
3. Use the different html tags in building a web page.
II. Lecture
JavaScript Introduction
The example below "finds" an HTML element (with id="demo"), and changes the element content
(innerHTML) to "Hello JavaScript":
Example
document.getElementById("demo").innerHTML = "Hello JavaScript";
In this example JavaScript changes the value of the src (source) attribute of an <img> tag:
IT ELEC 1|27
JavaScript Syntax
The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program. The
examples below make use of the log function of the console object present in most browsers for standard
text output. The JavaScript standard library lacks an official standard text output function.
JavaScript syntax is the set of rules, how JavaScript programs are constructed:
var x, y, z; // Declare Variables
x = 5; y = 6; // Assign Values
z = x + y; // Compute Values
JavaScript Values
Fixed values
Variable values
JavaScript Literals
The two most important syntax rules for fixed values are:
10.50
1001
"John Doe"
'John Doe'
JavaScript Variables
IT ELEC 1|28
An equal sign is used to assign values to variables.
var x;
x = 6;
JavaScript Operators
(5 + 6) * 10
Try it Yourself »
var x, y;
x = 5;
y = 6;
Try it Yourself »
JavaScript Expressions
5 * 10
x * 10
IT ELEC 1|29
JavaScript Keywords
var x, y;
x = 5 + 6;
y = x * 10;
JavaScript Comments
IT ELEC 1|30
There you will find the option to enable or disable javascript by right-clicking on the value of that
option → select toggle.
If javascript.enabled is true; it converts to false upon clicking toogle. If javascript is disabled; it gets
enabled upon clicking toggle.
JavaScript in Chrome
Here are the steps to turn on or turn off JavaScript in Chrome −
Click the Chrome menu at the top right hand corner of your browser.
Select Settings.
Click Show advanced settings at the end of the page.
Under the Privacy section, click the Content settings button.
In the "Javascript" section, select "Do not allow any site to run JavaScript" or "Allow all sites to run
JavaScript (recommended)".
JavaScript in Opera
Here are the steps to turn on or turn off JavaScript in Opera −
Follow Tools → Preferences from the menu.
Select Advanced option from the dialog box.
Select Content from the listed items.
Select Enable JavaScript checkbox.
Finally click OK and come out.
To disable JavaScript support in your Opera, you should not select the Enable JavaScript checkbox.
Warning for Non-JavaScript Browsers
If you have to do something important using JavaScript, then you can display a warning message to the
user using <noscript> tags.
You can add a noscript block immediately after the script block as follows −
<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
<noscript>
Sorry...JavaScript is needed to go ahead.
</noscript>
</body>
</html>
JavaScript Placement
IT ELEC 1|31
There is a flexibility given to include JavaScript code anywhere in an HTML document. However the most
preferred ways to include JavaScript in an HTML file are as follows −
Script in <head>...</head> section.
Script in <body>...</body> section.
Script in <body>...</body> and <head>...</head> sections.
Script in an external file and then include in <head>...</head> section.
In the following section, we will see how we can place JavaScript in an HTML file in different ways.
JavaScript in <head>...</head> section
If you want to have a script run on some event, such as when a user clicks somewhere, then you will
place that script in the head as follows −
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</body>
</html>
This code will produce the following results –
Say Hello
JavaScript in <body>...</body> section
If you need a script to run as the page loads so that the script generates content in the page, then the
script goes in the <body> portion of the document. In this case, you would not have any function defined
using JavaScript. Take a look at the following code.
<html>
<head>
</head>
<body>
<script type = "text/javascript">
<!--
document.write("Hello World")
//-->
</script>
IT ELEC 1|32
<p>This is web page body </p>
</body>
</html>
This code will produce the following results –
Hello World
A JavaScript variable is simply a name of storage location. There are two types of variables in JavaScript
: local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers).
IT ELEC 1|33
Correct JavaScript variables
1. var x = 10;
2. var _value="sonoo";
1. <script>
2. var x = 10;
3. var y = 20;
4. var z=x+y;
5. document.write(z);
6. </script>
30
What is an Operator?
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is called
the operator. JavaScript supports the following types of operators.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
IT ELEC 1|34
Sr.No Operator & Description
.
1 + (Addition)
Adds two operands
Ex: A + B will give 30
2 - (Subtraction)
Subtracts the second operand from the first
Ex: A - B will give -10
3 * (Multiplication)
Multiply both operands
Ex: A * B will give 200
4 / (Division)
Divide the numerator by the denominator
Ex: B / A will give 2
5 % (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0
6 ++ (Increment)
Increases an integer value by one
Ex: A++ will give 11
7 -- (Decrement)
Decreases an integer value by one
Ex: A-- will give 9
IT ELEC 1|35
Example
The following code shows how to use arithmetic operators in JavaScript.
Live Demo
<html>
<body
<script type = "text/javascript">
<!--
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />"
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
result = a + b + c;
document.write(result);
IT ELEC 1|36
document.write(linebreak);
a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);
b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);
//-->
</script>
Set the variables to different values and then try...
</body>
</html>
Output
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
++a = 35
--b = 8
Set the variables to different values and then try...
JavaScript If..Else
JavaScript supports conditional statements which are used to perform different actions based on different
conditions. Here we will explain the if..else statement.
IT ELEC 1|37
Flow Chart of if-else
The following flow chart shows how the if-else statement works.
Example
Try the following example to understand how the if statement works.
Live Demo
<html>
<body>
<script type = "text/javascript">
<!--
var age = 20;
IT ELEC 1|38
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Qualifies for driving
Set the variable to different value and then try...
You can use multiple if...else…if statements, as in the previous chapter, to perform a multiway branch.
However, this is not always the best solution, especially when all of the branches depend on the value of
a single variable.
Starting with JavaScript 1.2, you can use a switch statement which handles exactly this situation, and it
does so more efficiently than repeated if...else if statements.
Flow Chart
IT ELEC 1|39
Syntax
The objective of a switch statement is to give an expression to evaluate and several different statements
to execute based on the value of the expression. The interpreter checks each case against the value of
the expression until a match is found. If nothing matches, a default condition will be used.
switch (expression) {
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
The break statements indicate the end of a particular case. If they were omitted, the interpreter would
continue executing each statement in each of the following cases.
We will explain break statement in Loop Control chapter.
Example
Try the following example to implement switch-case statement.
<html>
<body>
<script type = "text/javascript">
<!--
var grade = 'A';
document.write("Entering switch block<br />");
switch (grade) {
case 'A': document.write("Good job<br />");
break;
case 'B': document.write("Pretty good<br />");
break;
case 'C': document.write("Passed<br />");
break;
case 'D': document.write("Not so good<br />");
break;
case 'F': document.write("Failed<br />");
break;
IT ELEC 1|40
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Entering switch block
Good job
Exiting switch block
Set the variable to different value and then try...
JavaScript Loops
Loops are handy, if you want to run the same code over and over again, each time with a different value.
Instead of writing:
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";
You can write:
var i;
for (i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
IT ELEC 1|41
The For Loop
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed.
Example
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
JavaScript For In
The For/In Loop
Syntax
for (key in object) {
// code block to be executed
}
Example
var person = {fname:"John", lname:"Doe", age:25};
IT ELEC 1|42
JavaScript For Of
The For/Of Loop
The JavaScript for/of statement loops through the values of an iterable object.
It lets you loop over iterable data structures such as Arrays, Strings, Maps, NodeLists, and more:
Syntax
for (variable of iterable) {
// code block to be executed
}
variable - For every iteration the value of the next property is assigned to the variable. Variable can be
declared with const, let, or var.
The while loop loops through a block of code as long as a specified condition is true.
Syntax
while (condition) {
// code block to be executed
}
Example
In the following example, the code in the loop will run, over and over again, as long as a variable (i) is less
than 10:
IT ELEC 1|43
Example
while (i < 10) {
text += "The number is " + i;
i++;
}
The break Statement
The break statement, which was briefly introduced with the switch statement, is used to exit a loop early,
breaking out of the enclosing curly braces.
Flow Chart
The flow chart of a break statement would look as follows −
Example
The following example illustrates the use of a break statement with a while loop. Notice how the loop
breaks out early once x reaches 5 and reaches to document.write (..) statement just below to the
closing curly brace −
<html>
<body>
<script type = "text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20) {
if (x == 5) {
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
IT ELEC 1|44
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Entering the loop
2
3
4
5
Exiting the loop!
Set the variable to different value and then try...
Function Definition
Before we use a function, we need to define it. The most common way to define a function in JavaScript
is by using the function keyword, followed by a unique function name, a list of parameters (that might be
empty), and a statement block surrounded by curly braces.
Syntax
The basic syntax is shown here.
<script type = "text/javascript">
<!--
function functionname(parameter-list) {
statements
}
//-->
</script>
Example
Try the following example. It defines a function called sayHello that takes no parameters −
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello there");
}
//-->
</script>
IT ELEC 1|45
What is an Event ?
JavaScript's interaction with HTML is handled through events that occur when the user or the browser
manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other
examples include events like pressing any key, closing a window, resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which cause buttons to close
windows, messages to be displayed to users, data to be validated, and virtually any other type of
response imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set
of events which can trigger JavaScript Code.
Please go through this small tutorial for a better understanding HTML Event Reference. Here we will see
a few examples to understand a relation between Event and JavaScript −
onclick Event Type
This is the most frequently used event type which occurs when a user clicks the left button of his mouse.
You can put your validation, warning etc., against this event type.
Example
Try the following example.
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>
</body>
</html>
Output
Hello Word
IT ELEC 1|46
What are Cookies ?
Web Browsers and Servers use HTTP protocol to communicate and HTTP is a stateless protocol. But for
a commercial website, it is required to maintain session information among different pages. For example,
one user registration ends after completing many pages. But how to maintain users' session information
across all the web pages.
In many situations, using cookies is the most efficient method of remembering and tracking preferences,
purchases, commissions, and other information required for better visitor experience or site statistics.
Cookies are a plain text data record of 5 variable-length fields −
Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor
quits the browser.
Domain − The domain name of your site.
Path − The path to the directory or web page that set the cookie. This may be blank if you want to
retrieve the cookie from any directory or page.
Secure − If this field contains the word "secure", then the cookie may only be retrieved with a
secure server. If this field is blank, no such restriction exists.
Name=Value − Cookies are set and retrieved in the form of key-value pairs
Example
<html>
<head>
<script type = "text/javascript">
<!--
function WriteCookie() {
if( document.myform.customer.value == "" ) {
alert("Enter some value!");
return;
}
cookievalue = escape(document.myform.customer.value) + ";";
document.cookie = "name=" + cookievalue;
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie();"/>
</form>
</body>
IT ELEC 1|47
</html>
IT ELEC 1|48
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "Warn();" />
</form>
</body>
</html>
Void is an important keyword in JavaScript which can be used as a unary operator that appears before
its single operand, which may be of any type. This operator specifies an expression to be evaluated
without returning a value.
Syntax
The syntax of void can be either of the following two −
<head>
<script type = "text/javascript">
<!--
void func()
javascript:void func()
or:
void(func())
javascript:void(func())
//-->
</script>
</head>
Example 1
The most common use of this operator is in a client-side javascript: URL, where it allows you to evaluate
an expression for its side-effects without the browser displaying the value of the evaluated expression.
Here the expression alert ('Warning!!!') is evaluated but it is not loaded back into the current document
−
<html>
<head>
<script type = "text/javascript">
<!--
//-->
</script>
</head>
<body>
<p>Click the following, This won't react at all...</p>
<a href = "javascript:void(alert('Warning!!!'))">Click me!</a>
IT ELEC 1|49
</body>
</html>
Page printing Many times you would like to place a button on your webpage to print the content of that
web page via an actual printer. JavaScript helps you to implement this functionality using
the print function of window object.
The JavaScript print function window.print() prints the current web page when executed. You can call
this function directly using the onclick event as shown in the following example.
Example
Try the following example.
<html>
<head>
<script type = "text/javascript">
<!--
//-->
</script>
</head>
<body>
<form>
<input type = "button" value = "Print" onclick = "window.print()" />
</form>
</body>
<html>
Introduction
This module entitled Javascript Objects is about an object. Booleans can be objects (if defined
with the new keyword) Numbers can be objects (if defined with the new keyword) Strings can be objects
(if defined with the new keyword) Dates are always objects. Maths is always objecting. Regular
expressions are always objecting.
IT ELEC 1|50
Date and Time Allotment
I. Objectives
At the end of the end of this module, students should be able to:
1. Identify the web standards and W3C recommendation
2. Learn HTML
3. Use the different html tags in building a web page.
II. Lecture
JavaScript Objects
- You have already learned that JavaScript variables are containers for data values.
- In JavaScript, objects are king. If you understand objects, you understand JavaScript.
- Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named car:
The values are written as name:value pairs (name and value separated by a colon).
JavaScript objects are containers for named values called properties or methods.
Object Definition
- You define (and create) a JavaScript object with an object literal:
Example:
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Spaces and line breaks are not important. An object definition can span multiple lines:
IT ELEC 1|51
Example:
var person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
Object Properties
The name:values pairs in JavaScript objects are called properties:
Or
Example1
Example2
IT ELEC 1|52
Example3
Object Methods
- Objects can also have methods.
- Methods are actions that can be performed on objects.
- Methods are stored in properties as function definitions.
IT ELEC 1|53
- Read more about the this keyword at JS this Keyword.
If you access a method without the () parentheses, it will return the function definition:
JavaScript Numbers
- JavaScript has only one type of number. Numbers can be written with or without decimals.
Extra large or extra small numbers can be written with scientific (exponent) notation:
IT ELEC 1|54
- JavaScript numbers are always stored as double precision floating point numbers, following the
international IEEE 754 standard.
This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the
exponent in bits 52 to 62, and the sign in bit 63:
Precision
- Integers (numbers without a period or exponent notation) are accurate up to 15 digits.
IT ELEC 1|55
If you add two numbers, the result will be a number:
Numeric Strings
JavaScript strings can have numeric content:
Trying to do arithmetic with a non-numeric string will result in NaN (Not a Number):
IT ELEC 1|56
However, if the string contains a numeric value , the result will be a number:
Infinity
Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible
number.
Hexadecimal
- JavaScript interprets numeric constants as hexadecimal if they are preceded by 0x.
var x = 123;
But numbers can also be defined as objects with the keyword new:
IT ELEC 1|57
JavaScript Booleans
A JavaScript Boolean represents one of two values: true or false.
Boolean Values
Very often, in programming, you will need a data type that can only have one of two values, like
YES / NO
ON / OFF
TRUE / FALSE
For this, JavaScript has a Boolean data type. It can only take the values true or false.
You can use the Boolean() function to find out if an expression (or a variable) is true:
Or even easier:
IT ELEC 1|58
Here are some examples:
JavaScript Strings
- JavaScript strings are used for storing and manipulating text.
- A JavaScript string is zero or more characters written inside quotes.
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
String Length
IT ELEC 1|59
Escape Character
Because strings must be written within quotes, JavaScript will misunderstand this string:
The solution to avoid this problem, is to use the backslash escape character.
The backslash (\) escape character turns special characters into string characters:
JavaScript Arrays
JavaScript arrays are used to store multiple values in a single variable.
What is an Array?
An array is a special variable, which can hold more than one value at a time.
IT ELEC 1|60
If you have a list of items (a list of car names, for example), storing the cars in single variables could look
like this:
However, what if you want to loop through the cars and find a specific one? And what if you had not 3
cars, but 300?
An array can hold many values under a single name, and you can access the values by referring to an
index number.
Creating an Array
Syntax:
By default, JavaScript will use the browser's time zone and display a date as a full text string:
IT ELEC 1|61
new Date()
new Date() creates a new date object with the current date and time:
new Date(year, month, ...) creates a new date object with a specified date and time.
7 numbers specify year, month, day, hour, minute, second, and millisecond (in that order):
Math.round()
IT ELEC 1|62
Math.pow()
Math.sqrt()
Math.abs()
- When you search for data in a text, you can use this search pattern to describe what you are
searching for.
- A regular expression can be a single character, or a more complicated pattern.
- Regular expressions can be used to perform all types of text search and text
replace operations.
IT ELEC 1|63
Syntax
/pattern/modifiers;
Example explained:
/w3schools/i is a regular expression.
w3schools is a pattern (to be used in a search).
i is a modifier (modifies the search to be case-insensitive).
In JavaScript, regular expressions are often used with the two string methods: search() and replace().
The search() method uses an expression to search for a match, and returns the position of the match.
The replace() method returns a modified string where the pattern is replaced.
The search() method searches a string for a specified value and returns the position of the match:
When a web page is loaded, the browser creates a Document Object Model of the page.
IT ELEC 1|64
The HTML DOM model is constructed as a tree of Objects:
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
V. Other References
Shelly, Gary B., Denise M. Woods, Willaim J. Dorin., HTML5 and CSS comprehensive 7 th Edition.,
Course Technology. 2013.Brian P. Hogan - HTML5 and CSS3: Develop with Tomorrow's
Standard Today, 2010 The Pragmatic Bookshelf, Dalas Texas
IT ELEC 1|65
Towers, J. Tarin– Macromedia Dreamweaver for Windows & Macintosh, 2005 USA: Peach pit
Press
Vaswani, Vikram– How to Do Everything with PHP and MySQL, 2005 McGraw-Hill/Osborne
Michael Morrison - Head First JavaScript 2008: O'REILLY
https://www.w3schools.com/js/js_objects.asp
https://www.w3schools.com/js/js_object_definition.asp
https://www.w3schools.com/js/js_numbers.asp
https://www.w3schools.com/js/js_regexp.asp
https://www.w3schools.com/js/js_htmldom.asp
https://www.w3schools.com/js/js_booleans.asp
https://www.w3schools.com/js/js_strings.asp
https://www.w3schools.com/js/js_arrays.asp
https://www.w3schools.com/js/js_dates.asp
https://www.w3schools.com/js/js_math.asp
ACTIVITY 1 – 2
1. What is JavaScript?
2. Enumerate the differences between Java and JavaScript?
3. What are JavaScript Data Types?
4. What is the use of isNaN function?
5. Between JavaScript and an ASP script, which is faster?
6. What is negative infinity?
7. Is it possible to break JavaScript Code into several lines?
8. Which company developed JavaScript?
9. What are undeclared and undefined variables?
10. Write the code for adding new elements dynamically?
ACTIVITY 3 – 4
1. What are global variables? How are these variables declared and what are the problems associated
with using them?
2. What is a prompt box?
3. What is 'this' keyword in JavaScript?
4. Explain the working of timers in JavaScript? Also elucidate the drawbacks of using the timer, if any?
5. Which symbol is used for comments in Javascript?
6. What is the difference between ViewState and SessionState?
7. What is === operator?
8. Explain how can you submit a form using JavaScript?
9. Does JavaScript support automatic type conversion?
10. How can the style/class of an element be changed?
IT ELEC 1|66
ASSESSMENT 1 – 4
Create a basic game using java script
upload the code and screen shot
Prepared by:
Checked by:
IT ELEC 1|67