0% found this document useful (0 votes)
0 views

WP Module 2 - CSS and Javascript

The document explains the use and advantages of Cascading Style Sheets (CSS) in web programming, detailing how CSS enhances the presentation of HTML documents by separating content from design elements. It covers CSS syntax, selectors, and methods for implementing CSS in web pages, along with basic properties such as font, color, and text formatting. Additionally, it introduces scripting languages, differentiating between client-side and server-side scripting, and their respective roles in web development.

Uploaded by

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

WP Module 2 - CSS and Javascript

The document explains the use and advantages of Cascading Style Sheets (CSS) in web programming, detailing how CSS enhances the presentation of HTML documents by separating content from design elements. It covers CSS syntax, selectors, and methods for implementing CSS in web pages, along with basic properties such as font, color, and text formatting. Additionally, it introduces scripting languages, differentiating between client-side and server-side scripting, and their respective roles in web development.

Uploaded by

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

Web Programming – Module 2

2.1.1 Explain the use of Cascading Style Sheets (CSS)

CSS stands for Cascading Style Sheets. It handles the look and feel part of a web page. It provides
powerful control over the presentation of an HTML document. It describes how HTML elements
are to be displayed on screen. It allows to separate visual design elements (layout, fonts, colors,
margins, and so on) from the contents of a Web page.

Advantages of CSS

1. CSS saves time − CSS is written once and can reuse in multiple HTML pages.

2. Pages load faster − CSS helps to avoid the rewriting of html tag attributes every time. The CSS
rules of a tag can be used to apply for all the occurrences of that tag. So less code means faster
download times.

3. Easy maintenance − To make a global change, simply change the style, and all elements in all
the web pages will be updated automatically.

4. Superior styles to HTML − CSS has a much wider array of a ributes than HTML, so we can give
a far better look to the HTML page in comparison to HTML attributes.

5. Multiple Device Compatibility − Style sheets allow content to be op mized for more than one
type of device. By using the same HTML document, different versions of a website can be
presented for handheld devices such as PDAs and cell phones or for printing.

6. Global web standards − Now HTML attributes are being deprecated and it is being
recommended to use CSS. So its a good idea to start using CSS in all the HTML pages to make
them compatible to future browsers.

7. Offline Browsing − CSS can store web applica ons locally with the help of an offline cache.
Using this, we can view offline websites. The cache also ensures faster loading and better overall
performance of the website.

8. Platform Independence − The Script offer consistent pla orm independence and can support
latest browsers as well.

2.1.2 Describe CSS syntax: A CSS comprises of style rules that are interpreted by the browser and then
applied to the corresponding elements in your document. A style rule is made of three parts −

 Selector − A selector is an HTML element tag at which a style will be applied. This could
be any tag like <h1> or <table> etc.

 Property - A property is a type of attribute of HTML tag. Put simply, all the HTML
attributes are converted into CSS properties. They could be color, border etc.

 Value - Values are assigned to properties. For example, color property can have value
either red or #F1F1F1 etc.

Web Programming Module 2 Page 1 of 15


CSS Style Rule Syntax
selector { property: value }

Example : table { border :1px solid #C00; }. Here table is a selector and border is a property and
given value 1px solid #C00 is the value of that property.

2.1.3 Explain CSS selectors: A selector is an HTML tag element in which a style will be
applied. CSS selectors are used to select HTML elements based on their element name, id, class,
attribute etc. Different types of selectors are used to apply styles to the html elements. They are

i) Element or Type Selector


ii) id selector
iii) Class Selector
iv) Group Selector

i) Element Selector: The element selector selects elements based on the element type. For
example to make all <p> elements on a page to be center-aligned, with a red text color, the
element selector is used as:
Ex: p{ text-align: center; color: red; }

ii) Id Selector: The id selector uses the id attribute of an HTML element to select a specific
element. The id of an element should be 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 : style rule to be applied to the HTML element with id="para1"
#para1 { text-align: center; color: red; }

