Web Interface Unit 3
Web Interface Unit 3
DHTML:
DHTML stands for Dynamic HTML. Dynamic means that the content of the web page can be
customized or changed according to user inputs i.e. a page that is interactive with the user. DHTML
included JavaScript along with HTML, CSS and DOM to make the page dynamic. HTML was used to
create a static page. It only defined the structure of the content that was displayed on the page. With
the help of CSS, we can beautify the HTML page by changing various properties like text size,
background color, etc. The HTML and CSS could manage to navigate between static pages but couldn’t
do anything else.
This combo made the web pages dynamic and eliminated the problem of creating static pages for
each user. In DOM, the document is represented as nodes and objects which are accessed by different
languages like JavaScript to manipulate the document.
Example DHTML:
<html><body>
<center><h1 id = "para1">
[Link]-BACHELOR OF SCIENCE</h1>
<input type = "Submit" onclick =
"Click()" ></center>
<script>
function Click() {
[Link]("para1").[Link]
or = "blue";
}
</script>
</body></html>
***JAVA SCRIPT:
JavaScript (JS) is the most popular lightweight, interpreted compiled programming language. It can be
used for both Client-side as well as Server-side developments. JavaScript also known as a scripting
language for web pages. JavaScript contains a standard library of objects, like Array, Date, and Math,
and a core set of language elements like operators, control structures, and statements.
JavaScript can be added to your HTML file in two ways:
Internal JavaScript
External JavaScript
Internal JavaScript: We can add JS code directly to our HTML file by writing the code inside the <script>
& </script>. The <script> tag can either be placed inside the <head> or the <body> tag according to the
requirement.
Example:
<html> <head> <title>
Basic Example to Describe JavaScript
</title> </head>
<body> <script>
[Link]("Welcome to Java Script");
</script> </body> </html>
External JavaScript: We can create the file with a .js extension and paste the JS code inside of it. After
creating the file, add this file in <script src=”file_name.js”> tag, and this <sctipt> can import inside
<head> or <body> tag of the HTML file.
Example:
<html > <head> <title> alert("Welcome to Java Script");
Basic Example to
Describe JavaScript
</title>
<script
src="[Link]"></script>
</head> <body>
</body> </html>
****APPLICATIONS OF JAVASCRIPT:
Creating Interactive Websites: JavaScript is used to make web pages dynamic and interactive.
It means using JavaScript, we can change the web page content and styles dynamically.
Building Applications: JavaScript is used to make web and mobile applications. To build web
and mobile apps, we can use the most popular JavaScript frameworks like – ReactJS, React
Native, [Link] etc.
Web Servers: We can make robust server applications using JavaScript. To be precise we use
JavaScript frameworks like [Link] and [Link] to build these servers.
Game Development: JavaSCript can be used to design Browser games. In JavaScript, lots of
game engines are available that provide frameworks for building games.
**VARIABLES IN JAVASCRIPT: Variables in JavaScript are containers that hold reusable data. It
is the basic unit of storage in a program.
----In the following code, clicking start will call a function that changes the color of the two headings
every 0.5sec. The color of the first heading is stored in a var and the second one is declared by using
let. Both of them are then accessed outside the function block. Var will work but the variable declared
using let will show an error because let is block scoped.
<HTML><BODY>
<h1 id="var" style="color:black;">COMPUTER SCIENCE</h1>
<h1 id="let" style="color:black;">COMPUTER SCIENCE</h1>
<button id="btn" onclick="colour()">Start</button>
<script type="text/javascript">
function colour() {
setInterval(function() {
if ([Link]('var').[Link] == 'black')
var col1 = 'blue';
else
col1 = 'black';
if ([Link]('let').[Link] == 'black') {
let col2 = 'red';
} else {
col2 = 'black';
}
[Link]('var').[Link] = col1;
[Link]('let').[Link] = col2;
}, 500);
}
</script></BODY></HTML>
Output:
Const is another variable type assigned to data whose value cannot and will not change throughout
the script.
// const variable
const name = 'Mukul';
name = 'Mayank'; // will give Assignment to constant variable error.
1. By string literal
2. By string object (using new keyword)
1) By string literal: The string literal is created using double quotes. The syntax of
creating string using string literal is given below:
var stringname="string value";
example of creating string literal.
<script>
var str="This is string literal";
[Link](str);
</script>
2) By string object (using new keyword):The syntax of creating string object using
new keyword is given below:
var stringname=new String("string literal");
example of creating string in JavaScript by new keyword.
<script>
var stringname=new String("hello javascript string");
[Link](stringname);
</script>
String object methods:
Methods Description
charAt() It provides the char value present at the specified index
concat() It provides a combination of two or more strings.
indexOf() It provides the position of a char value present in the given string
search() It searches a specified regular expression in a given string and returns its
position if a match occurs.
match() It searches a specified regular expression in a given string and returns that
regular 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
starting 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 well negative index.
toLowerCase() It converts the given string into lowercase letter
toUpperCase() It converts the given string into uppercase letter.
toString() It provides a string representing the particular object.
valueOf() It provides the primitive value of string object.
split() It splits a string into substring array, then returns that newly created array.
trim() It trims the white space from the left and right side of the string.
***MATHEMATICAL FUNCTIONS:
The JavaScript Math is a built-in object that provides properties and methods for
mathematical constants and functions to execute mathematical operations. It is not a
function object, not a constructor. You can call the Math as an object without creating it
because the properties and methods of Math are static.
•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
ceil(a) - Rounds up. Returns the smallest integer greater than or equal to a
floor(a) - Rounds down. Returns the largest integer smaller than or equal toa
[Link](4.9); // returns 4
[Link](64); // returns 8
break and continue: break keyword is used to terminate a loop and continue is
used to skip a particular iteration in a loop and move to the next iteration.
var i; var i;
for (i = 1; i < 5; i++) { for (i = 1; i < 5; i++) {
if (i ==3) { if (i ==3) {
break; continue;
} }
[Link](i); [Link](i);
} }
Output: 1 2 Output: 1 2 4
while: A While Loop in Javascript is a control flow statement that allows the code
to be executed repeatedly based on the given boolean condition.
There are mainly two types of loops:
i)Entry Controlled loops: In this type ii)Exit Controlled Loops: In this
of loop, the test condition is tested type of loop the test condition is
before entering the loop tested or evaluated at the end of the
body. ForLoop and While Loops are loop body. Therefore, the loop body
entry-controlled loops. will execute at least once, irrespective
of whether the test condition is true
Syntax: or false. the do-while loop is exit
while (condition) { controlled loop.
// Statements
} Syntax:
do {
// Statements
}
while (condition);
Syntax:
for (statement 1 ; statement 2 ; statement 3){
code here...
}
Statement 1: It is the initialization of the counter. It is executed once before the
execution of the code block.
Statement 2: It is the testing statement that defines the condition for executing the
code block It must return a boolean value. It is also an entry-controlled loop as the
condition is checked before the execution of the loop statements.
Statement 3: It is the increment or decrement of the counter & executed (every
time) after the code block has been executed.
for/in loop: There is another advanced loop called for/in loop which runs through all
the properties of an object.
Syntax :
for (var in object) { statements to be executed };
Ex:
var numbers = [45, 4, 9, 16, 25];
for (let x in numbers) {
[Link](x+”\n”);
}
For of:The JavaScript for of statement loops through the values of an iterable object.
It lets you loop over iterable data structures such as Arrays, Strings
Syntax
for (variable of iterable) {
// code block to be executed
}
variable - For every iteration the value of the next property is assigned to the
variable. Variable can be declared with const, let, or var.
iterable - An object that has iterable properties.
const cars = ["BMW", "Volvo", "Mini"];
for (let x of cars) {
[Link](x+”\n”);
}
function: This keyword is used to declare a function.
var, let, and const: These keywords are used to declare a variable in js.
**OPERATORS:
JavaScript operators operate the operands, these are symbols that are used to
manipulate a certain value or operand. Operators are used to performing specific
mathematical and logical computations on operands.
•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.
(i) 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();
***FUNCTIONS IN JAVASCRIPT
A function is a set of statements that take inputs, do some specific computation, and
produce output.
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: {}
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.
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.
If the function was invoked from a statement, JavaScript will "return" to execute the code
after the invoking statement.
Functions often compute a return value. The return value is "returned" back to the
"caller":
Example
Calculate the product of two numbers, and return the result:
let x = myFunction(4, 3); // Function is called, return value will end up in x
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
Why Functions?
You can reuse code: Define the code once, and use it many times. You can use the same
code many times with different arguments, to produce different results.
***JavaScript Objects:
A JavaScript object is an entity having state and behaviour (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.
1. By object literal
Syntax:
Example:
emp={id:102,name:"Shyam Kumar",salary:40000};
Output:
Example:
Here, you need to create function with arguments. Each argument value can be assigned
in the current object by using this keyword. The this keyword refers to the current object.
Example:
<html><body><script>
function emp(id,name,salary){
[Link]=id;
[Link]=name;
[Link]=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
[Link]([Link]+" "+[Link]+" "+[Link]);
</script></body></html>
Output of the above example
103 Vimal Jaiswal 30000
***Regular Expressions:
The term Regex stands for Regular expression. The regex or regexp or regular
expression is a sequence of different characters which describe the particular search
pattern. It is also referred/called as a Rational expression. It is mainly used for searching
and manipulating text strings. In simple words, you can easily search the pattern and
replace them with the matching pattern with the help of regular expression.
This concept or tool is used in almost all the programming or scripting languages such
as PHP, C, C++, Java, Perl, JavaScript, Python, Ruby, and many others. It is also used
in word processors such as word which helps users for searching the text in a document,
and also used in various IDEs. The pattern defined by the regular expression is applied
to the given string or a text from left to right.
Regular Expression Characters
1. Metacharacters
2. Quantifier
3. Groups and Ranges
4. Escape Characters or character classes
^ This character is used to match an ^a is an expression match to the string
expression to its right at the start of which starts with 'a' such as "aab",
a string. "a9c", "apr", "aaaaab", etc.
$ The $sign is used to match an r$ is an expression match to a string
expression to its left at the end of a which ends with r such as "aaabr", "ar",
string. "r", "aannn9r", etc.,
. This character is used to match any b.x is an expression that match strings
single character in a string except the such as "bax", "b9x", "bar".
line terminator, i.e. /n
| It is used to match a particular a|b is an expression which gives
character or a group of characters on various strings, but each string
either side. If the character on the left contains either a or b.
side is matched, then the right side's
character is ignored.
\ It is used to escape a special
character after this sign in a string.
A It is used to match the character 'A' This expression matches those strings
in the string. in which at least one- time A is
present. Such strings are "Amcx",
"mnAr", "mnopAx4".
1. Metacharacters
Characters Description Example
[a-z] It matches letters of a small case from a to This expression matches the strings such
z. as:
[A-Z] It matches letters of an upper case from A This expression matches the strings such
to Z. as:
"EXCELLENT", "NATURE".
[0-9] It matches a digit from 0 to 9. This expression matches the strings such
as:
"9845", "54455"
ab[^4-9] It matches those digits or characters which This expression matches those strings
are not defined in the square bracket. which do not contain 5, 6, 7, and 8.
Quantifiers
Description Example
+ This character specifies an expression s+ is an expression which gives
to its left for one or more times. "s", "ss", "sss", and so on.
? This character specifies an expression aS0? is an expression which gives
to its left for 0 (Zero) or 1 (one)times either "a" or "as", but not "ass".
* This character specifies an expression Br* is an expression which gives "B",
to its left for 0 or more times "Br", "Brr", "Brrr", and so on…
{x} It specifies an expression to its left for Mab{5} is an expression which gives
only x times. the following string which contains 5
b's: "Mabbbbb"
{x,y} It specifies an expression to its left, at Pr{3,6}a is an expression which
least x times but less than y times. provides twostrings. Bothstrings are
as follows: "Prrrr" and "Prrrrr"
The quantifiers are used in the regular expression for specifying the number of
occurrences of a character.
Groups and Ranges
The groups and ranges in the regular expression define the collection of characters
enclosed in the brackets.
Escape Characters or Character Classes
Characters Description
\s It is used to match a one white space character
\S It is used to match one non-white space character.
\0 It is used to match a NULL character.
\a It is used to match a bell or alarm.
\d It is used to match one decimal digit, which means from 0 to 9
\D It is used to match any non-decimal digit.
\n It helps a user to match a new line.
\w It is used to match the alphanumeric [0-9a-zA-Z]
characters.
\W It is used to match one non-word character
\b It is used to match a word boundary.
For example:a regular expression that matches any string that begins with "Mr.".
// Literal syntax var regex = /^Mr\./;
// Constructor syntax var regex = new RegExp("^Mr\\.");
Note: When using the constructor syntax, you've to double-escape special characters,
which means to match "." you need to write "\\." instead of "\.". If there is only one
backslash, it would be interpreted by JavaScript's string parser as an escaping character
and removed.
Example:
var regex = /ca[kf]e/g;
var str = "He was eating cake in the cafe.";
var matches = [Link](regex);
alert([Link]); // Outputs: 2
***Exception Handling in JavaScript
An exception signifies the presence of an abnormal condition which requires special
operable techniques. In programming terms, an exception is the anomalous code that
breaks the normal flow of the code. Such exceptions require specialized programming
constructs for its execution.
What is Exception Handling
In programming, exception handling is a process or method used for handling the
abnormal statements in the code and executing them. It also enables to handle the flow
control of the code/program. For handling the code, various handlers are used that
process the exception and execute the code. For example, the Division of a non-zero
value with zero will result into infinity always, and it is an exception. Thus, with the help
of exception handling, it can be executed and handled.
A throw statement is used to raise an exception. It means when an abnormal condition
occurs, an exception is thrown using throw.
The thrown exception is handled by wrapping the code into the try…catch block. If an
error is present, the catch block will execute, else only the try block statements will get
executed.
Thus, in a programming language, there can be different types of errors which may
disturb the proper execution of the program.
Types of ErrorsWhile coding, there can be three types of errors in the code:
1. Syntax Error: When a user makes a mistake in the pre-defined syntax of a
error is known as Runtime error. The codes which create runtime errors are known as
Exceptions. Thus, exception handlers are used for handling runtime errors.
3. Logical Error: An error which occurs when there is any logical mistake in the program
that may not produce the desired output, and may terminate abnormally. Such an error
is known as Logical error.
Error Object:When a runtime error occurs, it creates and throws an Error object. Such
an object can be used as a base for the user-defined exceptions too. An error object has
two properties:
1. name: This is an object property that sets or returns an error name.
2. message: This property returns an error message in the string form.
Built-in error types :
1. EvalError: It creates an instance for the error that occurred in the eval(), which is a
global function used for evaluating the js string code.
2. InternalError: It creates an instance when the js engine throws an internal error.
3. RangeError: It creates an instance for the error that occurs when a numeric variable
reference is de-referenced.
5. SyntaxError: An instance is created for the syntax error that may occur while parsing
the eval().
6. TypeError: When a variable is not a valid type, an instance is created for such an
error.
7. URIError: An instance is created for the error that occurs when invalid parameters
Keyboard events:
Event Performed Event Handler Description
Keydown&Keyup Onkeydown When the user press and then release the key
Onkeyup
Form events:
Event Event Description
Performed Handler
Focus Onfocus When the user focuses on an element
Submit Onsubmit When the user submits the form
Blur Onblur When the focus is away from a form element
Change Onchange When the user modifies or changes the value of a form
element
Window/Document events
Event Event Handler Description
Performed
Load Onload When the browser finishes the loading of the page
Unload Onunload When the visitor leaves the current webpage, the browser
unloads it
Resize Onresize When the visitor resizes the window of the browser
Load event
<html> <head>Javascript Events</head>
<body onload="[Link]('Page successfully loaded');">
<script>[Link]("The page is loaded successfully"); </script>
</body></html>
Output:
i) Password checking:
<html><head><script>
function validateform()
{
var name=[Link];
var password=[Link];
if (name==null ||name=="") {
alert("Name can't be blank");
return false;
}
else if([Link]<6){
alert("Password must be at least 6 characters long.");
return false;
} }
</script></head><body>
<form name="myform" method="post" action="[Link]" onsubmit="return
validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register"> </form></html>
Output:
2. Email validation
We can validate the email by the help of JavaScript. There are many criteria that need
to be follow to validate the email id such as:
o email id must contain the @ and . character
o There must be at least one character before and after the @.
o There must be at least two characters after . (dot).
Let's see the simple example to validate the email field.
<html><script>
function validateemail(){
var x=[Link]; var
atposition=[Link]("@");
var dotposition=[Link](".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=[Link]){
alert("Please enter a valid email address”);
return false;
}}
</script> <body>
<form name="myform" method="post" action="[Link]" onsubmit="return
validateemail();"> Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form> </body></html>
Output:
**JavaScript Window open method
JavaScript offers in-built methods to open and close the browser window to perform
additional operations like robot window etc. These methods help to open or close the
browser window pop- ups. Following are the window methods:open()
The [Link] method is used to open a new web page into a new
window and [Link] method to close web page opened by [Link] method.
See the [Link]() method in detail:
[Link]():
It is a pre-defined window method of JavaScript used to open the new tab or window in
the browser. This will depend on your browser setting or parameters passed in the
[Link]() method that either a new window or tab will open.
This method is supported by almost all popular web browsers, like Chrome, Firefox, etc.
Following is the syntax and parameters of the window open method -
Syntax:
This function accepts four parameters, but they are optional.
1. [Link](URL, name, specs, replace); Or
You can also use this function without using the window keyword as shown below:
1. open(URL, name, specs, replace)
There is no difference between both syntaxes.
Parameters List
Below is the parameters list of [Link]() method. Note that - all parameters of this
method are optional and works differently.
URL: This optional parameter of the [Link]() function contains the URL string of
a webpage, which you want to open. If you do not specify any URL in this function, it will
open a new blank window (about:blank).
name: Using this parameter, you can set the name of the window you are going to open.
Return Values
It will return a newly opened window.
Examples
Here are some examples of [Link]() function to open the browser window/tab. By
default, the specified URL opens in new tab or window. See the examples below:
1. open() with URL parameter
This is a simple example of window open method having a website URL inside it. We have
used a button. By clicking on this button, [Link]() method will call and open the
website in new browser tab.
Example: [Link]() with parameters
<html>
<body><center>
<h1>PB Siddhartha college of Arts and Science</h1>
<br><br>click here for ag & sg website<br>
<input type=button value="ag&sg"
onclick=[Link]("[Link]
</center></body></html>
output:
When you click this Open Window button, a blank window will open in a new tab.
Define the size for the new window:In this example, we will specify the height and
width for the new window. For this, we will use the third parameter (specs) in
[Link]() method and pass the height and width of the window separated by a
comma to this function. So, the window will open in the specified size.
<html><body><center>
<h1>Ag and Sg Siddhartha Degree college of Arts and Science</h1>
<br><br>click here for ag & sg website<br>
<button onclick=[Link](“[Link] ”height=100”,
”width=100”)>
ag & sg</button> </center></body></html>
Output: Execute the above code and get the output as given below. This will contain a
button to click and open the new URL on the same parent window.
When you click this button, a new window of pb Siddhartha college website will open
under the parent window of size.
**Messages and Conformations in JavaScript
Managing messages and conformations are one of the major task of Dynamic
programming. While handing event derive process also the user need to conforms some
actions and Those can be achieved using three JavaScript popup boxes.
The Alert Box:
An alert box is often used if you want to make sure information comes throw to the user.
When an alert box popup, the user will have to click “ok”.
Syntax::: alert(” some text Here”);
Example:
<html><head><script type="text/javascript">
function show_alert(){
alert(" I am an alert box !");
}</script>
</head><body><button onClick="show_alert()">show alert box</button>
</body></html>
Output: