Java Script
Java Script
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>
• 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";
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 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
};
• 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;
<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++;
}
<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>";
}
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.
<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>
• <!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>
</body>
</html>
HTML Event Attributes
<!DOCTYPE html>
<html>
<body>
<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>
<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>
</body>
</html>
• The onmouseover and onmouseout Events
<!DOCTYPE html>
<html>
<body>
<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>
<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>