Professional Documents
Culture Documents
What Is DHTML?
What Is DHTML?
UNIT – III
Introduction to JavaScript
What is DHTML, JavaScript, basics, variables, string manipulations, mathematical functions,
statements, operators, arrays, functions.
Objects in JavaScript: Data and objects in JavaScript, regular expressions, exception handling
………………………………………………………………………………………………………………
1. What is DHTML?
Dynamic HTML, or DHTML, is an umbrella term for a collection of technologies used together to create interactive and
animated websites by using a combination of a static markup language (such as HTML), a client-side scripting language
(such as JavaScript), a presentation definition language (such as CSS), and the Document Object Model (DOM). The
application of DHTML was introduced by Microsoft with the release of Internet Explorer 4 in 1997.
Differences between HTML and DHTML:
HTML is a mark-up language, while DHTML is a collection of technology.
DHTML creates dynamic web pages, whereas HTML creates static web pages.
DHTML allows including small animations and dynamic menus in Web pages.
DHML used events, methods, properties to insulate dynamism in HTML Pages.
DHML is basically using JavaScript and style sheets in an HTML page.
HTML sites will be slow upon client-side technologies, while DHTML sites will be fast enough upon client-side
technologies.
HTML creates a plain page without any styles and Scripts called as HTML. Whereas, DHTML creates a page with
HTML, CSS, DOM and Scripts called as DHTML.
HTML cannot have any server side code but DHTML may contain server side code.
In HTML, there is no need for database connectivity, but DHTML may require connecting to a database as it
interacts with user.
HTML files are stored with .htm or .html extension, while DHTML files are stored with .dhtm extension.
HTML does not require any processing from browser, while DHTML requires processing from browser
which changes its look and feel.
2. JavaScript
A JavaScript is a scripting language used at the client side design along with HTML,CSS, and XML. The main use of
JavaScript is to validate the data present in a web application. One can also control the web application using JavaScript.
Example: For example, when your login into a Facebook page account you need to provide correct user name and password.
If anything went wrong it display an error message. That means someone at the background validating the username and
password. This type of validation can be done using JavaScript.
Benefits / Advantages of JavaScript:
• JavaScript has a number of big benefits to anyone who wants to make their website dynamic.
• It is widely supported in web browsers
• It gives easy access to the document object and can manipulate most of them.
• JavaScript can give interesting animations without the long download times associated with many multimedia data
types.
• Web servers don’t need a special plugin to your scripts.
• Java script is relatively easy.
Page 1
III BSC VI SEM Web Technologies
• Because of the problem of broken scripts many web pages suffers disable JavaScript support in their browsers.
• Scripts can run slowly and complex scripts can take a long time to startup.
3. JavaScript Basic
Q. Including JavaScript in your HTML Page.
We can include JavaScript in two areas of a HTML document. The script is included in the webpage and run by the
browser usually as soon as the page loaded. The browser is able to debug the script and can display errors.
In HTML, JavaScript code must be inserted between <script> and </script> tags.
i) Including JavaScript in Header section.
The JavaScript which is included in the header section of the webpage will be run as soon as the web browser is loaded and it
is sometimes useful to execute a function that result when the browser is loaded.
Example:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h2>JavaScript in Head</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
ii) Including JavaScript in body section.
One can include the JavaScript in the body section when they want to execute some of the functions like validating the text,
event handling etc. The code inside the body react depending upon the conditions or code present in the HTML document.
Example:
<html>
<body>
<h2>JavaScript in Body</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
iii) Using external JavaScript file.
If we use a lot of scripts or our scripts are complex then including the code inside the webpage will make your
source file difficult to read and debug. We can put JavaScript code in a separate file and include the code in the head of the
webpage. JavaScript programs are stored in files with the .js extension.
myScript.js
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:
<script src="myScript.js"></script>
Example:
<!DOCTYPE html>
<html>
<body>
<h2>External JavaScript</h2>
<p id="demo">A Paragraph.</p>
Page 2
III BSC VI SEM Web Technologies
<button type="button" onclick="myFunction()">Try it</button>
<p>(myFunction is stored in an external file called "myScript.js")</p>
<script src="myScript.js"></script>
</body>
</html>
Q. Input and output statements in JavaScript
Input: In JavaScript the input is get by using prompt box. This function frames a window object and its general form
is
Syntax:
Window.prompt (“ “, variable name);
Example: Window.prompt (“enter your name”, name);
Output: In JavaScript t he data can be displayed on the web page by using two functions: write() and writeln(). The general
form is
4. Variables in JavaScript
Like any programming languages JavaScript has variables. These are data items that you can manipulate as program the
program runs. A variable is a named value that you use in your program.
Rules for variables
1. Variable name must starts with a letter or underscore
2. You can’t use spaces while giving variable names.
3. Names are case sensitive.
4. You can’t use reserved words as variable names. Reserved words are those words which are part of JavaScript
language which have special meaning and purpose.
Creating variables:
Page 3
III BSC VI SEM Web Technologies
The variable declaration tells what type of data we are using in your JavaScript. Like other languages JavaScript also
provides variables. When you declare a variable we can’t use its type instead JavaScript use “var” keyword to create
variables. This keyword is placed before the variable name.
Syntax: var Variable Name;
Example: var a;
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Variables</h2>
<p>In this example, x, y, and z are variables.</p>
<p id="demo"></p>
<script>
Var x=5;
Var y=6;
var z = x + y;
document.getElementById("demo").innerHTML = "The value of z is: " + z;
</script>
</body>
</html>
5. String Manipulation / String Functions / String Object
A sting is collection of characters. The sting object is used to manipulate a stored piece of text, String objects are created as,
Var t1= new String (“hello”); Or
Var t1= “hello”
JavaScript has functions which perform different operations on stings such as string comparison, searching a string in
another string, converting from one case to another one.
I. String Length: The length property returns the length of
Example: Var s1=”hello”;
S1.length;
The above example returns the length of string as 5.
Example:
<html>
<body>
<p id="a"></p>
<script>
var str="Hello World";
document.getElementById("a").innerHTML=str.length;
</script>
</body>
II. Finding a String in a String
The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string.
Example: var s1=”hello”; s1
indexOf(l); 0 1 2 3 4
h e l l o
In the above example, the indexOf() returns index position 2.
The lastIndexOf() method returns the index of the last occurrence of a specified text in a string.
Example: Var s1=”hello”;
lastIndexOf(l);
In the above example, lastIndexOf() returns index position 3.
III. Extracting String Parts
There are 3 methods for extracting a part of a string:
slice(start, end)
substring(start, end)
substr(start, length)
The slice() Method
slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: the start position, and the end position (end not included).
This example slices out a portion of a string from position 7 to position 12 (13-1):
Page 4
III BSC VI SEM Web Technologies
Example:
var str = "Apple, Banana, Kiwi";
var res = str.slice(7, 13);
The result of res will be: Banana
The substring() Method
substring() is similar to slice().
The difference is that substring() cannot accept negative indexes.
Example:
var str = "Apple, Banana, Kiwi";
var res = str.slice(7, 13);
The result of res will be: Banana
The substr() Method
substr() is similar to slice().
The difference is that the second parameter specifies the length of the extracted part.
Example:
var str = "Apple, Banana, Kiwi";
var res = str.slice(7, 6);
The result of res will be: Banana
iv. Replacing String Content
The replace() method replaces a specified value with another value in a string. Example:
str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "W3Schools");
v. Converting to Upper and Lower Case
A string is converted to upper case with toUpperCase().
Example:
var text1 = "Hello World!"; // String
var text2 = text1.toUpperCase(); // text2 is text1 converted to upper
A string is converted to lower case with toLowerCase()
Example:
var text1 = "Hello World!"; // String
var text2 = text1.toLowerCase(); // text2 is text1 converted to lower
vi. The concat() Method
concat() joins two or more strings:
Example:
var text1 = "Hello"; var text2 = "World";
var text3 = text1.concat(" ", text2);
vii. String.trim()
The trim() method removes whitespace from both sides of a string: Example:
var str = " Hello World! "; alert(str.trim());
viii. Extracting String Characters
The charAt() Method
The charAt() method returns the character at a specified index (position) in a string:
Example:
var str = "HELLO WORLD";
str.charAt(0); // returns H
Note:All string methods return a new string. They don't modify the original string.
Formally said: Strings are immutable: Strings cannot be changed, only replaced.
6. Mathematical Functions / Math Object
Mathematical functions and values are part of a built in JavaScript object called Math. All functions and attributes used in
complex mathematics must be accessed via this object.
i. Abs(value): it returns the absolute value of the number passed into it.
Ex: Abs(-20);
Output:20
Example:
<html>
<body>
Absolute Value is: <span id="p1"></span>
<script>
Page 5
III BSC VI SEM Web Technologies
document.getElementById('p1').innerHTML=Math.abs(-17);
</script>
</body>
</html>
ii. ACos, ASin, ATan: It returns the Arc Cosine, Arc Sin, Arc Tan of the values passed respectively in radians.
iii. Ceil (value):The ceil() method represents the ceiling function, which always rounds numbers up to the nearest
value.
Ex: alert(Math.ceil(25.5)); //outputs “26”
iv. Floor (value):The floor() method represents the floor function, which always rounds numbers down to the nearest
value.
Ex: alert(Math.floor(25.5)); //outputs “25”
v. Cos (value), sin (value), tan (value): It returns the Cosine, Sine, and Tangent values of the values passed
respectively.
vi. Log (value): It returns the natural logarithmic value of its argument.
vii.Max( val1, val2): It returns the biggest of the two passed values.
Var itemMax=Math.max(3,54,32,16);
alert(itemMax); //outputs “54”
viii. Min( val1, val2): It returns the smallest of the two passed values.
Ex: var itemMin = Math.min(3, 54, 32, 16);
alert(itemMin); //outputs “3”
ix. ParseInt(string[index]): It returns integer equivalent of the string passed in.
x. ParseFloat(string): It returns floating point number equivalent of the string passed in.
xi. POW(value power):The pow() method is used to raise a number to a given power, such as raising 2 to the power of
10.
Ex: variNum = Math.pow(2, 10);
xii.Random(): It returns a pseudo random number between 0 and 1.
xiii. Round(value): It returns result of rounding its argument to the nearest integer.
Ex: alert(Math.round(25.5)); //outputs “26”
xiv. Sqrt(value): It returns the square root of the value passed in.
Ex: var itemNum = Math.sqrt(4);
alert(itemNum); //outputs “2”
7. Statements in JavaScript
JavaScript supports three types of statements branching statements, looping statements, jumping statements.
i) Branching statements
The conditional branching statements help to jump
from one part of the program to another depending on
whether a particular condition is satisfied or not.
Generally they are two types of branching statements.
a. if statement:
if statement is used to select a block of statements based on certain condition become true, other wise general execution flow
continues
Syntax:
If(condition){
Block of statements
}
Next statements…
Example:
<html>
<head>
<title>IF Statments!!!</title>
<script type="text/javascript">
var age = prompt("Please enter your age");
if(age>=18)
document.write("You are an adult <br />");
Page 6
III BSC VI SEM Web Technologies
if(age<18)
document.write("You are NOT an adult <br />");
</script>
</head>
<body>
</body>
</html>
b. if-else statement:
It evaluates the content whether condition is true of false.
Syntax:
If(condition{
// do some thing
}
else
{
// do another
}
Example program:
<html>
<head>
<title>IF-ELSE Statement</title>
<script type="text/javascript">
var age = prompt("Please enter your age");
if(age>=18)
document.write("You are an adult <br />");
else
document.write("You are NOT an adult <br />");
</script>
</head>
<body>
</body>
</html>
c. if-else if statement
It evaluates the content only if expression is true from several expressions.
Syntax:
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}
Example:
<html>
<body>
<script>
var a = prompt("Please enter your a value");
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
Page 7
III BSC VI SEM Web Technologies
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
</body>
</html>
d. Switch statement
The switch statement is used to perform different actions based on different conditions. JavaScript Use the
switch statement to select one of many code blocks to be executed.
Syntax:
switch(expression) { case x:
// code block break;
case y:
// code block break;
default:
// code block
}
Example:
<html>
<body>
<h2>JavaScript switch</h2>
<p id="demo"></p>
<script>
var day;
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script>
</body>
</html>
2. Looping statements:
Loops are handy, if you want to run the same code over and over again, each time with a different value. Often this
is the case when working with arrays; Instead of assigning each value using index, we read and print values using
loops.
JavaScript supports different kinds of loops:
for - loops through a block of code a number of times
while - loops through a block of code while a specified condition is true
do-while: - also loops through a block of code while a specified condition is true
a) for loop:
The for loop has the following
syntax:
for (statement 1; statement 2; statement 3) {
Page 8
III BSC VI SEM Web Technologies
// code block to be executed
}
Example:
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
</body>
</html>
c) While statement
The while loop loops through a block of code as long as a specified condition is true.
Syntax:
while (condition) {
// code block to be executed
}
Example:
<html>
<body>
<script>
var i = 1;
while(i <= 5) {
document.write("The number is " + i);
i++;
}
</script>
</body></html>
d) do-wile statement
The do-while loop is a variant of the while loop. This loop will execute the code block once, before
checking if the condition is true, and then it will repeat the loop as long as the condition is true.
Syntax:
do {
// code block to be executed
}while (condition);
Example:
<html>
<body>
<script>
var i = 1;
do {
document.write("<p>The number is " + i + "</p>");
i++;
}
while(i <= 5);
</script>
</body>
</html>
3. Jumping statements
The break statement "jumps out" of a loop. The continue statement "jumps over" one iteration in the loop.
Example:
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
if(i==3){break;}
document.write(i + "<br/>")
}
Page 9
III BSC VI SEM Web Technologies
</script>
</body>
</html>
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next
iteration in the loop.
This example skips the value of 3:
Example:
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
if(i==3){continue;}
document.write(i + "<br/>")
}
</script>
</body>
</html>
8. Operators
JavaScript includes operators as in other languages. An operator performs some operation on single or multiple operands
(data value) and produces a result. For example 1 + 2, where + sign is an operator and 1 is left operand and 2 is right
operand. + operator adds two numeric values and produces a result which is 3 in this case.
Syntax:
<Left operand> operator <right operand>
<Left operand> operator
Arithmetic Operators:
Arithmetic operators are used to perform mathematical operations between numeric operands.
Operator Description
+ Adds two numeric operands.
- Subtract right operand from left operand
* Multiply two numeric operands.
/ Divide left operand by right operand.
% Modulus operator. Returns remainder of two operands.
++ Increment operator. Increase operand value by one.
-- Decrement operator. Decrease value by one.
Example:
<html>
<body>
<script>
var x = 10;
var y = 4;
document.write(x + y); // Prints: 14
document.write("<br>");
Comparison Operators:
JavaScript language includes operators that compare two operands and return Boolean value true or false.
Operators Description
== Compares the equality of two operands without considering type.
=== Compares equality of two operands with type.
!= Compares inequality of two operands.
> Checks whether left side value is greater than right side value. If yes then returns true otherwise
false.
< Checks whether left operand is less than right operand. If yes then returns true otherwise false.
>= Checks whether left operand is greater than or equal to right operand. If yes then returns true
otherwise false.
<= Checks whether left operand is less than or equal to right operand. If yes then returns true
otherwise false.
Example:
<html>
<body>
<script>
var x = 25;
var y = 35;
var z = "25";
document.write(x == z); // Prints: true
document.write("<br>");
Logical Operators:
Logical operators are used to combine two or more conditions. JavaScript includes following logical operators.
Operator Description
&& && is known as AND operator. It checks whether two operands are non-zero (0, false,
undefined, null or "" are considered as zero), if yes then returns 1 otherwise 0.
|| || is known as OR operator. It checks whether any one of the two operands is non-zero (0, false,
undefined, null or "" is considered as zero).
! ! is known as NOT operator. It reverses the boolean result of the operand (or condition)
Example:
<html>
<body>
<script>
Page
11
III BSC VI SEM Web Technologies
var year = 2018;
if((year % 400 == 0) || ((year % 100 != 0) && (year % 4 == 0))){
document.write(year + " is a leap year.");
} else{
document.write(year + " is not a leap year.");
}
</script>
</body>
</html>
Assignment Operators:
JavaScript includes assignment operators to assign values to variables with less key strokes.
Assignment Description
operators
= Assigns right operand value to left operand.
+= Sums up left and right operand values and assign the result to the left operand.
-= Subtract right operand value from left operand value and assign the result to the left
operand.
*= Multiply left and right operand values and assign the result to the left operand.
/= Divide left operand value by right operand value and assign the result to the left
operand.
%= Get the modulus of left operand divide by right operand and assign resulted modulus
to the left operand.
Example:
<html>
<body>
<script>
var x; // Declaring Variable
x = 10;
document.write(x + "<br>"); // Prints: 10
x = 20;
x += 30;
document.write(x + "<br>"); // Prints: 50
x = 50;
x -= 20;
document.write(x + "<br>"); // Prints: 30
x = 5;
x *= 25;
document.write(x + "<br>"); // Prints: 125
x = 50;
x /= 10;
document.write(x + "<br>"); // Prints: 5
x = 100;
x %= 15;
document.write(x); // Prints: 10
</script>
</body>
</html>
Page
12
III BSC VI SEM Web Technologies
Ternary operator starts with conditional expression followed by ? operator. Second part ( after ? and before :
operator) will be executed if condition turns out to be true. If condition becomes false then third part (after :)
will be executed.
Example:
<html>
<body>
<h2>JavaScript Comparison</h2>
<p>Input your age and click the button:</p>
<input id="age" value="" />
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
let age = document.getElementById("age").value;
let voteable = (age < 18) ? "Too young":"Old enough";
document.getElementById("demo").innerHTML = voteable + " to vote.";
}
</script>
</body>
</html>
9. Arrays in JavaScript
An array is an ordered set of data elements which can be accessed through a single name. Like other languages arrays in
JavaScript store group of elements but of different types. In JavaScript an array is an object and you have different methods
for performing different operations.
There is no relationship in between the elements which are stored in JavaScript arrays. Then we can define an array in
JavaScript is a collection of non-homogenous elements under a single name. The index value or the subscript value is used to
perform any operations on an array. The for loop is most frequently used loop along with arrays.
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
function myFunction() {
Page
13
III BSC VI SEM Web Technologies
fruits.push("Kiwi");
document.getElementById("demo").innerHTML = fruits;
}
</script>
</body>
</html>
// Calling function
sayHello(); // Prints: Hello, welcome to this website!
</script>
</body>
</html>
b) Passing Parameters
You can specify parameters when you define your function to accept input values at run time. The parameters work like
placeholder variables within a function; they're replaced at run time by the values (known as argument) provided to the
function at the time of invocation.
Example:
<html>
<body>
<script>
// Defining function
function displaySum(num1, num2) {
var total = num1 + num2;
document.write(total);
}
// Calling function
displaySum(6, 20); // Prints: 26
document.write("<br>");
displaySum(-5, 17); // Prints: 12
</script>
</body>
</html>
c)Examining the function call
In JavaScript parameters are passed as arrays. Every function has two properties that can be used to find information about
the parameters.
function.arguments
This is the array of parameters that have been passed function.arguments.length
This is the number of parameters that have been passed into the function.
Example:
<html>
<body>
Page
15
III BSC VI SEM Web Technologies
<script>
var x = [ 'p0', 'p1', 'p2' ];
call_me(x);
function call_me(params) {
for (i=0; i<params.length; i++) {
alert(params[i])
}
}
</script>
</body>
</html>
d) Returning Values
A function can return a value back to the script that called the function as a result using the return statement. The value may
be of any type, including arrays and objects.
The return statement usually placed as the last line of the function before the closing curly bracket and ends it with a
semicolon.
Example:
<html>
<body>
<script>
// Defining function
function getSum(num1, num2) {
var total = num1 + num2;
return total;
}
// Displaying returned value
document.write(getSum(6, 20) + "<br>"); // Prints: 26
document.write(getSum(-5, 17)); // Prints: 12
</script>
</body>
</html>
e)Scoping rules
However, you can declare the variables anywhere in JavaScript. But, the location of the declaration determines the
extent of a variable's availability within the JavaScript program i.e. where the variable can be used or accessed. This
accessibility is known as variable scope.
By default, variables declared within a function have local scope that means they cannot be viewed or manipulated from
outside of that function
Example:
<html>
<body>
<script>
//var greet = "Hello World!"; global variable
// Defining function
function greetWorld() {
var greet = "Hello World!"; //local variable
document.write(greet);
}
greetWorld(); // Prints: Hello World!
document.write(greet); // Uncaught ReferenceError: greet is not defined
</script>
</body>
</html>
Objects in JavaScript
Data and objects in JavaScript, regular expressions, exception handling, built-in objects, events.
1. Data and objects in javascript.
An object is a thing. It can be anything that you like from. Some data through a set of methods to an entire system. The
reason that object orientation is such a powerful idea is that quite simply it lets software designer and developers mimic the
real world designs.
Objects are described in software and design constructs called classes. A class usually contains some data items and some
Page
16
III BSC VI SEM Web Technologies
methods. Each class provides services to other classes in the system. A single generic class can be specialized in many ways
and each of the specialized versions inherits. Some of the properties and behaves of the generic class. That means that
common parts of the program can be developed just once and easily reused.
An object is a run time instance of a class. The object has all of the behavior that was defined in the class and is able to
perform processing.
JavaScript Objects: The built in JavaScript objects such as document and window act, and are used, like standard OO object.
JavaScript diverges from traditional OO is in its treatment of user defined objects. An object is really a data structure that has
been associated with some functions.
Example:
var patt = /w3schools/i
Example:
<html>
<body>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Visit W3Schools";
var patt = /w3schools/i;
var result = str.match(patt);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
2.JavaScript Regular Expression Grammar
i) RegExp object methods
Method Descript
Compile() Changes the regular expression
Exec() Search a string for specified value.
Test() Search a string for s specified value.
ii) String Object methods that support Regular Expressions
Method Description
Search() Search a string for specified value. Returns the position of the value
Match() Search a string for a specified value. Returns an array of the found values.
Replace() Replace characters with other characters
Page
17
III BSC VI SEM Web Technologies
Split() Split a string into an array of strings
iii) RegExp modifiers / flags
Modifier Description
I Performs case sensitive matching
G Performs a global matching. Find all matches, do not stop after the first match.
M Perform multiline matching.
iv) Regular Expression Patterns
Brackets are used to find a range of characters:
Expression Description
[abc] Find any of the characters between the brackets
[0-9] Find any of the digits between the brackets
(x|y) Find any of the alternatives separated with |
// Continue execution
document.write("<p>Hello World!</p>");
</script>
</body>
</html>
Page
18
III BSC VI SEM Web Technologies
try {
if(num > 0 && num <= 10) {
alert(Math.pow(num, num)); // the base to the exponent power
} else {
throw new Error("An invalid value is entered!");
}
} catch(e) {
alert(e.message);
} finally {
// Displaying the time taken to execute the code
alert("Execution took: " + (Date.now() - start) + "ms");
}
</script>
</body>
</html>
Page
20
III BSC VI SEM Web Technologies
using JavaScript. This is done by using the write or writeln methods of the document object.
Document.write(“<h1> Hello </h1>”);
2. The form object:
Two aspects of the form can be manipulated through JavaScript. First, most commonly and probably most usefully, the
data that is entered onto your form can be checked at submission. Second you can actually build forms through
JavaScript.
Example:
<html>
<head>
<script language="javascript">
function fibbo()
{
var var1=0;
var var2=1;
var var3;
var num=prompt("Enter the value to generate fibonacci no",0);
document.write(var1+"<br/>");
document.write(var2+"<br/>");
for(var i=3;i<=num;i++)
{
var3=var1+var2;
var1=var2;
var2=var3;
document.write(var3+"<br/>");
}
}
</script>
</head>
<body>
<form name="f1">
<table border=2>
<tr>
<td>
<input type=button value="Fibonacci" onclick="fibbo()">
</td>
<td id="num">result</td>
</tr>
</table>
</form>
</body>
</html>
4. Date Object:
JavaScript provides functions to perform many different date manipulations. Some of
the functions are mentioned below.
Date( ): Construct an empty date object.
Date(year, month, day [,hour, minute, second]): Create a new Date object based upon Numerical values
for the year, month and day. Optional time values may also be supplied.
getDate( ): Return the day of the month
getDay( ): Return an integer representing the day of the week.
getFullYear( ): Return the year as a four digit number.
Page
21
III BSC VI SEM Web Technologies
getHours( ): Return the hour field of the Date object.
getMinutes( ): Return the minutes field of the Date object.
getSeconds( ): Return the second field of the Date object.
setDate(day ): Set the day value of the object. Accepts values in the range 1 to 31.
setFullYear( year [,month, day]): Set the year value of the object. Optionally also sets month and day values.
toString( ): Returns the Date as a string.
Example:
<html>
<body>
<p id="demo"></p>
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
5. String object
6. Math object
Unit-3
Important Questions
Short Questions:
1. What is JavaScript? Advantages & Disadvantages of JavaScript?
2. What are Regular Expressions in JavaScript?
3. Explain different Data types in JavaScript?
4. Explain different math functions in JavaScript?
5. Event handling in JavaScript?
Essay Questions:
1. Write about String manipulation in JavaScript?
2. Explain different built in objects in JavaScript?
3. What are Exceptions? Exception handling in JavaScript?
Page
22