0% found this document useful (0 votes)
2 views

Java Script

JavaScript is a versatile scripting language used for adding functionality to web pages, including form validation and server communication. It consists of statements executed by the browser, with features like variables, data types, functions, and control structures such as loops and conditionals. JavaScript also allows for object-oriented programming, enabling the creation and manipulation of objects and their properties and methods.

Uploaded by

aashiyan.shaan
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java Script

JavaScript is a versatile scripting language used for adding functionality to web pages, including form validation and server communication. It consists of statements executed by the browser, with features like variables, data types, functions, and control structures such as loops and conditionals. JavaScript also allows for object-oriented programming, enabling the creation and manipulation of objects and their properties and methods.

Uploaded by

aashiyan.shaan
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 45

JavaScript

JavaScript is THE scripting language of the Web.JavaScript is used in billions of Web


pages to add functionality, validate forms, communicate with the server, and much
more.
<!DOCTYPE html>
<html>
<head>
<script>
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>
</head>
<body>
<h1>My First JavaScript</h1>
<p id="demo">This is a paragraph.</p>
<button type="button" onclick="displayDate()">Display Date</button>
</body> </html>
Output:My First JavaScript
Fri Jun 14 2013 12:28:29 GMT+0530 (India Standard Time)
JavaScript Statements
• JavaScript is a sequence of statements to be executed by the
browser.JavaScript statements are "commands" to the browser.
The purpose of the statements is to tell the browser what to do.

document.getElementById("demo").innerHTML="Hello Dolly";
This JavaScript statement tells the browser to write "Hello Dolly" inside an
HTML element with id="demo":

• Semicolon ;
Semicolon separates JavaScript statements.Normally you add a semicolon at
the end of each executable statement. Using semicolons also makes it
possible to write many statements on one line.
• JavaScript Code
JavaScript code (or just JavaScript) is a sequence of JavaScript statements.
Each statement is executed by the browser in the sequence they are
written.
<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph.</p>
<div id="myDIV">A DIV.</div>
<script>
document.getElementById("demo").innerHTML="Hello Dolly";
document.getElementById("myDIV").innerHTML="How are you?";
</script>
</body>
</htm
• Output: My Web Page
Hello Dolly
How are you?
• JavaScript Code Blocks
JavaScript statements can be grouped together in blocks.Blocks start
with a left curly bracket, and end with a right curly bracket.
The purpose of a block is to make the sequence of statements
execute together. A good example of statements grouped together
in blocks, are JavaScript functions.
• <!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<p id="myPar">I am a paragraph.</p>
<div id="myDiv">I am a div.</div>
<p>
<button type="button" onclick="myFunction()">Try it</button>
</p>
<script>
function myFunction()
{
document.getElementById("myPar").innerHTML="Hello Dolly";
document.getElementById("myDiv").innerHTML="How are you?";
}
</script>
<p>When you click on "Try it", the two elements will change.</p>
</body>
</html>

• Output :My Web Page


I am a paragraph.
I am a div.
When you click on "Try it", the two elements will change.
• JavaScript is Case Sensitive
JavaScript is case sensitive.Watch your capitalization closely when you
write JavaScript statements:
• A function getElementById is not the same as getElementbyID.
• A variable named myVariable is not the same as MyVariable.

• White Space
• JavaScript ignores extra spaces. You can add white space to your
script to make it more readable. The following lines are equivalent:
• var person="Hege";
var person = "Hege";

• Break up a Code Line


You can break up a code line within a text string with a backslash. The
example below will be displayed properly:
• document.write("Hello \
World!");
• However, you cannot break up a code line like this:
document.write \
("Hello World!");
• JavaScript Comments
JavaScript comments can be used to make the code more readable.
Comments will not be executed by JavaScript.
Comments can be added to explain the JavaScript, or to make the code
more readable.
Single line comments start with //.
The following example uses single line comments to explain the code:
// Write to a heading:
document.getElementById("myH1").innerHTML="Welcome to my
Homepage";
// Write to a paragraph:
document.getElementById("myP").innerHTML="This is my first
paragraph.";
• JavaScript Multi-Line Comments
Multi line comments start with /* and end with */.
The following example uses a multi line comment to explain the
code:
/*
The code below will write
to a heading and to a paragraph,
and will represent the start of
my homepage:
*/
document.getElementById("myH1").innerHTML="Welcome to my
Homepage";
document.getElementById("myP").innerHTML="This is my first
paragraph.";
JavaScript Variables
JavaScript variables are "containers" for storing information:
var x=5;
var y=6;
var z=x+y;
<!DOCTYPE html>
<html>
<body>
<script>
var x=5;
var y=6;
var z=x+y;

