0% found this document useful (0 votes)
67 views32 pages

Oopp Unit 5 Notes

This document provides an introduction to CSS and JavaScript. It discusses the need for CSS and the different types of CSS style sheets including inline, internal, and external styles. It describes CSS selectors like tag selectors, ID selectors, and class selectors. The document also covers CSS rule cascading and inheritance. For JavaScript, it mentions the basic data types and variables, functions, objects, built-in objects like String and Date, the Document Object Model (DOM), event handling, and form validation.

Uploaded by

pec library
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views32 pages

Oopp Unit 5 Notes

This document provides an introduction to CSS and JavaScript. It discusses the need for CSS and the different types of CSS style sheets including inline, internal, and external styles. It describes CSS selectors like tag selectors, ID selectors, and class selectors. The document also covers CSS rule cascading and inheritance. For JavaScript, it mentions the basic data types and variables, functions, objects, built-in objects like String and Date, the Document Object Model (DOM), event handling, and form validation.

Uploaded by

pec library
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

UNIT 5

INTRODUCTION TO CSS AND CLIENT SIDE PROGRAMMING – JAVASCRIPT


CSS3 – the need for CSS, the syntax and structure of style rule, type of style sheets: Inline,
embedded and external style sheets – Types of selectors used in CSS: Tag selector, ID selector,
and class selectorCSS Rule cascading and Inheritance - JavaScript Data types and Variables -
Functions - Objects – Built-in Objects: String, Number, Boolean, Array, Date and Math -
Document Object Model – Event Handling - Controlling Windows and Documents - Form
validations.

INTRODUCTION TO CSS AND CLIENT SIDE PROGRAMMING – JAVASCRIPT


BASIC HTML SYNTAX:
<!DOCTYPE> tag:
 HTML <!DOCTYPE> tag is used to inform the browser about the
version of HTML used in the document. It is called as the document type
declaration (DTD).
 <!DOCTYPE> is not a tag/element, it just an instruction to the browser
about the document type.
 It is a null element which does not contain the closing tag, and
must not include any content within it.

SYNTAX
<!DOCTYPE html>
An example of HTML document with doctype declaration.
<!DOCTYPE html>
<html>
<head>
<title>This is the title</title>
</head>
<body>
This is the content of the document.
</body>
</html>
CSS3 – the need for CSS
 Cascading Style Sheets (CSS) is a style sheet language used for describing
the look and formatting of a document written in a markuplanguage.
 CSS describes how HTML elements are to be displayed on screen.
 CSS is a formatting language used to provide more customized web pages
and make it easier to make multiple pages use the same style.
 CSS is a web development technology that stands behind the lookand-feel
of every web page.
There are three primary way to use style sheets
 Inline style sheets
 Embedded style sheets
 Linked style sheets

NEED FOR CSS:


 CSS saves time: You can write CSS once and reuse the same sheet in
multiple HTML pages.
 Easy Maintenance: To make a global change simply change the style,
and all elements in all the webpages will be updated automatically.
 Search Engines: CSS is considered a clean coding technique, which
means search engines won‟t have to struggle to “read” its content.
 Superior styles to HTML: CSS has a much wider array of attributes than
HTML, so you can give a far better look to your HTML page in comparison
to HTML attributes.
 Offline Browsing: CSS can store web applications locally with the help of
an offline cache. Using this we can view offline websites.
THE SYNTAX AND STRUCTURE OF STYLE RULE
 The selector points to the HTML element you want to style.
 The declaration block contains one or more declarations separated by
semicolons.
 Each declaration includes a CSS property name and a value, separated by
a colon.
 Multiple CSS declarations are separated with semicolons, and declaration
blocks are surrounded by curly braces.

SYNTAX:
EXAMPLE:
p{
color: red;
text-align: center;
font-size:12px;
}

TYPE OF STYLE SHEETS:

INLINE STYLESHEET:
Inline CSS contains the CSS property in the body section attached to the
element is known as inline CSS. This kind of style is specified within an HTML
tag using the style attribute.
Syntax:
<!DOCTYPE html>
<html>
<head>
<title>Inline CSS</title>
</head>
<body>
<p style="color:green; font-size:50px;
font-style:italic; text-align:center;">
I AM A STUDENT
</p>
</body>
</html>

Output:
INTERNAL STYLESHEET:
This can be used when a single HTML document must be styled uniquely.
The CSS rule set should be within the HTML file in the head section i.e. the CSS
is embedded within the <style> tag inside the head section of the HTML file.
EXAMPLE PROGRAM:
<!DOCTYPE html>
<html>
<head>
<title>Internal CSS</title>
<style>
.main {
text-align: center;
}
.test {
color: #009900;
font-size: 50px;
font-weight: bold;
}
.testa {
font-style: bold;
font-size: 20px;
}
</style>
</head>
<body>
<div class="main">
<div class="test">HACKEREARTH</div>
<div class="testa">
A computer science portal for students
</div>
</div>
</body>
</html>
Output:
EXTERNAL CSS:
External CSS contains separate CSS files that contain only style
properties with the help of tag attributes (For example class, id, heading, … etc).
CSS property is written in a separate file with a .css extension and should be
linked to the HTML document using a link tag. It means that, for each element,
style can be set only once and will be applied across web pages.
Program:
Example:
The file given below contains CSS property. This file saves with .css extension.
For Ex: ext.css
<style>
.main {
text-align: center;
}
.test {
color: green;
font-size: 50px;
font-weight: bold;
}
.testa {
font-style: bold;
font-size: 20px;
}
</style>
Another file has to be created with link given to ext.html file.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="ext.css" />
</head>
<body>
<div class="main">
<div class="test">HACKEREARTH</div>
<div id="testa">
A CODING WEBSITE FOR STUDENTS
</div>
</div>
</body>
</html>
TYPES OF SELECTORS IN CSS:
CSS Selector
CSS selectors are used to select the content you want to style. Selectors are the
part of CSS rule set. CSS selectors select HTML elements according to its id,
class, type, attribute etc.
There are several different types of selectors in CSS.
 CSS Element Selector
 CSS Id Selector
 CSS Class Selector
 CSS Universal Selector
 CSS Group Selector
CSS Element Selector (Tag Selector)
The element selector selects the HTML element by name.
EXAMPLE:
<!DOCTYPE html>
<html>
<head>
<style>
p{
text-align: center;
color: blue;
}
</style>
</head>
<body>
<p>This style will be applied on every paragraph.</p>
<p id="para1">Me too!</p>
<p>And me!</p>
</body>
</html>
OUTPUT:

CSS ID SELECTOR
The id selector selects the id attribute of an HTML element to select a
specific element. An id is always unique within the page so it is chosen to select
a single, unique element.
It is written with the hash character (#), followed by the id of the element.
EXAMPLE:
<!DOCTYPE html>
<html>
<head>
<style>
#para1 {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<p id="para1">HELLOWORLD</p>
<p>This paragraph will not be affected.</p>
</body>
</html>
OUTPUT:
CSS CLASS SELECTOR
The class selector selects HTML elements with a specific class attribute. It is
used with a period character. (full stop symbol) followed by the class name.
EXAMPLE:
<!DOCTYPE html>
<html>
<head>
<style>
.center {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<h1 class="center">This heading is blue and center-aligned.</h1>
<p class="center">This paragraph is blue and center-aligned.</p>
</body>
</html>
OUTPUT:

CSS Class Selector for specific element


If you want to specify that only one specific HTML element should be affected,
then you should use the element name with class selector.
EXAMPLE
<!DOCTYPE html>
<html>
<head>
<style>
p.center {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<h1 class="center">This heading is not affected</h1>
<p class="center">This paragraph is blue and center-aligned.</p>
</body>
</html>
OUTPUT:

CSS Universal Selector


The universal selector is used as a wildcard character. It selects all the elements
on the pages.
EXAMPLE:
<!DOCTYPE html>
<html>
<head>
<style>
*{
color: green;
font-size: 20px;
}
</style>
</head>
<body>
<h2>This is heading</h2>
<p>This style will be applied on every paragraph.</p>
<p id="para1">Me too!</p>
<p>And me!</p>
</body>
</html>

OUTPUT:

CSS Group Selector


The grouping selector is used to select all the elements with the same style
definitions.
Grouping selector is used to minimize the code. Commas are used to separate
each selector in grouping.
EXAMPLE
<!DOCTYPE html>
<html>
<head>
<style>
h1, h2, p {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<h1>HELLOWORLD</h1>
<h2>Helloworld(In smaller font)</h2>
<p>This is a paragraph.</p>
</body>
</html>
OUTPUT:

CSS RULE CASCADING AND INHERITANCE


CSS inheritance refers to the relationship between HTML tags (think
parent and children tags) and how certain CSS styles can apply to a tag even
though there aren't any CSS rules directly applied to it. Cascading refers to the
fact that cumulative styles across multiple CSS rules are applied to each and
every HTML tag.
CASCADING RULES:
Cascade and Inheritance are two different but related concepts:
Cascade is how conflicting CSS rules are resolved.
Inheritance is how children elements inherit properties from their parent
elements.
RULES
 The highest weighted attribute that the cascade checks is the ORIGIN and
IMPORTANT of a given rule.
 The origin of a declaration is based on WHERE it comes from and
importance is whether or not it is declared important with the !important
annotation.
 The important keyword is used to override order, specificity, and inline
rules.
1.ORIGIN OF STYLESHEET:
CSS declarations come from different origin types: User-agent stylesheets,
Author stylesheets, and User stylesheets.
User-agent, or browsers, have basic style sheets that give default styles to any
document. These style sheets are named user-agent stylesheets.
Author stylesheets are the most common type of style sheet; these are the
styles written by web developers. These styles can reset user-agent styles, and
define the styles for the design of a given web page or application.
User stylesheet:
In most browsers, the user (or reader) of the website can choose to override
styles using a custom user stylesheet designed to tailor the experience to the
user's wishes. Depending on the user agent, user styles can be configured
directly or added via browser extensions.
CASCADING ORDER
Relevance: It first filters all the rules from the different sources to keep only the
rules that apply to a given element.
Origin and importance: Then it sorts these rules according to their importance,
that is, whether or not they are followed by !important, and by their origin.
Ignoring layers for the moment, the cascade order is as follows:
Sort declarations according to their importance (normal or important) and origin
(author, user, or user agent). From highest to lowest precedence:
user !important declarations
author !important declarations
author normal declarations
user normal declarations
user agent declarations
Specificity: In case of equality with an origin, the specificity of a rule is
considered to choose one value or another. The specificity of the selectors are
compared, and the declaration with the highest specificity wins.
The higher the specificity, the higher the priority of the style. For example, an ID
selector (#id) has a higher specificity than a class selector (.class) or an element
selector (element).
Order of appearance: In the origin with precedence, if there are competing
values for a property that are in style block matching selectors of equal
specificity, the last declaration in the style order is applied.
EXAMPLE INHERITANCE:
CSS Inheritance: In CSS inheritance, the child element will naturally inherit
properties from its parent element.
Syntax:
<style>
#parentclass {
color: red;
}
</style>
<div id="parentclass">
Parent Div
<div id="div1Child">Child Div 1</div>
<div id="div2Child">Child Div 2</div>
</div>
Here parentclass passes a CSS styling done as color to be red. Whereas the
child classes div1Child and div2Child have no ruleset of color: red set to them
but they got displayed in red.
It is because the child div‟s 1 and 2 inherited the properties from the parent i.e.
parentclass
EXAMPLE PROGRAM:
<!DOCTYPE html>
<html>
<head>
<style>
#parentclass {
color: black;
}
#child1 {
color: green;
}

#childchild1 {
color: red;
}
</style>
</head>

<body>
<div id="div1">
Parent
<div id="child1">
Child 1
<div id="childchild1">
Child Child 1
<div id="childchildchild1">
Child Child Child
</div>
</div>
<div id="childchild2">
Child Child 2
</div>
</div>
<div id="child2">
Child 2
</div>
</div>
</body>
</html>
OUTPUT:

Here #parentclass has color:black, #child1 has color:green and #childchild1 has
color:red. In the above code #child1 and #child2 are in #parentclass so both
should get the color black inherited but only child 2 gets the color because we
gave #child1 to color: green this is known as specificity.

CSS properties that can be inherited.


We cannot inherit all the properties/rules of CSS. All font-* properties are
naturally inherited like
• font-size
• font-family
• font-weight
• font-style, etc.
The color property is also inherited.
CSS properties such as height, border, padding, margin, width, etc. are
not inherited naturally. We can do inheritance on non-inheritable CSS
properties. We use inherit for doing so.

<!DOCTYPE html>
<html>
<head>
<style>
#parentclass {
padding: 30px;
color: red;
}
#Child {
padding: inherit;
}
</style>
</head>
<body>
<div id="parentclass">
Parent
<div id="Child">Child</div>
</div>
</body>
</html>
OUTPUT:

JAVASCRIPT DATA TYPES


JavaScript has 8 Datatypes
1. String
2. Number
3. Bigint
4. Boolean
5. Undefined
6. Null
7. Symbol
8. Object
Number: JavaScript numbers are always stored in double-precision 64-bit
binary format IEEE 754. Unlike other programming languages, you don‟t need
int, float, etc to declare different numeric values.
String: JavaScript Strings are similar to sentences. They are made up of a list of
characters, which is essentially just an “array of characters, like “Hello I AM A
STUDENT” etc.
Boolean: Represent a logical entity and can have two values: true or false.
Null: This type has only one value that is null.
Undefined: A variable that has not been assigned a value is undefined.
Symbol: Symbols return unique identifiers that can be used to add unique
property keys to an object that won‟t collide with keys of any other code that
might add to the object.
BigInt: BigInt is a built-in object in JavaScript that provides a way to represent
whole numbers larger.

JAVASCRIPT VARIABLES:
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).
RULES:
Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ )
sign.
After first letter we can use digits (0 to 9), for example value1.
JavaScript variables are case sensitive, for example x and X are different
variables.
Correct JavaScript variables
var x = 10;
var _value="sonoo";
Incorrect JavaScript variables
var 123=30;
var *aa=320;

EXAMPLE:
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
OUTPUT: 30
JAVASCRIPT FUNCTIONS:
 A JavaScript function is a block of code designed to perform a particular
task.
 A JavaScript function is executed when "something" invokes it (calls it).
 A JavaScript function is defined with the function keyword, followed by a
name, followed by parentheses ().
 Function names can contain letters, digits, underscores, and dollar signs
(same rules as variables).
 The parentheses may include parameter names separated by commas:
 (parameter1, parameter2, ...)
 The code to be executed, by the function, is placed inside curly brackets: {}

SYNTAX:
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
EXAMPLE:
function myFunction(p1, p2) {
return p1 * p2;
}

Function Invocation
 The code inside the function will execute when "something" invokes (calls)
the function:
 When an event occurs (when a user clicks a button)
 When it is invoked (called) from JavaScript code
 Automatically (self invoked)

Function Return
When JavaScript reaches a return statement, the function will stop
executing.
EXAMPLE:
// Function is called, the return value will end up in x
let x = myFunction(4, 3);
function myFunction(a, b) {
// Function returns the product of a and b
return a * b; }

JAVASCRIPT OBJECTS:
BUILT-IN OBJECTS:
In JavaScript, almost "everything" is 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)
 Date are always objects
 Math are always objects
 Regular expressions are always objects
 Arrays are always objects
 Functions are always objects
 Objects are always objects

Array Object
 Multiple values are stored in a single variable using the Array object.
 In JavaScript, an array can hold different types of data types in a single
slot, which implies that an array can have a string, a number or an object
in a single slot.
 An Array object can be created by using following ways:
Using the Array Constructor:
To create empty array when don‟t know the exact number of elements to be
inserted in an array
var arrayname = new Array();
To create an array of given size
var arrayname = new Array(size);
To create an array with given elements
var arrayname = new Array(“element 1”,”element 2”,……..,”element n”);
Using the Array Literal Notation:
To create empty array
var arrayname =[ ];
To create an array when elements are given
var arrayname =[“element 1”,”element 2”,……..,”element n”];
 Properties of the Array object
o Length - Returns the number of elements in the array.
o Constructor - Returns the function that created the Array object.
o Prototype - Add properties and methods to an object.
 Methods of the Array object
o reverse() - Reverses the array elements
o concat() - Joins two or more arrays
o sort() - Sort the elements of an array
o push() - Appends one or more elements at the end of an array
o pop() - Removes and returns the last element
o shift() - Removes and returns the first element
 unshift(), join(), indexOf(), lastIndexOf(), slice(startindex, endindex) are
some of the methods used in Array object.
Boolean Object
 The Boolean object is wrapper class and member of global objects.
 It is used to convert a non-Boolean value to a Boolean value (true or
false).
 If the Boolean object has no initial value or if it is 0, -0, null, "", false,
undefined, or NaN, the object is set to false. Otherwise it is true (even with
the string "false")!
 Boolean object can be created by using following ways:
Using Boolean Literal Notation: var bool = true;
Using Boolean Object as Function: var bool = Boolean(true);
Using Testable Expressions: if(true) {………….}
 Properties of the Boolean object
o Constructor - Returns the function that created the Boolean object.
o Prototype - Add properties and methods to an object.
 Methods of the Boolean object
o toSource() - Returns a string containing the source of the Boolean
object; you can use this string to create an equivalent object.
o toString() - Returns a string of either "true" or "false" depending
upon the value of the object.
o valueOf() - Returns the primitive value of the Boolean object
Date Object
 At times when user need to access the current date and time and also
past and future date and times. JavaScript provides support for working
with dates and time through the Date object.
 The Date object provides a system-independent abstraction of dates and
times.
 Date object can be created as : var today = new Date( );
 Dates may be constructed from a year, month, day of the month, hour,
minute, and second, and those six components, as well as the day of the
week, may be extracted from a date.
 Dates may also be compared and converted to a readable string form. A
Date is represented to a precision of one millisecond.
 Properties of Date object
o Constructor - Returns the function that created the Date object.
o Prototype - Add properties and methods to an object.
 Methods of Date object
o Date() - Returns today's date and time
o getDate() - Returns the day of the month for the specified date
o getDay() - Returns the day of the week for the specified date
o getFullYear() - Returns the year of the specified date
o getHours() - Returns the hour in the specified date according to
local time.
o getMilliseconds() - Returns the milliseconds in the specified date
according to local time.
 getMinute(), getMonth(), getTime(), getTimezoneOffset(), setDate(),
setFullYear(), setHours(), setMilliseconds(), setMinutes(), setMonth(),
setSeconds(), setTime() are some of the methods used in Date object.
Math Object
 The Math object is used to perform simple and complex arithmetic
operations.
 The Math object provides a number of properties and methods to work
with Number values
 The Math object does not have any constructors. All of its methods and
properties are static; that is, they are member functions of the Math
object itself. There is no way to create an instance of the Math object.
 Properties of Math object
o PI - The value of Pi
o E - The base of natural logarithm e
o LN2 - Natural logarithm of 2
o LN10 - Natural logarithm of 10
o LOG2E - Base 2 logarithm of e
o LOG10E - Base 10 logarithm of e
o SQRT2 - Square root of 2
o SQRT1_2 - Square root of ½
 Methods of Math object
