CSS and JavaScript Basics Guide
CSS and JavaScript Basics Guide
of CSE ICCSCEM
Assignment 2:
1 Write html code to align an image using css CO2 K3 2 Write examples for
javascript object creation using CO2 K3 a. object literal
b. instance of object
c. object constructor
Tutorial 2:
MODULE 2
INTRODUCTION TO CSS
CSS Syntax
2
CST 463 Web Programming
The id selector uses the id attribute of an HTML element to select a specific element. 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":
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. The CSS Universal
Selector
The universal selector (*) selects all HTML elements on the page.
3
CST 463 Web Programming
Dept. of CSE ICCSCEM
The CSS Grouping Selector
The grouping selector selects all the HTML elements with the same style definitions. Look
at the following CSS code (the h1, h2, and p elements have the same style definitions):
It will be better to group the selectors, to minimize the code. To group selectors, separate each selector
with a comma.
4
CST 463 Web Programming
Dept. of CSE ICCSCEM
External CSS
Internal CSS
Inline CSS
Inline CSS
An inline style may be used to apply a unique style for a single element.
To use inline styles, add the style attribute to the relevant element. The style attribute can contain any
CSS property.
Internal CSS
An internal style sheet may be used if one single HTML page has a unique style. The internal style
is defined inside the <style> element, inside the head section.
5
CST 463 Web Programming
Dept. of CSE ICCSCEM
External CSS
With an external style sheet, you can change the look of an entire website by changing just
one file!
Each HTML page must include a reference to the external style sheet file inside the
6
CST 463 Web Programming
Dept. of CSE ICCSCEM
COLORS
CSS uses color values to specify a color. Typically, these are used to set a color either for the foreground
of an element or else for the background of the element. They can also be used to affect the color of
borders and other decorative effects. You can specify your color values in various formats.
A hexadecimal is a 6 digit representation of a color. The first two digitsRR represent a red value, the next
two are a green valueGG, and the last are the blue valueBB. A hexadecimal value can be taken from any
graphics software like Adobe Photoshop, Jasc Paintshop Pro, or even using Advanced Paint Brush. Each
hexadecimal code will be preceded by a pound or hash sign '#'. Following are the examples to use
Hexadecimal notation.
Ex: #FFFF00
CSS Colors - RGB Values
This color value is specified using the rgb property. This property takes three values, one each for red,
green, and blue. The value can be an integer between 0 and 255 or a percentage.
NOTE: All the browsers does not support rgb property of color so it is recommended not to use it.
Ex: rgb255, 0, 255
This color value is specified using the rgba(red,green,blue,alpha) [Link] alpha value which
represents opacity—can be any value in the range 0.0(fully transparent) through 1.0(fully opaque).
Ex: rgba(255,0,0,0.5)
HSL (hue,saturation,lightness)
7
CST 463 Web Programming
Dept. of CSE ICCSCEM
HSLA(hue,saturation,lightness,alpha)
The hue is a color or shade expressed as a value from 0 to 359 representing the degree on a color
[Link] colors on the wheel progress in the ode of the colors of the rainbow.
The saturation- the intensity of the hue is expressed as a percentage,where 100% is fully saturated and
0% is gray.
Lightness- the intensity of light or luminance of the hue
FONT PROPPERTIES
8
CST 463 Web Programming
Dept. of CSE ICCSCEM
font-size: large;
}
div.c {
font-size: 150%;
}
{
font-style: oblique;
}
position property
9
CST 463 Web Programming
Dept. of CSE ICCSCEM
The position property determines which of the positioning schemes is used to calculate the
position of a box. Values other than static make the box a positioned box, and cause it
to establish an absolute positioning containing block for its descendants. Values have
the following meanings:
static: The box is not a positioned box, and is laid out according to the rules of its parent formatting
context. The inset properties do not apply.
relative: The box is laid out as for static, then offset from the resulting position. This offsetting is a purely
visual effect, and does not affect the size or position of any other box, except insofar as it increases the
scrollable overflow area of its ancestors. This positioning scheme is called relative positioning.
Sticky: Identical to relative, except that its offsets are properties) in whichever axes
automatically adjusted in reference to the nearest ancestor the inset properties are not both auto, to try to keep the box
scroll container’s scrollport (as modified by the inset in view within its containing block as the user scrolls. This
positioning scheme is called sticky positioning.
absolute: The box is taken out of flow such that it has no impact on the size or position of its siblings and
ancestors, and does not participate in its parent’s formatting context.
Instead, the box is positioned and sized solely in reference to its absolute positioning containing
block, as modified by the box’s inset properties, see § 4 Absolute Positioning Layout Model. It
can overlap in-flow content or other absolutely positioned elements, and is included in the
scrollable overflow area of the box that generates is containing block. This positioning scheme is
called absolute positioning.
fixed: Same as absolute, except the box is positioned and sized relative to a fixed positioning containing
block (usually the viewport in continuous media, or the page area in paged media). The box’s position is
fixed with respect to this reference rectangle: when attached to the viewport it does not move when the
document is scrolled, and when attached to the page area is replicated on every page when the document
is paginated. This positioning scheme is called fixed positioning and is considered a subset of absolute
positioning.
The precise location of a positioned box is controlled by the inset properties: the physical inset
properties top, right, bottom, left; the flow-relative inset properties inset block-start, inset-inline-
start, inset-block-end,and inset-inline-end; and their shorthands, inset-block, inset-inline, and inset.
The interpretation of these inset properties varies by positioning scheme:
● for absolute positioning, they represent insets from the containing block.
● for relative positioning, they represent insets from the box’s original margin edge.
● for sticky positioning, they represent insets from the scrollport edge.
Relative Positioning
For a relatively positioned box, the inset properties move the box inward from the
respective edge, without changing its size. left moves the box to the right, right
moves it to the left, etc. Since boxes are not split or stretched as a result of relative
positioning opposing used values in a given axis must be negations of each other:
10
CST 463 Web Programming
Dept. of CSE ICCSCEM
● If opposing inset properties in an axis both compute to auto (their initial values),
their used values are zero (i.e., the boxes stay in their original position in that axis).
● If only one is auto, its used value becomes the negation of the other, and the box is
shifted by the specified amount.
● If neither is auto, the position is over-constrained; (with respect to the writing mode
of its containing block) the computed end side value is ignored, and its used value
becomes the negation of the start side.
Sticky positioning
For a sticky positioned box, the inset properties represent insets from the respective
edges of the nearest scrollport, defining the sticky view rectangle used to constrain
the box’s position. (For this purpose an auto value represents a zero inset.) If this
results in a sticky view rectangle size in any axis less than the size of the border box
of the sticky box in that axis, then the effective end-edge inset in the affected axis is
reduced (possibly becoming negative) to bring the sticky view rectangle’s size up
to the size of the border box in that axis (where end is interpreted relative to the
writing mode of the containing block).
Absolute (and Fixed) Positioning
For an absolutely positioned box, the inset properties effectively reduce the
containing block into which it is sized and positioned by the specified amounts.
If only one inset property in a given axis is auto, it is set to zero. If both inset
properties in a given axis are auto, then, depending on the box’s self-alignment
property in the relevant axis (treating normal as start and any distributed, baseline,
or stretch alignment value as its fallback alignment):
11
CST 463 Web Programming
Dept. of CSE ICCSCEM
● for self-start alignment or its equivalent Set its start-edge inset property to the static position,
and its end-edge inset property to zero.
● for self-end alignment or its equivalent Set its end-edge inset property to the static position, and
its start-edge inset property to zero.
● for center alignment Let start distance be the distance from the center of its static position
rectangle to the start edge of its containing block, and end distance be the distance from the
center of its static position rectangle to the end edge of its containing block. If start distance is
less than or equal to end distance, then set the start-edge inset property to zero, and set the
end-edge inset property to (containing block size - 2 × |start distance|); otherwise, set the end-
edge inset property to zero and the start-edge inset property to (containing block size - 2 × |end
distance|)
If these adjustments result in an effective containing block size in any axis less than
zero, then the weaker inset in the affected axis is reduced (possibly becoming negative) to
bring that size up to zero. In the case that only one inset is auto, that is the weaker inset;
otherwise the weaker inset is the inset of the end edge (where end is interpreted relative to
the writing mode of the containing block).
If its self-alignment property in an axis is normal, then the resolved value of its
weaker inset in that axis is the value necessary to match that edge of its inset-modified
containing block to the corresponding edge of its margin box after layout.
Block Layout
The static position rectangle is a zero-thickness rectangle spanning between the
inline-axis sides of the box’s static-position containing block; and positioned at its block
start static position.
Inline Layout
The static position rectangle is a zero-thickness rectangle spanning between the
line- over/line-under sides of the line box that would have contained its “hypothetical box”;
and positioned at its inline-start static position.
Flex Layout
The static position rectangle of the child of a flex container corresponds to the
content edges of the flex container.
Grid Layout
By default, the static position rectangle of the child of a grid container corresponds
to the content edges of the grid container. However, if that grid container also establishes
the box’s actual containing block, then the grid area specified by the grid-placement
properties establishes its static position rectangle instead.
For the purposes of calculating the static position rectangle, the containing block of
fixed positioned elements is the initial containing block instead of the viewport, and all
scroll containers should be assumed to be scrolled to their initial scroll position.
Additionally, all auto margins on the box itself are treated as zero.
12
CST 463 Web Programming
Dept. of CSE ICCSCEM
Eg:
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>cell padding</title>
5. <style>
6. div {
7. width: auto;
8. text-align: center;
9. padding: 15px;
10. border: 3px solid red
11. }
12. img {
13. max-width: 100%;
14. height: auto;
15. }
16. </style>
17. </head>
18. <body>
19. <div>
20. <img src= "[Link]">
21. </div>
22. </body>
23. </html>
13
CST 463 Web Programming
Dept. of CSE ICCSCEM
Output
How to align images in CSS?
Images are an important part of any web application. Including a lot of images in a web
application is generally not recommended, but it is important to use the images wherever they
required. CSS helps us to control the display of images in web applications.
Aligning an image means to position the image at center, left and right. We can use the float
property and text-align property for the alignment of images.
If the image is in the div element, then we can use the text-align property for aligning the
image in the div.
Example
In this example, we are aligning the images by using the text-align property. The images are
in the div element
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <style>
5. div {
6. border: 2px solid
red; 7. }
8. img{
9. height: 250px;
10. width: 250px;
14
CST 463 Web Programming
Dept. of CSE ICCSCEM
11. }
12. #left {
13. text-align: left;
14. }
15. #center {
16. text-align: center;
17. }
18. #right{
19. text-align: right;
20. }</style>
21. </head>
22. <body>
23. <div id ="left">
24. <img src="[Link]">
25. </div>
26. <div id ="center">
27. <img src="[Link]">
28. </div>
29. <div id ="right">
30. <img src="[Link]">
31. </div>
32. </body>
33. </html>
15
CST 463 Web Programming
Dept. of CSE ICCSCEM
Output
CSS helps us to control the display of images in web applications. The centering of images
or texts is a common task in CSS. To center an image, we have to set the value of margin- left and
margin-right to auto and make it a block element by using the display: block; property.
If the image is in the div element, then we can use the text-align: center; property for
aligning the image to center in the div.
The <img> element is said to be an inline element that can easily be centered by applying
the text-align: center; property of CSS to the parent element that contains it.
We can use the shorthand property margin and set it to auto for aligning the image at the
center, rather than using the margin-left and margin-right property.
Let's see how to center an image by applying text-align: center; property to its parent
element.
Example
In this example, we are aligning the images by using the text-align: center; property. The
image is in the div element.
How to center images in CSS?
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <style>
5. div {
6. border: 2px solid
red; 7. }
16
CST 463 Web Programming
Dept. of CSE ICCSCEM
8. img{
9. height: 300px;
10. width: 300px;
11. }
12. #center {
13. text-align: center;
14. }
15. </style>
16. </head>
17. <body>
18. <div id ="center">
19. <img src="[Link]">
20. </div>
21. </body>
22. </html>
Output
17
CST 463 Web Programming
Dept. of CSE ICCSCEM
The url() value of this property allows us to include a file path to any image. It will show the
element's background. We can use multiple images or a mixture of gradients and images for the
background. If the background-image is failed to load or if we are using the gradients, but they
are not supported on the corresponding browser then, we can use the fallback value (the value
used as the substitution) as the background color of the element.
Syntax
background-image: url();
Values
url(): It is the URL to the image. We can separate the URLs by a comma if we want to specify
more than one image.
Example:
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <style>
5. body {
6. background-image: url("[Link]");
7. background-c
olor: lightgray; 8. }
9. </style>
18
CST 463 Web Programming
Dept. of CSE ICCSCEM
10. </head>
11. <body>
12. </body>
13. </html>
Output
CSS Gradient
CSS gradient is used to display smooth transition within two or more specified colors.
19
CST 463 Web Programming
Dept. of CSE ICCSCEM
1. Linear gradients
2. Radial gradients
3. CSS Linear Gradient
.
The CSS3 linear gradient goes up/down/left/right and diagonally. To create a CSS3 linear
gradient, you must have to define two or more color stops. The color stops are the colors which are
used to create a smooth transition. Starting point and direction can also be added along with the
gradient effect.
CSS Radial Gradient
You must have to define at least two color stops to create a radial gradient. It is defined by its
center.
Media Queries
Media queries are a way to target browser by certain characteristics, features, and user
preferences, then apply styles or run other code based on those things. Perhaps the most common
media queries in the world are those that target particular viewport ranges and apply custom styles,
which birthed the whole idea of responsive design.
There are lots of other things we can target beside viewport width. That might be screen
resolution, device orientation, operating system preference, or even more among a whole bevy of
things we can query and use to style content
20
CST 463 Web Programming
Dept. of CSE ICCSCEM
INTRODUCTION TO JAVASCRIPT
21
CST 463 Web Programming
Dept. of CSE ICCSCEM
Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:
o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm
dialog box and prompt dialog box),
o Displaying clocks etc.
JavaScript Example
1. <script>
2. [Link]("Hello JavaScript by JavaScript");
3. </script>
JavaScript Comment
The JavaScript comments are meaningful way to deliver message. It is used to add
information about the code, warnings or suggestions so that end user can easily interpret the
code.
The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the browser.
Advantages of JavaScript comments
There are mainly two advantages of JavaScript comments.
1. To make code easy to understand It can be used to elaborate the code so that end user
can easily understand the code.
2. To avoid the unnecessary code It can also be used to avoid the code being executed.
Sometimes, we add the code to perform some action. But after sometime, there may
be need to disable the code. In such case, it is better to use comments.
1. Single-line Comment
2. Multi-line Comment
It is represented by double forward slashes (//). It can be used before and after the statement.
Let’s see the example of single-line comment i.e. added before the statement.
22
CST 463 Web Programming
Dept. of CSE ICCSCEM
1. <script>
2. // It is single line comment
3. [Link]("hello javascript");
4. </script>
JavaScript Multi line Comment
It can be used to add single as well as multi line comments. So, it is more convenient. It is
represented by forward slash with asterisk then asterisk with forward slash. For example: 1. /*
your code here */
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). 1.
After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.
1. var x = 10;
2. var _value="sonoo";
var 123=30;
2. var *aa=320;
23
CST 463 Web Programming
Dept. of CSE ICCSCEM
1 <script>
2 var x = 10;
3 var y = 20;
4 var z=x+y;
5 [Link](z);
6. </script>
Output of the above example
24
CST 463 Web Programming
Dept. of CSE ICCSCEM
JavaScript provides different data types to hold different types of values. There are two
types of data types in JavaScript.
1. Primitive data type
2. Non-primitive (reference) data type
JavaScript is a dynamic type language, means you don't need to specify type of the
variable because it is dynamically used by JavaScript engine. You need to use var here
to specify the data type. It can hold any type of values such as numbers, strings etc. For
example:
1. var a=40;//holding number
2. var b="Rahul";//holding string
There are five types of primitive data types in JavaScript. They are as follows: String represents
sequence of characters e.g. "hello"
Undefined
Number
Boolean
represents numeric values e.g. 100 represents boolean value
25
CST 463 Web Programming
Dept. of CSE ICCSCEM Object represents instance through which we can access members
Array
represents group of similar values represents regular
RegExp expression
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on
operands. For example:
1. var sum=10+20;
Here, + is the arithmetic operator and = is the assignment
operator. There are following types of operators in
JavaScript.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
Division 20/10 = 2
- Modulus (Remainder) 20%10 = 0
* Increment var a=10; a++; Now a = 11
++
Subtraction 20-10 = 10
--
Decrement var a=10; a--; Now a = 9
The JavaScript comparison operator compares the two operands. The comparison operators are as
follows:
== Is equal to 10==20 = false
!= Not equal to
27
CST 463 Web Programming
Dept. of CSE ICCSCEM
^
<<
>>
>>>
Bitwise XOR (10==20 ^ 20==33) = false Bitwise NOT (~10) = -10 Bitwise
||
Logical OR (10==20 || 20==33) = false Logical Not !
!
(10==20) = true
= Assign 10+10 = 20
%=
+=
(?:) Conditional Operator returns value based on the condition. It is like if-else.
JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function many
times to reuse the code.
Advantage of JavaScript function
There are mainly two advantages of JavaScript functions.
1. Code reusability: We can call a function several times so it save coding.
2. Less coding: It makes our program compact. We don’t need to write many lines
of code each time to perform a common task.
30
CST 463 Web Programming
Dept. of CSE ICCSCEM
Let’s see the simple example of function in JavaScript that does not has arguments.
1. <script>
2. function msg(){
3. alert("hello! this is
message"); 4. }
5. </script>
6. <input type="button" onclick="msg()" value="call function"/>
JavaScript Function Arguments
We can call function by passing arguments. Let’s see the example of function that has one
argument.
1. <script>
2. function getcube(number){
3. alert(number*number*num
ber);
4. }
5. </script>
6. <form>
7. <input type="button" value="click" onclick="getcube(4)"/>
8. </form>
31
CST 463 Web Programming
Dept. of CSE ICCSCEM
Syntax
Parameter
apply() It is used to call a function contains this value and a single array of arguments.
bind()
It is used to create a new function.
call()
It is used to call a function contains this value and an
toString() argument list. It returns the result in a form of a string.
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method).
For example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is an object-based language. Everything is an object in JavaScript. JavaScript is
template based not class based. Here, we don't create class to get the object. But, we direct
create objects.
Creating Objects in JavaScript
There are 3 ways to create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
1. object={property1:value1,property2:value2. propertyN:valueN}
Here, you need to create function with arguments. Each argument value can be assigned
in the current object by using this keyword.
1. <script>
2. function emp(id,name,salary){
3. [Link]=id;
4. [Link]=name;
5. [Link]=sa
lary; 6. }
10. </script>
35
CST 463 Web Programming
Dept. of CSE ICCSCEM
Here, you need to create instance of array by passing arguments in constructor so that we
don't have to provide value explicitly.
1. <script>
2. var emp=new Array("Jai","Vijay","Smith");
3. for (i=0;i<[Link];i++){
4. [Link](emp[i] +
"<br>"); 5. }
6. </script>
Output of the above example
concat() It returns a new array object that contains two or more merged arrays.
It copies the part of the given array with its own elements
copywithin() and returns the modif array.
36
CST 463 Web Programming
Dept. of CSE ICCSCEM
It maps all array elements via mapping function, then flattens
the result into a n array.
flat()
It fills elements into an array with static values.
flatMap() It creates a new array carrying the exact copy of another
array element.
fill() It returns the new array containing the elements that pass the
provided funct conditions.
from()
It returns the value of the first element in the given array that
filter() satisfies the specif condition.
It returns the index value of the first element in the given
array that satisfies specified condition.
find()
It invokes the provided function once for each element of an
findIndex() array. It checks whether the given array contains the
specified element.
forEach()
lastIndexOf() It calls the specified function for every array element and
returns the new array
JavaScript String
1) By string literal
The string literal is created using double quotes. The syntax of creating string using string
literal is given below:
1. <script>
2. var str="This is string literal";
3. [Link](str);
4. </script
>
38
CST 463 Web Programming
Dept. of CSE ICCSCEM
The syntax of creating string object using new keyword is given below:
1. <script>
2. var stringname=new String("hello javascript string");
3. [Link](stringname);
4. </script
>
Output:
hello javascript string
concat()
indexOf()
lastIndexOf() It provides the position of a char value present in the given string by searching
character from the last position.
search() It searches a specified regular expression in a given string and returns its position match occurs.
match() It searches a specified regular expression in a given string and returns that reg expression
if a match occurs.
replace() It replaces a given string with the specified replacement.
substr() It is used to fetch the part of the given string on the basis of the specified start position and
length.
substring() It is used to fetch the part of the given string on the basis of the specified index.
slice() It is used to fetch the part of the given string. It allows us to assign positive as negative index.
toLowerCase() It converts the given string into lowercase letter.
toLocaleLowerCase() It converts the given string into lowercase letter on the basis of host?s current locale.
toUpperCase() It converts the given string into uppercase letter.
toLocaleUpperCase() It converts the given string into uppercase letter on the basis of host?s current locale.
toString() It provides a string representing the particular object.
40
CST 463 Web Programming
Dept. of CSE ICCSCEM
JavaScript Number Object
The JavaScript number object enables you to represent a numeric value. It may be integer
or floating-point. JavaScript number object follows IEEE standard to represent the floating
point numbers.
By the help of Number() constructor, you can create number object in JavaScript. For example:
If value can't be converted to number, it returns NaN(Not a Number) that can be checked by
isNaN() method.
Output:
41
CST 463 Web Programming
Dept. of CSE ICCSCEM
JavaScript Number Methods
Let's see the list of JavaScript number methods with their description.
JavaScript Math
The JavaScript math object provides several constants and methods to perform
mathematical operation. Unlike date object, it doesn't have constructors.
42
CST 463 Web Programming
Dept. of CSE ICCSCEM
abs() It returns the absolute value of the given number.
acos()
It returns the arccosine of the given number in radians.
asin()
It returns the arcsine of the given number in radians.
atan()
It returns the arc-tangent of the given number in radians.
ceil() It returns a smallest integer value, greater than or equal to the
cos() given number. It returns the cosine of the given number.
exp() It returns the exponential form of the given number.
floor() It returns largest integer value, lower than or equal to the given number. log() It
The JavaScript date object can be used to get year, month and day. You can display a
timer on the webpage by the help of JavaScript date object.
You can use different Date constructors to create date object. It provides methods to get and
set day, month, year, hour, minute and seconds.
Constructor
1. Date()
2. Date(milliseconds)
43
CST 463 Web Programming
Dept. of CSE ICCSCEM
3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)
Let's see the list of JavaScript date methods with their description.
getDate() It returns the integer value between 1 and 31 that represents the day for the specify date
on the basis of local time.
44
CST 463 Web Programming
Dept. of CSE ICCSCEM
Decision Making and Loops
1. if(expression){
2. //content to be
evaluated 3. }
45
CST 463 Web Programming
Dept. of CSE ICCSCEM
1. <script>
2. var
a=20; 3.
if(a>10){
4. [Link]("value of a is greater than
10"); 5. }
6. </script>
It evaluates the content whether condition is true of false. The syntax of JavaScript if-else
statement is given below.
1. if(expression){
2. //content to be evaluated if condition is
true 3. }
46
CST 463 Web Programming
Dept. of CSE ICCSCEM
1. <script>
2. var a=20;
3. if(a%2==0){
4. [Link]("a is even number"); 5. }
6. else{
7. [Link]("a is odd
number"); 8. }
9. </script>
47
CST 463 Web Programming
Dept. of CSE ICCSCEM
JavaScript If...else if statement
It evaluates the content only if expression is true from several expressions. The signature of
JavaScript if else if statement is given below.
1. if(expression1){
2. //content to be evaluated if expression1 is
true 3. }
4. else if(expression2){
5. //content to be evaluated if expression2 is
true 6. }
7. else if(expression3){
8. //content to be evaluated if expression3 is
true 9. }
10. else{
11. //content to be evaluated if no expression is true
12. }
Let’s see the simple example of if else if statement in javascript.
1. <script>
2. var
a=20; 3.
if(a==10){
4. [Link]("a is equal to
10"); 5. }
48
CST 463 Web Programming
Dept. of CSE ICCSCEM
6. else if(a==15){
7. [Link]("a is equal to
15"); 8. }
9. else if(a==20){
10. [Link]("a is equal to 20");
11. }
12. else{
13. [Link]("a is not equal to 10, 15 or 20");
14. }
15. </script>
JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple expressions. It is
just like else if statement that we have learned in previous page. But it is convenient than
if..else..if because it can be used with numbers, characters etc.
1. switch(expression){
2. case value1:
3. code to be executed;
4. break;
5. case value2:
6. code to be executed;
7. br
eak; 8.
......
9.
10. default:
11. code to be executed if above values are not matched;
12. }
49
CST 463 Web Programming
Dept. of CSE ICCSCEM
1. <script>
2. var grade='B';
3. var result;
4. switch(grade){
5. case 'A':
6. result="A Grade";
7. break;
8. case 'B':
9. result="B Grade";
10. break;
11. case 'C':
12. result="C Grade";
13. break;
14. default:
15. result="No Grade";
16. }
17. [Link](result);
18. </script>
JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in
loops. It makes the code compact. It is mostly used in array.
1. for loop
2. while loop
50
CST 463 Web Programming
Dept. of CSE ICCSCEM
3. do-while loop
The JavaScript for loop iterates the elements for the fixed number of times. It should be used
if number of iteration is known. The syntax of for loop is given below.
1. <script>
2. for (i=1; i<=5;
i++) 3. {
4. [Link](i +
"<br/>") 5. }
6. </script>
Output:
The JavaScript while loop iterates the elements for the infinite number of times. It should be
used if number of iteration is not known. The syntax of while loop is given below.
1. while (condition)
51
CST 463 Web Programming
Dept. of CSE ICCSCEM
2. {
3. code to be
executed 4. }
1. <script>
2. var i=11;
3. while
(i<=15) 4. {
5. [Link](i +
"<br/>"); 6. i++;
7. }
8. </script>
Output:
3) JavaScript do while loop
The JavaScript do while loop iterates the elements for the infinite number of times like while
loop. But, code is executed at least once whether condition is true or false. The syntax of do
while loop is given below.
1. do{
2. code to be executed
3. }while (condition);
52
CST 463 Web Programming
Dept. of CSE ICCSCEM
1. <script>
2. var i=21;
3. do{
4. [Link](i +
"<br/>"); 5. i++;
6. }while (i<=25);
7. </script>
Output:
Browser Object Model
The Browser Object Model (BOM) is used to interact with the browser.
The default object of browser is window means you can call all the functions of window
by specifying window or directly. For example:
1. [Link]("hello javatpoint");
is same as:
1. alert("hello javatpoint");
You can use a lot of properties (other objects) defined underneath the window object like
document, history, screen, navigator, location, innerHeight, innerWidth,
53
CST 463 Web Programming
Dept. of CSE ICCSCEM
Document Object Model
When html document is loaded in the browser, it becomes a document object. It is the root
element that represents the html document. It has properties and methods. By the help of
document object, we can add dynamic content to our web page.
54
CST 463 Web Programming