document.write(x + "<br>");
document.write(y + "<br>");
document.write(z + "<br>");
</script>

</body>
</html>
JavaScript Data Types
JavaScript variables can also hold other types of data, like text values
(person="John Doe").
In JavaScript a text like "John Doe" is called a string.
There are many types of JavaScript variables, but for now, just think
of numbers and strings.
When you assign a text value to a variable, put double or single
quotes around the value.
When you assign a numeric value to a variable, do not put quotes
around the value. If you put quotes around a numeric value, it will
be treated as text.
var pi=3.14;
var person="John Doe";
var answer='Yes I am!';
<!DOCTYPE html>
<html>
<body>
<p>Click the button to create a variable, and display the result.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var carname="Volvo";
document.getElementById("demo").innerHTML=carname;
}
</script>
</body>
</html>
One Statement, Many Variables
You can declare many variables in one statement. Just start the
statement with var and separate the variables by comma:
var lastname="Doe", age=30, job="carpenter";
Your declaration can also span multiple lines:
var lastname="Doe",
age=30,
job="carpenter";
Re-Declaring JavaScript Variables
If you re-declare a JavaScript variable, it will not lose its value:.
The value of the variable carname will still have the value "Volvo"
after the execution of the following two statements:
var carname="Volvo";
var carname;
JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using operators like = and +:
<!DOCTYPE html>
<html>
<body>

<p>Given that y=5, calculate x=y+2, and display the result.</p>


<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction()
{
var y=5;
var x=y+2;
var demoP=document.getElementById("demo")
demoP.innerHTML="x=" + x;
}
</script>

</body>
</html>
JavaScript Booleans
• Booleans can only have two values: true or false.
• var x=true;
var y=false;

JavaScript Arrays
var cars=new Array();
cars[0]="Saab";
cars[1]="Volvo";
cars[2]="BMW";
var cars=new Array("Saab","Volvo","BMW"); //condensed array
var cars=["Saab","Volvo","BMW"]; //literal array
JavaScript Objects
• An object is delimited by curly braces. Inside the braces the object's properties
are defined as name and value pairs (name : value). The properties are
separated by commas:
var person={firstname:"John", lastname:"Doe", id:5566};

• Spaces and line breaks are not important. Your declaration can span multiple
lines:
var person={
firstname : "John",
lastname : "Doe",
id : 5566
};

You can address the object properties in two ways:


name=person.lastname;
name=person["lastname"];
Undefined and Null
cars=null;
person=null;
• Properties and Methods
• Properties are values associated with objects.
• Methods are actions that objects can perform.

• Properties:
car.name=Fiat
car.model=500
car.weight=850kg
car.color=white

• Methods:
car.start()
car.drive()
car.brake()
Objects in JavaScript:
In JavaScript, objects are data (variables), with properties and methods.
var txt = "Hello";
• Properties:
txt.length=5

Methods:
txt.indexOf()
txt.replace()
txt.search()
• Creating JavaScript Objects
Almost "everything" in JavaScript is an object. Strings, Dates, Arrays, Functions.You
can also create your own objects.

person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";
Accessing Object Properties
objectName.propertyName
var message="Hello World!";
var x=message.length;

Accessing Object Methods


objectName.methodName()
var message="Hello world!";
var x=message.toUpperCase();
JavaScript Functions
A function is a block of code that will be executed when "someone" calls it:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>
Calling a Function with Arguments
When you call a function, you can pass along some values to it, these values are called
arguments or parameters. You can send as many arguments as you like, separated
by commas (,)
myFunction(argument1,argument2)

<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>

<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>
The function above will alert "Welcome Harry Potter, the Wizard" when the button is
clicked.
The function is flexible, you can call the function using different arguments, and
different welcome messages will be given:
<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>
<button onclick="myFunction('Bob','Builder')">Try it</button>
• Functions With a Return Value
Sometimes you want your function to return a value back to where the call was
made.This is possible by using the return statement.When using the return
statement, the function will stop executing, and return the specified value.
function myFunction()
{
var x=5;
return x;
}
• It is not the entire JavaScript that will stop executing, only the function.
JavaScript will continue executing code, where the function-call was made
from.The function-call will be replaced with the return value:
var myVar=myFunction();
The variable myVar holds the value 5, which is what the function "myFunction()"
returns.
You can also use the return value without storing it as a variable:
document.getElementById("demo").innerHTML=myFunction();
The innerHTML of the "demo" element will be 5, which is what the function
"myFunction()" returns.

You can make a return value based on arguments passed into the function:
<!DOCTYPE html>
<html>
<body>
<p>This example calls a function which performs a calculation, and returns the
result:</p>
<p id="demo"></p>
<script>
function myFunction(a,b)
{
return a*b;
}
document.getElementById("demo").innerHTML=myFunction(4,3);
</script>
</body>
</html>
The return statement is also used when you simply want to exit a function. The
return value is optional:
function myFunction(a,b)
{
if (a>b)
{
return;
}
x=a+b
}
The function above will exit the function if a>b, and will not calculate the sum of a
and b.
The JavaScript Switch Statement
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
JavaScript Loops
for (var i=0;i<cars.length;i++)
{
document.write(cars[i] + "<br>");
}

var i=2,len=cars.length;
for (; i<len; i++)
{
document.write(cars[i] + "<br>");
}

var i=0,len=cars.length;
for (; i<len; )
{
document.write(cars[i] + "<br>");
i++;
}
<!DOCTYPE html>
<html>
<body>
<p>Click the button to loop through the properties of an object named "person".</p>
<button onClick="myFunction()">Try it</button>
<p id="demo"></p>

<script>
function myFunction()
{
var x;
var txt="";
var person={fname:"John",lname:"Doe",age:25};

for (x in person)
{
txt=txt + person[x];
}

document.getElementById("demo").innerHTML=txt;
}
</script>
</body>
</html>
The While Loop
while (i<5)
{
x=x + "The number is " + i + "<br>";
i++;
}

The Do/While Loop


do
{
x=x + "The number is " + i + "<br>";
i++;
}
while (i<5);
<!DOCTYPE html>
<html>
<body>

<p>Click the button to loop through a block of as long as <em>i</em> is less than 5.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script>
function myFunction()
{
var x="",i=0;
do
{
x=x + "The number is " + i + "<br>";
i++;
}
while (i<5)
document.getElementById("demo").innerHTML=x;
}
</script>

</body>
</html>
The Break Statement
for (i=0;i<10;i++)
{
if (i==3)
{
break;
}
x=x + "The number is " + i + "<br>";
}

The Continue Statement


for (i=0;i<=10;i++)
{
if (i==3) continue;
x=x + "The number is " + i + "<br>";
}

JavaScript Labels
label:
statements
JavaScript Form Validation
JavaScript can be used to validate data in HTML forms before sending off the content to a
server.
• Form data that typically are checked by a JavaScript could be:
• has the user left required fields empty?
• has the user entered a valid e-mail address?
• has the user entered a valid date?
• has the user entered text in a numeric field?
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
</head>

<body>
<form name="myForm" action="demo_form.html" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>

</html>
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
</script>
</head>

<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
</body>

</html>
JavaScript HTML DOM
With the HTML DOM, JavaScript can access all the elements of an HTML document.
When a web page is loaded, the browser creates a Document Object Model of
the page.
The HTML DOM model is constructed as a tree of Objects.

Finding HTML Elements by Id


<!DOCTYPE html>
<html>
<body>

<p id="intro">Hello World!</p>


<p>This example demonstrates the <b>getElementById</b> method!</p>

<script>
x=document.getElementById("intro");
document.write("<p>The text from the intro paragraph: " + x.innerHTML + "</p>");
</script>