iii) Class Selector:The class selector selects elements with a specific class attribute. To select elements
with a specific class, write a period (.) character, followed by the name of the class.
Ex: .center { text-align: center; color: red; }, all HTML elements with class="center" will be red
and center-aligned:
iv) Group Selectors: This is used to the style definitions to group of elements having same styles.
Example: h1, h2, p {
text-align: center;
color: red; }

2.1.4 Illustrate how to insert CSS in a web page (CSS Implementation)


CSS stands for Cascading Style Sheets. It describes how HTML elements are to be displayed on
screen, paper, or in other media. When a browser reads a style sheet, it will format the HTML
document according to the information in the style sheet. There are three ways of inserting a style
sheet:
i) Inline style sheets
ii) Internal or embedded style sheet
iii) External style sheet

a) Inline style sheet: 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. Example : <h1 style="color:blue;margin-left:30px;">This is a heading</h1>

Web Programming Module 2 Page 2 of 15


b) Internal or embedded style sheet: An internal style sheet may be used if one single page has a
unique style. Internal styles are defined within the <style> element, inside the <head> section of
an HTML page:
Example: <head>
<style>
body {
background-color: linen; }
h1 { color: maroon;
margin-left: 40px; }
</style>
</head>

c) External Style Sheet: With an external style sheet, we can change the look of an entire website by
changing just one external file in which the style rules are specified. The file should not contain any html
tags. The style sheet file must be saved with a .css extension. Each page in the website must include a
reference to the external style sheet file inside the <link> element. The <link> element goes inside the
<head> section.
Example:
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<h1>Style Applied from External Stylesheet</h1>
</body>
</html>

Mystyle.css file
body { background-color: lightblue; }

h1 { color: navy;
margin-left: 20px; }
2.1.5 Explain basic CSS properties – font, colour, background, list, link, text

a) CSS Fonts: It is used to set fonts of content, available in an HTML element. The following font
properties of an element can be set with CSS

i) The font-family property is used to change the face of a font.


Ex: <p style="font-family:georgia,garamond,serif;">
ii) The font-style property is used to make a font italic or oblique.
Ex: <p style="font-style:italic;">
iii) The font-variant property is used to create a small-caps effect.
Ex: <p style="font-variant:small-caps;">
iv) The font-weight property is used to increase or decrease how bold or light a font
appears. It can be used to specify how bold a font is. Possible values could be normal,
bold, bolder, lighter, 100, 200, 300, 400, 500, 600, 700, 800, 900.
Ex: <p style="font-weight:bold;">This font is bold.</p>
<p style="font-weight:bolder;">This font is bolder.</p>
<p style="font-weight:500;">This font is 500 weight.</p>
Web Programming Module 2 Page 3 of 15
v) The font-size property is used to increase or decrease the size of a font. The font-size
property is used to control the size of fonts. Possible values could be xx-small, x-small,
small, medium, large, x-large, xx-large, smaller, larger, size in pixels or in %.
Ex: <p style="font-size:20px;">This font size is 20 pixels</p>
<p style="font-size:small;">This font size is small</p>
<p style="font-size:large;">This font size is large</p>

vi) The font property is used as shorthand to specify all the font properties at once.
Ex: <p style="font:italic small-caps bold 15px georgia;">
Applying all the properties on the text at once. </p>

b) CSS Colors : CSS uses color values to specify a color. Typically, these are used to set a color
either for the foreground of an element (i.e., its text) or else for the background of the element.
They can also be used to affect the color of borders and other decorative effects. The color
values can be specified in various formats. Following table lists all the possible formats −
Format Syntax Example

Hex Code #RRGGBB p {color:#FF0000;}

Short Hex Code #RGB p{color:#6A7;}

RGB % rgb(rrr%,ggg%,bbb%) p{color:rgb(50%,50%,50%);}

RGB Absolute rgb(rrr,ggg,bbb) p{color:rgb(0,0,255);}

keyword aqua, black, etc. p{color:teal;}

c) CSS Lists : The CSS list properties allow to:


i) Set different list item markers for ordered lists
ii) Set different list item markers for unordered lists
iii) Set an image as the list item marker
iv) Add background colors to lists and list items

