WP Module 2 - CSS and Javascript
WP Module 2 - CSS and Javascript
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.
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 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; }
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>
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
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
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.
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>
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.
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.
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
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.
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.
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.
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 />); }
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.
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();” />
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.
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.
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; }
<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>
<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
****