Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 55

Java script

• JavaScript is a lightweight, interpreted programming language.

• Designed for creating network-centric applications.


“network-centric applications are applications that send data to the server and are interconnected by
a communications network”

• Complementary to and integrated with Java.

• Complementary to and integrated with HTML.

• Open and cross-platform


Syntax:
<script..>
javaScript code
</script>
Advantages of JavaScript:
• Less server interaction − You can validate user input before sending the page off
to the server. This saves server traffic, which means less load on your server.

• Immediate feedback to the visitors − They don't have to wait for a page reload
to see if they have forgotten to enter something.

• Increased interactivity − You can create interfaces that react when the user
hovers over them with a mouse or activates them via the keyboard.

• Richer interfaces − You can use JavaScript to include such items as drag-and-
drop components and sliders to give a Rich Interface to your site visitors.
Limitations of JavaScript:
• Client-side JavaScript does not allow the reading or writing of files. This has been
kept for security reason.

• JavaScript cannot be used for networking applications because there is no such


support available.

• JavaScript doesn't have any multi-threading or multiprocessor capabilities.


The script tag takes two important attributes −

1] Language
2] Type
<script language = "javaScript" type = "text/javaScript">
JavaScript code
</script>

<script type = "text/javaScript">


JavaScript code
</script>
The <script> Tag-
In HTML, JavaScript code is inserted between <script> and </script> tags.

JavaScript in <head> or <body>-


• You can place any number of scripts in an HTML document.
• Scripts can be placed in the <body>, or in the <head> section of an HTML page,
or in both.
Your First JavaScript Code

<html>
<body>
<script language = "javascript" type = "text/javascript">

document.write("Hello World!")
</script>
</body>
</html>
JavaScript Display Possibilities: JavaScript can "display" data in different
ways:

• Writing into an HTML element, using innerHTML.

• Writing into the HTML output using document.write().

• Writing into an alert box, using window.alert().

• Writing into the browser console, using console.log().


JS output:
<html><body>

<h1>My First Web Page</h1>


<p>My First Paragraph</p>

<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6; //To access an HTML element,
JavaScript can use the document.getElementById(id) method. The id attribute defines the HTML
element. The innerHTML property defines the HTML content
document.write(5 + 6);//For testing purposes
<button type="button" onclick="document.write(5 + 6)">Try it</button>
window.alert(5 + 6);// window is keyword ,it is optional
alert(5 + 6);//You can use an alert box to display data
console.log(5 + 6);//you can call the console.log() method in the browser to display data.
</script>

</body></html>
JavaScript Data types & Variables

• Numbers eg. 123, 120.50 etc.


• Strings of text e.g. "This text string" etc.
• Boolean e.g. true or false.

var x, y, z;       // Declare Variables


x = 5; y = 6;      // Assign Values
z = x + y;         // Compute Values

<script type = "text/javascript">


var name = “Deep";
var money;
money = 2000.50;
</script>
Operators:
<script type="text/javascript">
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
document.write("a / b = ");
document.write("a % b = ");
document.write("a + b + c = ");</script>
Conditional Statements-
i) if
ii) else
iii) else if
iv) switch