1) The list-style-type allows you to control the shape or appearance of the marker.
2) The list-style-position specifies whether a long point that wraps to a second line should
align with the first line or start underneath the start of the marker.
3) The list-style-image specifies an image for the marker rather than a bullet point or
number.
4) The list-style serves as shorthand for the preceding properties.
5) The marker-offset specifies the distance between a marker and the text in the list.
d) CSS Links : We can set following properties of a hyper link through CSS. Usually, all these
properties are kept in the header part of the HTML document.

 The :link signifies unvisited hyperlinks.


 The :visited signifies visited hyperlinks.

Web Programming Module 2 Page 4 of 15


 The :hover signifies an element that currently has the user's mouse pointer hovering
over it.
 The :active signifies an element on which the user is currently clicking.
Example : <style type="text/css">
a:link {color: #000000}
a:visited {color: #006600}
a:hover {color: #FFCC00}
a:active {color: #FF00CC}
</style>
e) CSS Texts
1) The color property is used to set the color of a text.
Ex: <p style="color:red;">
This text will be written in red. </p>
2) The direction property is used to set the text direction. Possible values are ltr or rtl.
Ex: <p style="direction:rtl;">
This text will be renedered from right to left </p>
3) The letter-spacing property is used to add or subtract space between the letters that make
up a word. Possible values are normal or a number specifying space.
Ex: <p style="letter-spacing:5px;">
This text is having space between letters. </p>
4) The word-spacing property is used to add or subtract space between the words of a
sentence. Possible values are normal or a number specifying space.
Ex: <p style="word-spacing:5px;">
This text is having space between words. </p>
5) The text-indent property is used to indent the text of a paragraph. Possible values are % or
a number specifying indent space.

6) The text-align property is used to align the text of a document. Possible values are left,
right, center, justify.
Ex: <p style="text-align:right;">
This will be right aligned. </p>
7) The text-decoration property is used to underline, overline, and strikethrough text.
Possible values are none, underline, overline, line-through, blink.
Ex: <p style="text-decoration:underline;">
This will be underlined </p>
8) The text-transform property is used to capitalize text or convert text to uppercase or
lowercase letters. Possible values are none, capitalize, uppercase, lowercase.

9) The white-space property is used to control the flow and formatting of text. It describes
how white space inside an element is handled. Possible values are normal, pre, nowrap.
10) The text-shadow property is used to set the text shadow around a text.
Ex: <p style="text-shadow:4px 4px 8px blue;">
If your browser supports the CSS text-shadow property, this text will have a blue
shadow. </p>

Web Programming Module 2 Page 5 of 15


2.1.6 Implement CSS in web pages
****Assignment ****

2.1.7 State the need for scripting languages: Scripting language is a high-level programming
language that is interpreted at runtime by some other application program rather
than compilation procedures as in normal programming languages. Scripting languages, which
can be embedded within HTML, can be used to add functionality to a web page, such as different
menu styles or graphic displays or to serve dynamic advertisements. They are also used to
manipulate the data, usually in a database, on the server.

2.1.8 Define server side scripting and client side scripting

A. Client side Scripting: The client-side scripting is used to run scripts in a browser of the client
machine. The processing takes place on the end users computer. It is the collection of objects that
support the control of a browser and interactions with users.
Examples of client side scripting languages are VB Script, javascript etc.

The advantages of client side scripting are the following.

i. Transfer of computational load from server to clients: Client-side scripts can serve as an
alternative for some of what is done with server-side programming such as validation of user
inputs etc before submitting to the server. This transfer of load from the overloaded server to
the underloaded client can obviously benefit other clients.

ii. User Interactions: Interactions with users through form elements, such as buttons and menus,
can be conveniently done with client side scripting.

iii. Dynamic Web Pages: Client side scripts can be used to access and modify the CSS properties
and contents of the elements of a displayed XHTML document and making these static
documents to highly dynamic.

iv. Event driven Methods: In client side scripting the actions are executed in response to the
browser user’s actions such as mouse clicks, rollover, form submission etc.

B. Server side Scripting: Server side scripting is a method of designing websites so that the
process or user request is run on the server. Server side scripts provide an interface to the user
and are used to limit access the proprietary data. The user's request is fulfilled by running a script
directly on the web server to generate dynamic HTML pages. This HTML is then sent to the client
browser. It is usually used to provide interactive web sites that interface with databases or other
data stores on the server.

Examples of server side scripting languages are ASP, PHP, Perl, Python etc.

Server-side | Uses

 It processes the user input


 Displays the requested pages
 Structure web applications

Web Programming Module 2 Page 6 of 15


 Interaction with servers/storages
 Interaction with databases
 Querying the database
 Encoding of data into HTML
 Operations over databases like delete, update.

Working of Client side and server side scripts

When a client makes a request for a web page that information is processed by the web server. If
the request is a server side script, before the information is returned to the client, the script is
executed on the server and the result of the script is returned to the client as an HTML
document.

Once the client receives the returned information from the server if it contains a client side script
(ex. Javascript) the client browser executes that script before displaying the HTML document.

2.1.9 List client side scripting languages.

Client Side :- VB Script, Javascript, AJAX etc.


Server side scripting languages are ASP, PHP, Perl, Python etc.

2.1.10 Illustrate how JavaScript is used in an HTML page

JavaScript: JavaScript, earlier known as LiveScript, developed by Netscape is used as a scripting


language in both server and client sides. However, it is commonly used as a client side
programming tool.

Advantages of JavaScript
The merits of using JavaScript are −

a) Less server interaction – The user inputs can be validated before sending the page to the
server with javascript. This saves server traffic, which means less load to the server.

b) Immediate feedback to the visitors − They don't have to wait for a page reload to see if
they have forgotten to enter something.

c) Increased interactivity – With javascript, web pages can be designed that react with the
the user inputs such as the user hovers over different elements with a mouse or activates
them via the keyboard.

d) Richer interfaces − JavaScript can be used to include such items as drag-and-drop


components and sliders to give a Rich Interface to your site visitors.
2.1.11 Describe Programming elements in JavaScript

Javascript:

i) Data types: JavaScript has five primitive types: Number, String, Boolean, Undefined, and Null.

ii) Numerical Operators: JavaScript has the typical collection of numeric operators: the binary
operators + for addition, - for subtraction, * for multiplication, / for division, and % for modulus.
Web Programming Module 2 Page 7 of 15
The unary operators are plus (+), negate (-), decrement (--), and increment (++). The increment
and decrement operators can be either prefix or postfix.

iii) String Properties and Methods:


Method Parameters Result
charAt A number Returns the character in the String object that is at the
specified location
indexOf One-character string Returns the position in the String object of the parameter
Substring Two numbers Returns the substring of the string object from the first
parameter position to the second
toLowerCase None Converts any uppercase letters in the string to lower case
toUpperCase None Converts any lowercase letters in the string to uppercase

iv) Relational Operators


Operation Operator
is equal to ==
Is not equal to !=
is less than <
is greater than >
is less than or equal to <=
Is greater than or equal to >=
is strictly equal to ===
Is strictly not equal to !==

v) Selection Statements:
if (a>b) document.write(“a is greater than b <br />”);
else { a=b;
document.write(“a was not greater than b <br />”, Now they are equal <br />); }

vi) Switch Statements:


switch (expression) {
case value_1: //statement(s)
case value_2: //statement(s)
......
default: //statement(s) }

vii) Loop Statements:


a) While (control expression)
{ statement(s) }
b) for (initial expression; control expression; increment expression)
{ statement(s) }
***
2.1.12 Describe Document Object Model: The DOM is an application programming interface
(API) that defines an interface between HTML documents and application programs.
The Document Object Model (DOM) is a cross-platform and language-independent application
programming interface that treats an HTML, XHTML, or XML document as a tree
structure wherein each node is an object representing a part of the document. The objects can
be manipulated programmatically and any visible changes occurring as a result may then be
reflected in the display of the document.

Web Programming Module 2 Page 8 of 15


The HTML DOM is a standard object model and programming interface for HTML. It defines:
 The HTML elements as objects
 The properties of all HTML elements
 The methods to access all HTML elements
 The events for all HTML elements