o max(a,b) - Returns largest of a and b
o min(a,b) - Returns least of a and b
o round(a) - Returns nearest integer
o ceil(a) - Rounds up. Returns the smallest integer greater than or
equal to a
o floor(a) - Rounds down. Returns the largest integer smaller than or
equal to a
o exp(a) - Returns ea
o pow(a,b) - Returns ab
o abs(a) - Returns absolute value of a
o random() - Returns a pseudo random number between 0 and 1
o sqrt(a) - Returns square root of a
o sin(a) - Returns sin of a (a is in radians)
o cos(a) - Returns cos of a (a is in radians)
Number Object
 The Number objects represents numerical date, either integers or floating-
point numbers.
 A Number objects are created using the Number() constructor var num =
new number(value);
 Properties of Number object
o Constructor - Returns the function that created the Number object.
o MAX VALUE - Returns maximum numerical value possible in
JavaScript.
o MIN VALUE - Returns minimum numerical value possible in
JavaScript.
o NEGATIVE INFINITY - Represent the value of negative infinity.
o POSITIVE INFINITY - Represent the value of infinity.
o Prototype - Add properties and methods to an object.
 Methods of Number object
o toExponential() - Converts a number into exponential notation.
o toFixed() - Formats a number with a specific number of digits to
the right of the decimal.
o toLocaleString() - Returns a string value version of the current
number in a format that may vary according to a browser's locale
settings.
o toPrecision() - Defines how many total digits to display of a
number.
o toString() - Returns the string representation of the number's
value.
o valueOf() - Returns the number's value.
String Object
 in JavaScript, all strings are represented as instances of the String object.
 The String object is wrapper class and member of global objects.
 String object used to perform operations on the stored text, such as
finding the length of the string, searching for occurrence of certain
characters within string, extracting a substring etc.
 A String is created by using literals. A string literal is either enclosed
within single quotes(„ „) or double quotes(“ “) var string1= “ Ques10“ ;
 Properties of String object
o Length - Returns the length of string.
o Constructor - Returns the function that created the String object
o Prototype - Add properties and methods to an object
 Methods of String object
o charAt() - Returns the character at a specified position.
o concat() - Combines two or more strings.
o toLowerString() - Converts a string to lowercase.
o toUpperString() - Converts a string to uppercase.
o indexOf(searchtext, index) - Searches for the specified string from
the beginning of the string.
o lastIndexof(searchtext, index) - Searches for the specified string
from the end of the string

DOCUMENT OBJECT MODEL


The DOM is a W3C (World Wide Web Consortium) standard.
The DOM defines a standard for accessing documents:
"The W3C Document Object Model (DOM) is a platform and language-neutral
interface that allows programs and scripts to dynamically access and update the
content, structure, and style of a document."
The W3C DOM standard is separated into 3 different parts:
 Core DOM - standard model for all document types
 XML DOM - standard model for XML documents
 HTML DOM - standard model for HTML documents
The DOM Programming Interface

The HTML DOM can be accessed with JavaScript (and with other programming
languages).

In the DOM, all HTML elements are defined as objects.

The programming interface is the properties and methods of each object.

A property is a value that you can get or set (like changing the content of an
HTML element).

A method is an action you can do (like add or deleting an HTML element).

Example
The following example changes the content (the innerHTML) of
the <p> element with id="demo":
<html>
<body>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>

</body>
</html>
In the example above, getElementById is a method, while innerHTML is
a property.
The getElementById Method
The most common way to access an HTML element is to use the id of the
element.
In the example above the getElementById method used id="demo" to find the
element.
The innerHTML Property
The easiest way to get the content of an element is by using
the innerHTML property.
The innerHTML property is useful for getting or replacing the content of HTML
elements.
The innerHTML property can be used to get or change any HTML element,
including <html> and <body>.
The HTML DOM document object is the owner of all other objects in your web
page.
The HTML DOM Document Object
The document object represents your web page.
If you want to access any element in an HTML page, you always start with
accessing the document object.
Below are some examples of how you can use the document object to access and
manipulate HTML.
Finding HTML Elements