Loop-
i) for
ii) while
iii) do-while
<html>
<body>
<script type = "text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20) {
if (x == 5) {
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body> </html>
Functions in JavaScript-
function functionname (parameter1, para2…..)
{
// function body
}

Ex:
function showMessage ()
{
alert(‘hello everyone!’)
}
Local variables: A variable declared inside a function is only visible
inside that function.
<script>
function showMessage()
{
message = "Hello, I'm JavaScript!"; // local variable
alert( message );
}
showMessage(); // Hello, I'm JavaScript!
alert( message ); // <-- Error! The variable is local to the function
</script>
Global variables: Variables declared outside of any function ,such as the
outer, username in the code above are called global.
<script>
userName = 'John';
function showMessage()
{
message = 'Hello, ' + userName;
alert(message);
}
showMessage(); // Hello, John
</script>
The return Statement
If you want to return a value from a function.
return value;

Note: This statement should be the last statement in a function.


<html> <head> <script type = "text/javascript">
function concatenate(first, last)
{ var full;
full = first + last;
return full;
}
function secondFunction()
{
var result;
result = concatenate(‘Aman', 'Ali');
document.write (result );
}
</script> </head> <body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "secondFunction()" value = "Call Function">
</form>
<p>Use different parameters inside the function and then try...</p> </body></html>
The Function() Constructor

<script type = "text/javascript">


var variablename = new Function(Arg1,Arg2…, “Function body");
</script>
<html>
<head>
<script type = "text/javascript">
var func = new Function("x", "y", "return x*y;");
function secondFunction() {
var result;
result = func(10,20);
document.write ( result );
}
</script>
</head><body>
<form>
<input type = "button" onclick = "secondFunction()" value = "Call Function">
</form></body></html>
<html> <head> <script type = "text/javascript">
function hypotenuse(a, b)
{ function square(x)
{ return x*x; }
return Math.sqrt(square(a) + square(b));
}
function secondFunction() {
var result;
result = hypotenuse(1,2);
document.write ( result );}
</script> </head> <body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "secondFunction()" value = "Call Function">
</form>
</body></html>
console.log() function: used to print any kind of variables defined
before in it or to just print any message that needs to be displayed to the
user.
Syntax : console.log(a);
1] Passing a number as an argument:
<script>
var a =2;
console.log(a);
</script>
2] Passing a string as an argument:
<script>
var str =“hello there”;
console.log(str);
</script>
3] Passing a char as an argument:
<script>
var ch =‘2’;
console.log(ch);
</script>
4] Passing a message as an argument:
console.log(“Hello my dear student”);
5] Passing a function as an argument:
<script>
function func(){return(5*5);}
console.log(func());
</script>
Program to generate one-time password (OTP)

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Math</h1>
<h2>The Math.random() Method</h2>
<p>Math.random()*10 returns a random number between 0 and 10:</p>

<p id="demo"></p>
<script>
let x = Math.random() * 10;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
Generates alphanumeric OTP of lenght 6:
<script>
function generateOTP() {
var string =
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY
Z';
var OTP = ‘ ';
var len = string.length;
for (var i = 0; i < 6; i++ ) {
OTP += string[Math.floor(Math.random() * len)]; }
return OTP; }
document.write("OTP of 6 lenght: ")
document.write( generateOTP() );
</script>
Event? JavaScript's interaction with HTML is handled through events that occur when the user or the browser
manipulates a page.

• When the page loads, it is called an event.


• When the user clicks a button, that click too is an event.
onclick Event Type- This is the most frequently used event type which occurs
when a user clicks the left button of his mouse.
<html> <head> <script type = "text/javascript">
function sayHello()
{ alert("Hello World")}
</script></head> <body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>
</body></html>
onsubmit Event Type- onsubmit is an event that occurs when you try to submit a form. You can put your form validation against this event type.

validate() function returns true, the form will be submitted, otherwise it will not
submit the data.
<script type = "text/javascript">
function validation() {
all validation goes here
.........
return either true or false
} </script>
<body>
<form method = "POST" action = "t.cgi" onsubmit = "return validate()">
<input type = "submit" value = "Submit" />
</form></body></html>
onmouseover and onmouseout-
<script type = "text/javascript">
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
</script>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover = "over()" onmouseout = "out()">
<h2> This is inside the division </h2>
</div>
</body>
JavaScript - Errors & Exceptions Handling

1) Syntax Errors/parsing errors-occur at compile time


<script type = "text/javascript">
<!--
window.print(;
//-->
</script>

For example, the following line causes a syntax error because it is


missing a closing parenthesis.
2) Runtime Errors/exceptions, occur during execution (after
compilation/interpretation)
<script type = "text/javascript">
<!--
window.printme();
//-->
</script>