In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML
elements.

With the object model, JavaScript gets all the power it needs to create dynamic HTML:
 JavaScript can change all the HTML elements in the page
 JavaScript can change all the HTML attributes in the page
 JavaScript can change all the CSS styles in the page
 JavaScript can remove existing HTML elements and attributes
 JavaScript can add new HTML elements and attributes
 JavaScript can react to all existing HTML events in the page
 JavaScript can create new HTML events in the page

In the html construct <input type=”text” name=”address” id=”address”>, the HTML element
would be represented as an object with properties, type, name and id, with the values “text”,
“address” and “address”, respectively.

Embedding Javascript in HTML: Javascript can be embedded in HTML pages in following ways
i) Internal scripts
ii) External Files
iii) External References

i) Internal Scripts: In this the javaScript code is inserted between <script> and </script> tags in
the same html file within head or body tag.
Example: <script type = "text/javascript">
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>

ii) External Files: In this the script is stored in some external file with ‘.js’ extension and it is
included in the script tag with src attribute. Scripts are stored in external files when the same
script is called in more than one html pages.

Example: <script type = "text/javascript" src="myScript1.js"></script>

Web Programming Module 2 Page 9 of 15


Advantages:

1. Code Reusability
2. It separates HTML and code
3. It makes HTML and JavaScript easier to read and maintain
4. Cached JavaScript files can speed up page loads

iii) External References: External scripts can be referenced with a full URL or with a path relative to
the current web page.
Example: <script type = "text/javascript" src="https://www.w3schools.com/js/myScript1.js">
</script>
2.1.13 Explain how Event Handling is done using JavaScript

One important use of JavaScript for Web programming is to detect certain activities of the
browser and the browser user and provide computation when those activities occur. These
computations are specified with a special form of programming called event-driven
programming.

An event is a notification that something specific has occurred, either with the browser, such as
the completion of the loading of a document, or because of a browser user action, such as a
mouse click on a form button. An event is an object that is implicitly created by the browser and
the JavaScript system in response to something happening.

An event handler is a script that is implicitly executed in response to the appearance of an event.
Event handlers enable a Web document to be responsive to browser and user activities. One of
the most common uses of event handlers is to check for simple errors and omissions in user
input to the elements of a form, either when they are changed or when the form is submitted.
This kind of checking saves the time of sending incorrect form data to the server.

There are two ways to register an event handler in the DOM event model.
i) Assigning the event handler script to an event tag attribute.
Example: <input type=”button” id=”myButton” onclick=”alert(‘Clicked the Button’);” />

ii) Using Event handling functions: In case the handler consists of more than a single statement,
a function can be used and the literal string value of the attribute is the call to the function.
Consider the following example of a button element:
Example: <input type=”button” id=”myButton” onclick=”buttonHandler();” />

 List of various java events and its tag attributes


Event Tag Attribute Event Tag Attribute
blur onblur change onchange
click onclick dblclick ondblclick
focus onfocus keydown onkeydown
keypress onkeypress keyup onkeyup
load onload mousedown onmousedown
mousemove onmousemove mouseout onmouseout
mouseover onmouseover mouseup onmouseup
reset onreset select onselect
submit onsubmit unload onunload
Web Programming Module 2 Page 10 of 15
2.1.14 Explain how input data validations are done using JavaScript: JavaScript is widely used
for input data validations. Validation means to verify the user input values in web forms are
sensible. Without client-side checks of such values, the erroneous form values will be
transmitted to the server for processing. The server side script that processes this erroneous
data may behave indifferently or returns error message to the client. When invalid data is found,
the server informs the client to resubmit with modified input. It is obviously more efficient to
perform input data checks and carry on the user dialog entirely on the client. This approach
shifts some processing burden from the busy server to the client. It also reduces unnecessary
network traffic. Furthermore, proper input data validation increases server response to users.

When a user fills in a web form, a javascript event handler function can be utilised for input
data validation. If any error is detected by the validation function, it produces an alert message
to the user indicating the error in the input. Next, it would be good to focus the invalid data
element for correction.