</body>
</html>
Finding HTML Elements by Tag Name
<!DOCTYPE html>
<html>
<body>

<p>Hello World!</p>

<div id="main">
<p>The DOM is very useful.</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method</p>
</div>

<script>
var x=document.getElementById("main");
var y=x.getElementsByTagName("p");
document.write('First paragraph inside "main" is ' + y[0].innerHTML);
</script>

</body>
</html>
Changing the HTML Output Stream
<!DOCTYPE html>
<html>
<body>
<script>
document.write(Date());
</script>
</body>
</html>

Changing HTML Content


<html>
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML="New text!";
</script>
</body>
</html>
Changing an HTML Attribute
<!DOCTYPE html>
<html>
<body>
<img id="image" src="smiley.gif" width="160" height="120">
<script>
document.getElementById("image").src="landscape.jpg";
</script>
<p>The original image was smiley.gif, but the script changed it to
landscape.jpg</p>
</body>
</html>
• Changing HTML Style
<html>
<body>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color="blue";
</script>
<p>The paragraph above was changed by a script.</p>
</body>
</html>

• <!DOCTYPE html>
<html>
<body>
<h1 id="id1">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color='red'">
Click Me!</button>
</body>
</html>
JavaScript HTML DOM Events
• Examples of HTML events:
• When a user clicks the mouse
• When a web page has loaded
• When an image has been loaded
• When the mouse moves over an element
• When an input field is changed
• When an HTML form is submitted
• When a user strokes a key

<!DOCTYPE html>
<html>
<body>
<h1 onclick="this.innerHTML='Ooops!'">Click on this text!</h1>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script>
function changetext(id)
{
id.innerHTML="Ooops!";
}
</script>
</head>
<body>

<h1 onclick="changetext(this)">Click on this text!</h1>

</body>
</html>
HTML Event Attributes
<!DOCTYPE html>
<html>
<body>

<p>Click the button to execute the <em>displayDate()</em> function.</p>

<button onclick="displayDate()">Try it</button>

<script>
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>

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

</body>
</html>
Assign Events Using the HTML DOM
<!DOCTYPE html>
<html>
<head>
</head>
<body>

<p>Click the button to execute the <em>displayDate()</em> function.</p>

<button id="myBtn">Try it</button>

<script>
document.getElementById("myBtn").onClick=function(){displayDate()};
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>

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

</body>
</html>
• The onload and onunload Events
<!DOCTYPE html>
<html>
<body onload="checkCookies()">

<script>
function checkCookies()
{
if (navigator.cookieEnabled==true)
{
alert("Cookies are enabled")
}
else
{
alert("Cookies are not enabled")
}
}
</script>

<p>An alert box should tell you if your browser has enabled cookies or not.</p>
</body>
</html>
• The onchange Event
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
var x=document.getElementById("fname");
x.value=x.value.toUpperCase();
}
</script>
</head>
<body>

Enter your name: <input type="text" id="fname" onchange="myFunction()">


<p>When you leave the input field, a function is triggered which transforms the
input text to upper case.</p>

</body>
</html>
• The onmouseover and onmouseout Events
<!DOCTYPE html>
<html>
<body>

<div onmouseover="mOver(this)" onmouseout="mOut(this)" style="background-


color:#D94A38;width:120px;height:20px;padding:40px;">Mouse Over Me</div>

<script>
function mOver(obj)
{
obj.innerHTML="Thank You"
}

function mOut(obj)
{
obj.innerHTML="Mouse Over Me"
}
</script>

</body>
</html>
The onmousedown, onmouseup and onclick Events
<!DOCTYPE html>
<html>
<body>

<div onmousedown="mDown(this)" onmouseup="mUp(this)" style="background-


color:#D94A38;width:90px;height:20px;padding:40px;">Click Me</div>

<script>
function mDown(obj)
{
obj.style.backgroundColor="#1ec5e5";
obj.innerHTML="Release Me"
}

function mUp(obj)
{
obj.style.backgroundColor="#D94A38";
obj.innerHTML="Thank You"
}
</script>

</body>
</html>

You might also like