For example, the following line causes a runtime error because here the
syntax is correct, but at runtime, it is trying to call a method that does
not exist.
3) Logical Errors -try...catch...finally
<script type = "text/javascript">
try {
// Code to run
[break;]
}
catch ( e ) {
// Code to run if an exception occurs
[break;]
}
[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
</script>
<html> <head><script type = "text/javascript">
function myFunc() {
var a = 100;
try {
alert("Value of variable a is : " + a );}
catch ( e ) {
alert("Error: " + e.description ); }}
</script></head> <body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
<html><head> <script type = "text/javascript">
function myFunc() {
var a = 100;
try {
alert("Value of variable a is : " + a ); }
catch ( e ) {
alert("Error: " + e.description ); }
finally {
alert("Finally block will always execute!"}}
</script> </head><body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form></body></html>
Array
Declaration of an Array-basically two ways to declare an array.
1] var house = [ ];
2] var house = new Array( );
Initialization of an Array-
1] var house = [‘1BHK’, ‘2BHK’, ‘3BHK’ ];
house[0] = 1BHK;
house[1] = 2BHK;

2] var house = new Array(10,20,30) ;


JavaScript Basic Array Methods

1) Array.push() -Adding Element at the end of an Array.


var number_arr = [10,20,30,40,50];
number_arr.push(60);
2) Array.unshift() - Adding elements at the front of an Array.
Array.unshift(item1,item2…)
var number_arr=[20,30,40];
Number_arr.unshift(10,20);

3) Array.pop() : Removing elements from the end of an array.


It is used to remove array elements from the end of an array.

4) Array.shift() : Removing elements at the beginning of an array


5] Array.splice() : Insertion and Removal in between an Array.
Array.splice(start, deletecount, item1, item2)
var number arr = [20,30,40,50,60];
//splice()
//deletes 3 element starting from 1
//number array contain[20,60]
Number_arr.splice(1,3);
concat() Javascript array concat() method returns a new array comprised of
this array joined with two or more arrays.
every() Returns true if every element in this array satisfies the provided testing
function.
filter() Creates a new array with all of the elements of this array for which the
provided filtering function returns true.
forEach() Calls a function for each element in the array.
indexOf() Returns the first (least) index of an element within the array equal to the
specified value, or -1 if none is found.
Join() Joins all elements of an array into a string.
map() Creates a new array with the results of calling a provided function on
every element in this array.
lastIndexOf() Returns the last (greatest) index of an element within the array equal to
the specified value, or -1 if none is found.
Document Object Model

• The document object represents the whole html document.


• When html document is loaded in the browser, it becomes a
document object.
• It is the root element that represents the html document.
• It has properties and methods.
• By the help of document object, we can add dynamic content
to our web page.
NOTE - It is the object of window. So
window.document as same as document
Properties of document object
Methods of document object

Method Description

write("string") writes the given string on the doucment.

writes the given string on the doucment


writeln("string")
with newline character at the end.

returns the element having the given id


getElementById()
value.
returns all the elements having the given
getElementsByName()
name value.
returns all the elements having the given
getElementsByTagName()
tag name.
returns all the elements having the given
getElementsByClassName()
class name.
Accessing field value by document object

• In this example, we are going to get the value of input text by user. Here, we are
using document.form1.name.value to get the value of name field.
• Here, document is the root element that represents the html document.
• form1 is the name of the form.
• name is the attribute name of the input text.
• value is the property, that returns the value of the input text.
<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name); } </script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/> </form>
Javascript - document.getElementById() method

• The document.getElementById() method returns the element of


specified id.
<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>
document.getElementsByName() method

The document.getElementsByName() method returns all the element of specified name.


Syntax- document.getElementsByName("name")

<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">
<input type="button" onclick="totalelements()" value="Total Genders">
</form>   
document.getElementsByTagName() method

• The document.getElementsByTagName() method returns all the element of


specified tag name.
document.getElementsByTagName("name")  
<script type="text/javascript">
function countpara(){
var totalpara=document.getElementsByTagName("p");
alert("total p tags are: "+totalpara.length); }
</script>
<p>This is a pragraph</p>
<p>Here we are going to count total number of paragraphs by
getElementByTagName() method.</p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button>
Javascript - innerHTML

The innerHTML property can be used to write the dynamic html on the html document.

<html><body>
<script type="text/javascript" >
function showcommentform() {
var data="Name:<br><input type='text' name='name'><br>Comment:<br><textarea
rows='5' cols='50'></textarea><br><input type='submit' value='comment'>";
document.getElementById('mylocation').innerHTML=data; } </script>
<form name="myForm">
<input type="button" value="comment" onclick="showcommentform()">
<div id="mylocation"></div>
</form>
</body></html>
Show/Hide Comment Form Example using innerHTML

<script>
var flag=true;
function commentform(){
var cform="<form action='Comment'>Enter Name:<br><input type='text' name='name'/><br/>
Enter Email:<br><input type='email' name='email'/><br>Enter Comment:<br/>
<textarea rows='5' cols='70'></textarea><br><input type='submit' value='Post
Comment'/></form>";
if(flag){
document.getElementById("mylocation").innerHTML=cform;
flag=false;
}else{
document.getElementById("mylocation").innerHTML="";
flag=true; } }
</script> </head> <body>
<button onclick="commentform()">Comment</button>
innerText

• The innerText property can be used to write the dynamic text on the
html document. Here, text will not be interpreted as html text but a
normal text.
• It is used mostly in the web pages to generate the dynamic content
such as writing the validation message, password strength etc.
<html><body><script type="text/javascript" >
function validate() {
var msg;
if(document.myForm.userPass.value.length>5){
msg="good";
}
else{
msg="poor"; }
document.getElementById('mylocation').innerText=msg; }
</script>
<form name="myForm">
<input type="password" value="" name="userPass" onkeyup="validate()">
Strength:<span id="mylocation">no strength</span>
</form> </body></html>
<html><body><script>-VALIDATION
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.google.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>
Retype Password Validation

<html><head> <script type="text/javascript">


function matchpass(){
var firstpassword=document.f1.password.value;
var secondpassword=document.f1.password2.value;
if(firstpassword==secondpassword){
return true;}
else{
alert("password must be same!");
return false;}}
</script></head><body>
<form name="f1" action="http://www.javatpoint.com/javascriptpages/valid.jsp"
onsubmit="return matchpass()">
Password:<input type="password" name="password" /><br/>
Re-enter Password:<input type="password" name="password2"/><br/>
<input type="submit">
</form>
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:
• email id must contain the @ and . character
• There must be at least one character before and after the @.
• There must be at least two characters after . (dot).
<script>
function validateemail() {
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
} }
</script>
<body>
<form name="myform" method="post" action="http://www.google.com/javascriptpages/valid.jsp"
onsubmit="return validateemail();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register"> </form> </body>
JavaScript this keyword

The this keyword is a reference variable that refers to the current object.
<script>
var address=
{
company:"Javascript",
city:"Noida",
state:"UP",
fullAddress:function()
{
return this.company+" "+this.city+" "+this.state;
} };
var fetch=address.fullAddress();
document.writeln(fetch);
</script>
Global Context

In global context, variables are declared outside the function. Here, this
keyword refers to the window object.

<script>
var website=“yahoo";
function web()
{
document.write(this.website);
}
web();
</script>
The call() and apply() method? Do it by yourself

<script>
var emp_address = {
fullAddress: function() {
return this.company + " " + this.city+" "+this.state;
}
}
var address = {
company:"Javascript",
city:"Noida",
state:"UP", }
document.writeln(emp_address.fullAddress.call(address));
</script>

You might also like