Você está na página 1de 22

What is JavaScript?

•JavaScript was designed to add interactivity to HTML pages


•JavaScript is a scripting language
•A scripting language is a lightweight programming language
•JavaScript is usually embedded directly into HTML pages
•Everyone can use JavaScript without purchasing a license
Are Java and JavaScript the Same?
NO!
Java and JavaScript are two completely different languages in both
concept and design!
Java (developed by Sun Microsystems) is a powerful and much more
complex programming language - in the same category as C and C++.
What can a JavaScript Do?
•JavaScript can put dynamic text into an HTML page - A JavaScript
statement like this: document.write("<h1>" + name + "</h1>") can write a
variable text into an HTML page.
•JavaScript can react to events - A JavaScript can be set to execute when
something happens.
•JavaScript can read and write HTML elements - A JavaScript can read
and change the content of an HTML element.
•JavaScript can be used to validate data - A JavaScript can be used to
validate form data before it is submitted to a server.
•JavaScript can be used to detect the visitor's browser - A JavaScript can
be used to detect the visitor's browser, and - depending on the browser -
load another page specifically designed for that browser
•JavaScript can be used to create cookies - A JavaScript can be used to
store and retrieve information on the visitor's computer
Why Use JavaScript?
 JavaScript enhances Web pages with dynamic and interactive
features.
JavaScript runs in client software.
JavaScript enables shopping carts, form validation, calculations,
special graphic and text effects, image swapping, image mapping,
clocks, and more.
Unlike HTML, JavaScript is case sensitive.
Objects refers to windows, documents, images, tables, forms,
buttons or links, etc.
Objects should be named.
Objects have properties that act as modifiers.
document is the object.
Methods
Methods are actions applied to particular objects. Methods are
what objects can do..
e.g., document.write(”Hello World")
document is the object.
write is the method.
Events
Events associate an object with an action.
e.g., the OnMouseover event handler action can change an
image.
e.g., the onSubmit event handler sends a form.
User actions trigger events
Embedding JavaScript in HTML.
When specifying a script only the tags <script> and
</script> are essential, but complete specification is
recommended:

<script language="javascript”
type="text/javascript">
<!-- Begin hiding
window.location=”index.html"
// End hiding script-->
</script>
How to Put a JavaScript Into an HTML Page

<html>
<body>
<script type="text/javascript"> document.write("Hello World!");
</script>
</body>
</html>
To insert a JavaScript into an HTML page, we use the
<script> tag. Inside the <script> tag we use the type
attribute to define the scripting language.
The word document.write is a standard JavaScript command for
writing output to a page.
JavaScript Statements

Javascript is a sequence of statements to be executed by the


browser.

unlike html, javascript is case sensitive - therefore watch your


capitalization closely when you write javascript statements, create
or call variables, objects and functions.
A JavaScript statement is a command to the browser. The purpose
of the command is to tell the browser what to do.
Javascript comments
comments can be added to explain the javascript, or to make it
more readable.
Single line comments start with //.
this example uses single line comments to explain the code:
Try it
<html>
<head>
<title>Title of the Page</title>
<script language="JavaScript">

function hello(){
alert("Hello World")
}
</script>
</head>
<body onLoad="hello()">
Here are the contents of the page!
</body>
</html>
function hello(){, defines a function. function is a reserved word
that must be in this position. hello, by contrast, is the name of the
function, which you can choose as you like. The only thing you have to
watch out for is that you don’t choose a
reserved word as your function name – it’s best to give functions
meaningful names. By the way – reserved words are words that can only
be used in Java Code itself, not as function or variable names.
() means that the function isn’t expecting any parameters, that is, it
doesn’t
need any values.
onLoad="hello()">. This means that our function, again without
parameters, should be called when the document is loaded. The whole
thing should be saved as
a normal HTML file and called up in the browser
onUnload
…is the opposite of the event handler onLoad and is activated when an HTML page
closes.
The following example is a transformation of the “Hello World” program. When leaving
the page, it displays the message “Goodbye.” This could, for example, happen when a
link is activated. If the link in our example is to function properly, you must create one
further HTML
page, called here page2.htm.
<html>
<head>
<title>Title of the Page</title>
<script language="JavaScript">
function goodbye(){
alert("Goodbye!")
}
</script>
</head>
<body onUnload="goodbye()">
Now you are leaving this page <a href="page2.htm">for another</a>.
</body>
</html>
JavaScript Where To
JavaScripts can be put in the body and in the head sections of an HTML
page.
Scripts in <head>
Scripts to be executed when they are called, or when an event is
triggered, are placed in functions.
Put your functions in the head section, this way they are all in one
place, and they do not interfere with page content.

<html>
<head>
<script type="text/javascript">
function message()
{
alert("This alert box was called with the onload event");
}
</script>
</head>
<body onload="message()">
</body>
</html>
Scripts in <body>
If you don't want your script to be placed inside a function,
or if your script should write page
content, it should be placed in the body section.
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.write("This message is written by JavaScript");
</script>
</body>
</html>
Scripts in <head> and <body>
You can place an unlimited number of scripts in your document, so you
can have scripts in both the
body and the head section.
Example
<html>
<head>
<script type="text/javascript">
function message()
{
alert("This alert box was called with the onload event");
}
</script>
</head>
<body onload="message()">
<script type="text/javascript">
document.write("This message is written by JavaScript");
</script>
</body>
</html>
Using an External JavaScript
If you want to run the same JavaScript on several
pages, without having to write the same script on
every page, you can write a JavaScript in an external
file.
Save the external JavaScript file with a .js file
extension.
Note: The external script cannot contain the
<script></script> tags!
<html>
<head>
<script type="text/javascript" src="abc.js"></script>
</head>
<body>
</body>
</html>
JavaScript If...Else Statements
Conditional statements are used to perform different actions based on different
conditions.
Conditional Statements
Very often when you write code, you want to perform different actions for different
decisions. You
can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
if statement - use this statement to execute some code • only if a specified condition
is true
if...else statement - use this statement to execute some code if the condition is true
and
another code if the condition is false

if...else if....else statement - use this statement to select one of many blocks of code
to be
executed

• switch statement - use this statement to select one of many blocks of code to be
executed
Syntax
if (condition)
{
code to be executed if condition is true
}
Note that if is written in lowercase letters. Using uppercase letters (IF) will
generate a JavaScript
error!
If...else Statement
Use the if....else statement to execute some code if a condition is true and
another code if the
condition is not true.
Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
How to Validate
• Before submitting the user’s input to the
server-side.
– it’s always a good approach to validate it on the
client-side script.
• When you want the full name input from the
user, the input value must be checked
whether the user provides a valid name (first
name and last name).
• Validating email is a very important point
while validating an HTML form. In this page
we have discussed how to validate an email
using JavaScript :
Full name validation

• The above code snippet shows how you can


validate the input field for the full name in HTML
form using JavaScript.
Email validation
Cont..
Email validation using index function
<html>
<body>
<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="#" onsubmit="return validateemail();">
Email: <input type="text" name="email"><br/>

<input type="submit" value="register">


</form>
</body>
</html>
Enter Userid [between 6 to 8
characters] and Submit
function stringlength(inputtxt, minlength, maxlength)
{ var field = inputtxt.value;
var mnlen = minlength;
var mxlen = maxlength;
if(field.length<mnlen || field.length> mxlen)
{ alert("Please input the userid between " +mnlen+ " and " +mxlen+ " characters");
return false;}
else
{ alert('Your userid have accepted.');
return true;}}

Você também pode gostar