Unit-3 HTML Java Script
Unit-3 HTML Java Script
JavaScript
• JavaScript (js) is a light-weight object-oriented interpreted, scripting language
which is used by several websites for scripting the webpages.
• It enables dynamic interactivity on websites when applied to an HTML document.
• JavaScript is an object-based scripting language which is lightweight and cross-
platform.
Features of JavaScript
1. All popular web browsers support JavaScript as they provide built-in execution
environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus,
it is a structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast
(depending on the operation).
4. JavaScript is an object-based scripting language that uses prototypes rather than
using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows,
macOS, etc.
8. It provides good control to the users over the web browsers.
History of JavaScript
• in May 1995, Marc Andreessen coined the first code of Javascript named
'Mocha'.
• Later, the marketing team replaced the name with 'LiveScript'.
• in December 1995, the language was finally renamed to 'JavaScript'. From
then, JavaScript came into existence.
Application of JavaScript
o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm
dialog box and prompt dialog box),
o Displaying clocks etc.
In the above example, we have displayed the dynamic content using JavaScript. Let’s see
the simple example of JavaScript that displays alert dialog box.
<html>
<body>
<script type="text/javascript">
alert("Hello Javatpoint");
</script>
</body>
</html>
Let’s see the same example of displaying alert dialog box of JavaScript that is contained
inside the head tag.
In this example, we are creating a function msg(). To create function in JavaScript, you
need to write function with function_name as given below.
To call function, you need to work on event. Here we are using onclick event to call
msg() function.
<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello Javatpoint");
</script>
</head>
<body>
<p>Welcome to Javascript</p>
<form>
</form>
</body>
</html>
We can create external JavaScript file and embed it in many html page.
It provides code re usability because single JavaScript file can be used in several html
pages.
Let's create an external JavaScript file that prints Hello Javatpoint in a alert dialog box.
message.js
function msg(){
alert("Hello Javatpoint");
}
Let's include the JavaScript file into html page. It calls the JavaScript function on button
click.
index.html
<html>
<head>
<script type="text/javascript" src="message.js"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/> </form> </body> </html>
JavaScript provides different data types to hold different types of values. There are two
types of data types in JavaScript.
JavaScript is a dynamic type language, means you don't need to specify type of the
variable because it is dynamically used by JavaScript engine. You need to use var here
to specify the data type. It can hold any type of values such as numbers, strings etc.
There are five types of primitive data types in JavaScript. They are as follows:
Data Type Description
The non-primitive data types are as follows:Hello Java Program for Beginners
Data Description
Type
JavaScript Variable
1) local variable
2) global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers).
1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.
<html>
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>
Statements in JavaScript
JavaScript supports threes types of statements.
1. branching statements
2. looping statements
3. jumping statements
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.
1. If Statement
2. If else statement
3. if else if statement
4. switch
1.If statement
Syntax: if(expression){
//content to be evaluated
}
Flowchart
Example: <html>
<body>
<script>
var a=20;
if(a>10){
}
</script> </body></html>
2.If...else Statement
It evaluates the content whether condition is true of false. The syntax of JavaScript if-
else statement is given below.
Syntax: if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
Ex: <html>
<body><script>
var a=20;
if(a%2==0){
}
else{
</script></body></html>
3.If...else if statement:
It evaluates the content only if expression is true from several expressions. The
signature of JavaScript if else if statement is given below.
Syntax: if(expression1){
Statement block1;
}
else if(expression2){
Statement block2; }
else if(expression3){
Statement block3; }
else{
Statement block4; }
Example:
<html>
<body>
<script>
var a=20;
if(a==10){
else if(a==15){
else if(a==20){
else{
</script> </body></html>
Output: a is equal to 20
4)Switch
The JavaScript switch statement is used to execute one code from multiple expressions.
It is just like else if statement that we have learned in previous page. But it is convenient
than if..else..if because it can be used with numbers, characters etc.
Syntax: switch(expression){
case value1: statement block1;
break;
case value2: statement block1;
break;
......
default:
<html>
<body>
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
document.write(result);
</script>
</body>
</html>
Output: B Grade
Looping statements:
The JavaScript loops are used to iterate the piece of code using for, while, do while or
for-in loops. It makes the code compact. It is mostly used in array.
1. for loop
2. while loop
3. do-while loop
4. for-in loop
1.For loop
The JavaScript for loop iterates the elements for the fixed number of times. It should be
used if number of iteration is known. The syntax of for loop is given below.
The JavaScript while loop iterates the elements for the infinite number of times. It
should be used if number of iteration is not known. The syntax of while loop is given
below.
3) do while loop
The JavaScript do while loop iterates the elements for the infinite number of times like
while loop. But, code is executed at least once whether condition is true or false. The
syntax of do while loop is given below.
Syntax: do{
code to be executed
}while (condition);
Example:
<!DOCTYPE html>
<html>
<body>
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script> </body></html>
Output:21
22
23
24
25
JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function
many times to reuse the code.
//code to be executed
}
JavaScript Functions can have 0 or more arguments.
Example: <html>
<body>
<script>
function msg(){
</script>
</body></html>
We can call function by passing arguments. Let’s see the example of function that has
one argument.
<html>
<body>
<script>
function getcube(number){
alert(number*number*number);
</script>
<form>
We can call function that returns a value and use it in our program. Let’s see the
example of function that returns value.
<html>
<body>
<script>
function getInfo(){
</script>
<script>
document.write(getInfo());
</script> </body></html>
JavaScript Strings
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:
Ex:
The index position of first character in a string is always starts with zero. If an element is
not present in a string, it returns -1.
Syntax: string.indexOf(ch)
2.charAt()
The JavaScript string charAt() method is used to find out a char value present at the
specified index in a string.
Syntax String.charAt(index)
3) lastIndexOf(str) Method
The JavaScript String lastIndexOf(str) method returns the last index position of the given
string.
Syntax String.lastIndexOf(ch)
4) toLowerCase()
The JavaScript String toLowerCase() method returns the given string in lowercase letters.
Syntax: string.toLowerCase()
The JavaScript String toUpperCase() method returns the given string in uppercase
letters.
Syntax: string.toUpperCase()
The JavaScript String slice(beginIndex, endIndex) method returns the parts of string
from given beginIndex to endIndex. In slice() method, beginIndex is inclusive and
endIndex is exclusive.
Syntax string.slice(start,end)
The JavaScript String trim() method removes leading and trailing whitespaces from the
string.
Syntax :string.trim();
8) split() Method:
Split method splits the given string.
Syntax: string.split();
Example: <!DOCTYPE html>
<html>
<body>
<script>
document.write(“index of a is”+str.indexOf('a'));
document.writeln(“character at 4 place”+str.charAt(4));
var s2=str.toLowerCase();
var s3=str.toUpperCase();
var s4=str.slice(2,5);
</script></body></html>
Output:: index of a is 2
character at 4 place n
last index of a 8
JavaScript Array
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
As you can see, values are contained inside [ ] and separated by , (comma).
EX: <html>
<body>
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
</script>
</body>
</html>
Sonoo
Vimal
Ratan
Example:
<html>
<body>
<script>
var i;
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
</script>
</body></html>
Output of the above example
Arun
Varun
John
Here, you need to create instance of array by passing arguments in constructor so that
we don't have to provide value explicitly.
<html>
<body>
<script>
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
</script>
</body>
</html>
Jai
Vijay
Smith
Array operations:
1. Traversing
2. Inserting element into array
3. Deleting element from array
4. Merging arrays
5. Searching
<!DOCTYPE HTML>
<html>
<body>
<script>
var arr=["C","C++",”java”,"Python",”html”];
var j=0;
for(i=0;i<arr.length;i++)
If(arr[i]==ele)
{}
else
{ temp[j]=arr[i];
j++; }
arr=temp;
</script></body></html>
Output: the elements of array C C++ java Python html
Syntax: array.concat(arr1,arr2,....,arrn)
2)pop():The JavaScript array pop() method removes the last element from the
given array and return that element. This method changes the length of the
original array.
Syntax: array.pop()
3)push()
The JavaScript array push() method adds one or more elements to the end of the given
array. This method changes the length of the original array.
Syntax: array.push(element1,element2....elementn)
4)reverse()
The JavaScript array reverse() method changes the sequence of elements of the given
array and returns the reverse sequence. In other words, the arrays last element becomes
first and the first element becomes the last. This method also made the changes in the
original array.
Syntax: array.reverse()
The JavaScript array join() method combines all the elements of an array into a string
and return a new string. We can use any type of separators to separate given array
elements.
Syntax: array.join(separator)
<!DOCTYPE html>
<html>
<body>
<script>
var arr1=["C","C++","Python"];
var arr2=["Java","JavaScript","Android"];
var result=arr1.concat(arr2);
document.writeln(result);
result.push("html");
var rev=result.reverse();
document.writeln(rev);
var result=rev.join()
document.write(result);
</script>
</body>
</html>
html,Javscript,Java,Python,C++,C
JavaScript Object:
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
Syntax: object={property1:value1,property2:value2.....propertyN:valueN}
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.
We can define method in JavaScript object. But before defining method, we need to add
property in the function with same name as method.
<html>
<body>
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
this.changeSalary=changeSalary;
function changeSalary(otherSalary){
this.salary=otherSalary;
} }
e.changeSalary(45000);
</script> </body></html>
JavaScript Math
The JavaScript math object provides several constants and methods to perform
mathematical operation. Unlike date object, it
Math Methods
1)Math.sqrt(n)
The JavaScript math.sqrt(n) method returns the square root of the given number.
The JavaScript math.pow(m,n) method returns the m to the power of n that is mn.
<html>
<body>
<script>
document.getElementById('p3').innerHTML=Math.pow(3,4);
3)Math.floor(n)
The JavaScript math.floor(n) method returns the lowest integer for the given number.
For example 3 for 3.7, 5 for 5.9 etc.
<html>
<body>
<script>
document.getElementById('p4').innerHTML=Math.floor(4.6);
</script> </body></html>
4)Math.ceil(n)
The JavaScript math.ceil(n) method returns the largest integer for the given number. For
example 4 for 3.7, 6 for 5.9 etc.
<!DOCTYPE html>
<html>
<body>
<script>
document.getElementById('p5').innerHTML=Math.ceil(4.6);
</script> </body></html>
5)Math.round(n)
The JavaScript math.round(n) method returns the rounded integer nearest for the given
number. If fractional part is equal or greater than 0.5, it goes to upper value 1 otherwise
lower value 0. For example 4 for 3.7, 3 for 3.3, 6 for 5.9 etc.
Example: <html>
<body>
<script>
document.getElementById('p6').innerHTML=Math.round(4.3);
document.getElementById('p7').innerHTML=Math.round(4.7);
</script> </body></html>
The JavaScript math.abs(n) method returns the absolute value for the given number. For
example 4 for -4, 6.6 for -6.6 etc.
<!DOCTYPE html>
<html>
<body>
<script>
document.getElementById('p8').innerHTML=Math.abs(-4);
</script></body></html>
7)Math.abs(n)
The JavaScript math.abs(n) method returns the absolute value for the given number. For
example 4 for -4, 6.6 for -6.6 etc
Example: <html>
<body>
<script>
document.getElementById('p8').innerHTML=Math.abs(-4);
</script> </body></html>
The JavaScript date object can be used to get year, month and day. You can display a
timer on the webpage by the help of JavaScript date object.
You can use different Date constructors to create date object. It provides methods to
get and set day, month, year, hour, minute and seconds.
Constructor
1. Date()
2. Date(milliseconds)
3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)\
Date Methods
1)getDate() method returns the day for the specified date on the basis of local
time.
Syntax: dateObj.getDate()
An integer value between 1 and 31 that represents the day of the specified date.
2)getDay() getDay() method returns the value of day of the week for the specified
date on the basis of local time. The value of the day starts with 0 that represents
Sunday.
Syntax dateObj.getDay()
3)getUTCFullYear()
The JavaScript date getUTCFullYear() method returns the year for the specified date on
the basis of universal time.
Syntax dateObj.getHours()
5)getMonth()
The JavaScript date getMonth() method returns the integer value that represents month
in the specified date on the basis of local time. The value returned by getMonth()
method starts with 0 that represents January.
SyntaxdateObj.getMonth()
An integer value between 0 and 11 that represents the month in the specified date.
6)getMinutes() date getMinutes() method returns the minutes in the specified date
on the basis of local time.
Syntax dateObj.getMinutes()
7)getSeconds()
The JavaScript date getSeconds() method returns the seconds in the specified date on
the basis of local time.
Syntax dateObj.getSeconds()
There are two ways to set interval in JavaScript: by setTimeout() or setInterval() method.
<html>
<body>
<script>
window.onload=function(){getTime();}
function getTime(){
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
setTimeout(function(){getTime()},1000);
//setInterval("getTime()",1000);//another way
function checkTime(i){
if (i<10){
i="0" + i;
return i;
</script>
</body>
</html>
BROWSER OBJECTS:
Document Object
1)document.getElementById()
Example:
<html><body>
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form> </body></html>
cube
2)document.getElementsByName()
syntax : document.getElementsByName("name")
Here, name is required.
Example : <html><body>
<script type="text/javascript">
function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">
Female
Total Genders
The Browser Object Model (BOM) is used to interact with the browser.
The default object of browser is window means you can call all the functions of window
by specifying window or directly. For example:
window.alert("hello javatpoint"); ``
is same as:
alert("hello javatpoint");
1)Window Object
</body></html>
confirm() :
It displays the confirm dialog box. It has message with ok and cancel buttons.
Example: <html>
<body>
<script type="text/javascript">
function msg()
{
var v= confirm("Are u sure?");
if(v==true)
{
alert("ok");
}
else{
alert("cancel");
}
}
</script>
prompt()
It displays prompt dialog box for input. It has message and textfield.
Example:
<html><body>
<script type="text/javascript">
function msg(){
var v= prompt("Who are you?");
alert("I am "+v);
}
</script>
2)History Object
The JavaScript history object represents an array of URLs visited by the user. By using
this object, you can load previous, forward or any particular page.
3)Navigator Object
The JavaScript navigator object is used for browser detection. It can be used to get
browser information such as appName, appCodeName, userAgent etc.
window.navigator
There are many properties of navigator object that returns information of the browser.
4)Screen Object
The JavaScript screen object holds information of browser screen. It can be used to
display screen width, height, colorDepth, pixelDepth etc.
There are many properties of screen object that returns information of the browser.
o throw statements
o try…catch statements
o try…catch…finally statements.
try…catch
Syntax:
try{
expression; }
catch(error){
expression; }
try…catch example:
<html>
<body>
<script>
try{
}catch(e){
</script>
</body>
</html>
RegExp Object
A regular expression is an object that describes a pattern of characters.
The JavaScript RegExp class represents regular expressions, and both String and RegExp define
methods that use regular expressions to perform powerful pattern-matching and search-and-
replace functions on text.
Syntax
A regular expression could be defined with the RegExp () constructor, as follows −
or
Modifier Description
Brackets
Brackets are used to find a range of characters:
Expression Description
Method Description
EXAMPLE 1:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript RegExp</h2>
<p id="demo"></p>
<script>
let text = "The best things in life are free";
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
JavaScript RegExp
The exec() method tests for a match in a string:
EXAMPLE 2:
<html>
<head>
</head>
<body>
</script>
</body></html>
Output
Test 1 - returned value : script
Test 2 - returned value : null