Advantages of input data validation


1) Removes unwanted processing burden from the busy server.
2) Reduces unnecessary data traffic.
3) Increased server response.
4) Avoids indifferent server response.
5) Ensures data integrity.

Example: Event handling and data validation (validate mail address)


<html>
<head>
<title> Event Handling and Data Validation</title>
<script type = "text/javascript" >
function validateEmail()
{ var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 )) {
alert("Please enter correct email ID");
document.myForm.EMail.focus() ;
return false; }
return( true ); }
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") { alert("Name must be filled out");
document.myForm.fname.focus() ;
return false; }
validateEmail(); }
</script> </head>
<body>
<form name="myForm" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname" id=”fname”>
E-mail: <input type="text" name="EMail" id=”Email”>
<input type="submit" value="Submit">
</form>
</body>
</html>
Web Programming Module 2 Page 11 of 15
2.1.15 Describe Dynamic Documents with JavaScript: A dynamic HTML document is an HTML
document that can be changed while it is being displayed by a browser. The most common client-side
approach to providing dynamic documents is to use JavaScript to manipulate the objects of the Document
Object Model (DOM) of the displayed document. Changes to documents can occur when they are
explicitly requested by user interactions or at regular timed intervals or when a browser event occurs.

HTML elements can be initially positioned at a given location on the browser display. In run time, these
elements can be dynamically moved to new positions, elements can be made to disappear and reappear,
the colors of the background and the foreground (the elements) of a document can be changed. The font,
font size, and font style of displayed text can be changed. Even the content of an element can be
changed. Overlapping elements in a document can be positioned in a specific top-to-bottom stacking
order, and their stacking order can be dynamically changed. The position of the mouse cursor on the
browser display can be determined when a mouse button is clicked. Elements can be made to move
slowly around the display screen. Finally, elements can be defined to allow the user to drag and drop
them anywhere in the display window.

Examples of Dynamic Documents

Ex. 1 Moving Elements: JavaScript can be used to move a number of DOM elements (<img />, <div> or
any other HTML element) around the page according to some sort of pattern determined by a logical
equation or function.

JavaScript provides the following two functions to be frequently used in animation programs.
 setTimeout( function, duration) − This func on calls function after duration milliseconds from
now.
 setInterval(function, duration) − This func on calls function after every duration milliseconds.
 clearTimeout(setTimeout_variable) − This func on calls clears any mer set by the setTimeout()
functions.
JavaScript can also set a number of attributes of a DOM object including its position on the screen. The
top and left attribute of an object can be set up to position it anywhere on the screen
Sample Code:

<html>
<head>
<title>JavaScript Animation</title>
<script type = "text/javascript">
<!-- var imgObj = null;
var animate ;
var moveDirection="right";
function init() {
imgObj = document.getElementById('myImage');
imgObj.style.position= 'relative';
imgObj.style.left = '0px'; }
function move() {
if (moveDirection=="right") {
if (parseInt(imgObj.style.left) > 500) moveDirection="left";
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
animate = setTimeout(move,20); // call move in 20msec }
else {
if (parseInt(imgObj.style.left) < 10) moveDirection="right";
imgObj.style.left = parseInt(imgObj.style.left) - 10 + 'px';
animate = setTimeout(move,20); // call move in 20msec } }
Web Programming Module 2 Page 12 of 15
function stop() {
clearTimeout(animate);
imgObj.style.left = '0px'; }
window.onload = init; //-->
</script> </head>
<body>
<form>
<img id = "myImage" src = "images\tenor.gif" />
<p>Click the buttons below to handle animation</p>
<input type = "button" value = "Start" onclick = "move();" />
<input type = "button" value = "Stop" onclick = "stop();" />
</form>
</body>
</html>
Ex. 2 Element Visibility: Document elements can be specified to be visible or hidden with the value of
their visibility property. The two possible values for visibility are visible and hidden. The appearance or
disappearance of an element can be controlled by the user through a widget.

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px; }
</style>
</head>
<body>
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="toggleVisibility()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<script>
function toggleVisibility() {
var x = document.getElementById("myDIV");
if (x.style.visibility == 'hidden') x.style.visibility = 'visible';
else x.style.visibility = 'hidden'; }
</script>
</body>
</html>
Ex. 3 Changing colours: Javascript and CSS can be used to change the colours of various DOM elements
with different color style properties.
Example:
<!DOCTYPE html>
<html >
<head>
<title>Change the Background Color with JavaScript</title>
<script>
function changeBodyBg(color){ // Function to change webpage background color
document.body.style.background = color; }

Web Programming Module 2 Page 13 of 15


function changeHeadingBg(color) { // Function to change heading background color
document.getElementById("heading").style.background = color; }
</script>
</head>
<body>
<h1 id="heading">This is a heading</h1>
<p>This is a paragraph of text.</p>
<hr>
<div>
<label>Change Webpage Background To:</label>
<button type="button" onclick="changeBodyBg('yellow');">Yellow</button>
<button type="button" onclick="changeBodyBg('lime');">Lime</button>
<button type="button" onclick="changeBodyBg('orange');">Orange</button>
</div>
<br>
<div>
<label>Change Heading Background To:</label>
<button type="button" onclick="changeHeadingBg('red');">Red</button>
<button type="button" onclick="changeHeadingBg('green');">Green</button>
<button type="button" onclick="changeHeadingBg('blue');">Blue</button>
</div>
</body>
</html>
Ex. 4 Changing Fonts: Use of the mouseover event to trigger a JavaScript event handler allows us to
change any property of any element in a document, including text, when the mouse cursor is placed over
it. Thus, the font style and font size, as well as the color and background color of text, can be changed
when the cursor is placed over the text. The text can be changed back to its original form when an event
handler is triggered with the mouseout event.

<html>
<head>
<title> Dynamic Fonts </title>
<style type="text/css">
.regText {font: 16pt 'Times New Roman';}
.wordText {color:blue;}
</style>
</head>
<body>
<p class "regText">
WE ARE
<span class = "wordText";
onmouseover = "this.style.color='red';
this.style.fontStyle='italic';
this.style.fontSize='24pt';"
onmouseout= "this.style.color='green';
this.style.fontStyle='normal';
this.style.fontSize='16pt';">
PROGRAMMERS
</span>
IN FUTURE.
</p>
</body>
</html>

Web Programming Module 2 Page 14 of 15


Ex. 5 Dynamic Contents: Dynamically adding contents (elements) to web pages. The sample program to
add/remove div elements with a label and text box to a web page is given below.

<html>
<head>
<title>Dynamic Content through javascript</title>
<script>

var intTextBox = 0; //Counter to maintain number of textboxes and give them unique id for later reference

/* Function to add textbox element dynamically, First we incrementing the counter and creating new div element
with unique id, then adding new textbox element to this div and finally appending this div to main content. */
function addElement() {
intTextBox++;
var objNewDiv = document.createElement('div');
objNewDiv.setAttribute('id', 'div_' + intTextBox);
objNewDiv.innerHTML = 'Textbox ' + intTextBox + ': <input type="text" id="tb_' +
intTextBox + '" name="tb_' + intTextBox + '"/>';
document.getElementById('content').appendChild(objNewDiv); }

/*Function to remove textbox element dynamically. Check if counter is more than zero then remove the div
element with the counter id and reduce the counter. if counter is zero then show alert as no existing textboxes are
there */
function removeElement() {
if(0 < intTextBox) {
document.getElementById('content').removeChild(document.getElementById
('div_' + intTextBox));
intTextBox--; }
else {
alert("No textbox to remove"); }
}
</script>
</head>
<body>
<p>Demo of adding and removing textboxes dynamically using simple JavaScript</p>
<p>
<a href="javascript:void(0);" onclick="addElement();">Add</a>
<a href="javascript:void(0);" onclick="removeElement();">Remove</a> </p>
<div id="content"></div>
</body>
</html>

2.1.16 Design web pages implementing event handling and input validations and dynamic
elements

Assignment

****

Web Programming Module 2 Page 15 of 15

You might also like