Changing HTML Elements

Adding and Deleting Elements

Adding Events Handlers


Changing HTML Content
The easiest way to modify the content of an HTML element is by using
the innerHTML property.
To change the content of an HTML element, use this syntax:
document.getElementById(id).innerHTML = new HTML
This example changes the content of a <p> element:
Example
<html>
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML = "New text!";
</script>
</body>
</html>
Example explained:
 The HTML document above contains a <p> element with id="p1"
 We use the HTML DOM to get the element with id="p1"
 A JavaScript changes the content (innerHTML) of that element to "New
text!"
Changing the Value of an Attribute

To change the value of an HTML attribute, use this syntax:

document.getElementById(id).attribute = new value

This example changes the value of the src attribute of an <img> element:

Example
<!DOCTYPE html>
<html>
<body>
<img id="myImage" src="smiley.gif">
<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>
</body>
</html>
Example explained:
 The HTML document above contains an <img> element with id="myImage"
 We use the HTML DOM to get the element with id="myImage"
 A JavaScript changes the src attribute of that element from "smiley.gif" to
"landscape.jpg"

JAVASCRIPT EVENT HANDLERS


When an event, consider pressing a keyboard key or clicking an element, occurs
on a DOM or an HTML element, we can call the specific functions based on
these events. This is taken care of by the event handlers. The properties of DOM
or HTML elements are called event handlers to control how an element should
respond to a given event.

Syntax:
<HTML-element Event-Type = "Action to be performed">
These are some javascript events:
JavaScript onclick events: This is a mouse event and provokes any logic
defined if the user clicks on the element it is bound to.
Example: In this example, we will display a message in the alert box when the
button is clicked
<!doctype html>
<html>
<head>
<script>
function hiThere() {
alert('Hi there!');
}
</script>
</head>

<body>
<button type="button"
onclick="hiThere()"
style="margin-left: 50%;">
Click me event
</button>
</body>
</html>

CONTROLLING WINDOWS AND DOCUMENTS –


The window object represents a window in browser. An object of window is
created automatically by the browser.
Window is the object of browser, it is not the object of javascript. The
javascript objects are string, array, date etc.
Methods of window object
The important methods of window object are as follows:

Example of alert() in javascript


It displays alert dialog box. It has message and ok button.
1. <script type="text/javascript">
2. function msg(){
3. alert("Hello Alert Box");
4. }
5. </script>
6. <input type="button" value="click" onclick="msg()"/>

Output of the above example

FORM VALIDATION IN JAVASCRIPT


 Form validation normally used to occur at the server, after the client had
entered all the necessary data and then pressed the Submit button.
 If the data entered by a client was incorrect or was simply missing, the
server would have to send all the data back to the client and request that
the form be resubmitted with correct information.
 This was really a lengthy process which used to put a lot of burden on the
server.
 JavaScript provides a way to validate form's data on the client's computer
before sending it to the web server. Form validation generally performs
two functions.
 Basic Validation − First of all, the form must be checked to make sure all
the mandatory fields are filled in. It would require just a loop through
each field in the form and check for data.
 Data Format Validation − Secondly, the data that is entered must be
checked for correct form and value. Your code must include appropriate
logic to test correctness of data.

It is important to validate the form submitted by the user because it can have
inappropriate values. So, validation is must to authenticate user.

JavaScript provides facility to validate the form on the client-side so data processing will
be faster than server-side validation. Most of the web developers prefer JavaScript form
validation.

Through JavaScript, we can validate name, password, email, date, mobile numbers and
more fields.

JavaScript Form Validation Example


In this example, we are going to validate the name and password. The name
can‟t be empty and password can‟t be less than 6 characters long.
<html>
<body>
<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;

if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action =
http://www.javatpoint.com/javascriptpages/valid.jsp
onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
</html>

OUTPUT:

You might also like