javascript functions in html

A JAVASCRIPT FUNCTIONS will be executed by an event or by a call to the function.

JavaScript Functions:

To keep the browser from executing a script when the page loads, you can put your script into a function. A function contains code that will be executed by an event or by a call to the function. You may call a function from anywhere within a page (or even from other pages if the function is embedded in an external .js file).

Functions can be defined both in the <head> and in the <body> section of a document. However, to assure that a function is read/ loaded by the browser before it is called, it could be wise to put functions in the <head> section.

How to Define a JavaScript Function?

Syntax:

function functionname(var1, var2, …., varX)

{

some code

}

The parameters var1, var2, etc. are variables or values passed into the function. The { and the } defines the start and end of the function.

Note: A function with no parameters must include the parentheses ( ) after the function name.

Note: Do not forget about the importance of capitals in JavaScript! The word function must be written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a function with the exact same capitals as in the function name.

JavaScript Function Example :

Example:

<html>
<head>
<script type= “text/javascript”>
Function displaymessage( )
{
alert(“Jai Mata Di!”);
}
</script>
</head>
<body>
<form>
<input type= “button” value= “Click me!”
onclick= “displaymessege( )”/>
</form>
</body>
</html>

If the line: alert(“Jai Mata Di!”) in the example above had not been put within a function, it would have been executed as soon as the line was loaded. Now, the script is not executed before a user hits the input button. The function displaymessage( ) will be executed if the input button is clicked.

The return Statement:

The return statement is used to specify the value that is returned from the function. So, functions that are going to return a value must use the return statement.

The example below returns the product of two numbers (a and b):

Example:

<html>
<head>
<script type= “text/javascript”>
function product(a,b)
{
return a*b;
}
</script>
</head>
<body>
<script type= “text/javascript”>
document.write(product(5,10));
</script>
</body>
</html>

The Lifetime of JavaScript Variables:

If you declare a variable within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables.

You can have local variables with the same name in different functions because each is recognized only by the function in which it is declared.

JAVASCRIPT SPECIAL CHARACTERS:

In JavaScript you can add special characters to a text string by using the backslash sign.

Insert Special Characters:

The backslash (\) is used to insert apostrophes, new lines, quotes, and other special characters into a text string.

Look at the following JavaScript code:

var txt= “We are the so-called “Vikings” from the north.”;

document.write(txt);

In JavaScript, a string is started and stopped with either single or double quotes. This means that the string above will be chopped to: We are the so-called

To solve this problem, you must place a backslash(\) before each double quote in “Viking”. This turns each double quote into a string literal:

var txt= “We are the so-called\ “Vikings\” from the north.”;

document.write(txt);

JavaScript will now output the proper text string: We are the so-called “Vikings” from the north.

Here is another example:

document.write (“You \& I are singing!”);

The example above will produce the following output:

You & I are singing!

The table below lists other special characters that can be added to a text string with the backslash sign:

CodeOutputs
\’single quote
\”double quote
\&ampersand
\\backslash
\nnew line 
\rcarriage return
\ttab
\bbackspace
\fform feed
JAVASCRIPT FUNCTIONS

JavaScript is Case Sensitive:

A function named “myfunction” is not the same as “myFunction” and a variable named “myVar” is not the same as “myvar”. JavaScript is case sensitive- therefore watch your capitalization closely when you create or call variables, objects and functions.

White Space:

JavaScript ignores extra space. You can add white space to your script to make it more readable. The following lines are equivalent:

name= “Hege”;

name= “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:

document.write(“Hello\World!”);

However, you cannot break up a code line like this:

document.write\

(“Hello World!”);

JAVASCRIPT BROWSER DETECTION:

The Navigator object contains information about the vistior’s browser.

Browser Detection:

Almost everything in this tutorial works on all JavaScript-enabled browsers. However, there are some things that just don’t work on certain browsers especially on older browsers. So, sometimes it can be very useful to detect the visitor’s browser, and then serve up the appropriate information.

The best way to do this is to make your web pages smart enough to look one way to some browsers and another way to other browsers. The Navigator object can be used for this purpose.

The Navigator object contains information about the visitor’s browser name, version, and more.

Note: There is no public standard that applies to the navigator object, but all major browsers support it.

The Navigator Object:

The Navigator object contains all information about the visitor’s browser. We are going to look at two properties of the Navigator object:

appName: holds the name of the browser.

appVersion: holds, among other things, the version of the browser.

Example:

<html>
<body>
<script type= “text/javascript”>
var browser= navigator.appName;
var b_version= navigator.appVersion;
var version= parseFloat(b_version);
documnet.write(“Browser name:”+ browser);
document.write(“<br/>”);
document.write(“Browser version:”+ version);
</scrip>
</body>
</html>

The variable “browser” in the example above holds the name of the browser, i.e. “Netscape” or “Microsoft Internet Explorer”.

The example below displays a different alert, depending on the visitor’s browser:

Example:

<html>
<head>
<script type= “text/javascript”>
function detectBrowser( )
{
var browser= navigator.appName;
var b_version= navigator.appVersion;
var version= parselFloat(b_version);
if ((browser== “Netscape”|| browser== “Microsoft Internet Explorer”)
&& (version>=4))
{
alert(“Your browser is good enough!”);
}
else
{
alert(“It’s time to upgrade your browser!”);
}
}
</script>
</head>
<body onload= “detectBrowser( )”>
</body>
</html>

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?

Required Fields:

The function below checks if a required field has been left empty. If the required field is blank, an alert box alert a message and the function returns false. If a value is entered, the function returns true (means that data is OK):

function validate_required(field,alerttxt)

{
with (field)
{
if (value==null || value== “”)
{
alert(alerttxt);return false;
}
else
{
return true;
}
}
}

The entire script, with the HTML form could look something like this:

<html>
<head>
<script type= “text/javascript”>
function validate_required(field,alerttxt)
{with (field)
{
if (value==null || value== “”)
{
alert(alerttxt);return false;
}
else{
return true;
}
}
}
function validate_form(thisform)
{
with (this form)
{
if (validate_required(email, “Email must be filled out!”)==false)
{email.focus( );return false;}
}
}
</script>
</head>
<body>
<form action= “submit.htm” onsubmit= “return
vaildate_form(this)” method= “post”>
Email: <input type= “text” name= “email”
size= “30”>
<input type= “submit” value= “Submit”>
</form>
</body>
</html>

E-mail Validation:

The function below checks if the content has the general syntax of an e-mail.

This means that the input data must contain at least an @ sign and a dot (.). Also, the @ must not be the first character of the e-mail address, and the last dot must at least be one character after the @ sign:function

validate_email(field, alerttxt)
{
with (field)
{
apos= value.indexOf(“@”);
dotpos= value.lastIndexOf(“.”);
if (apos<1 || dotpos-apos<2)
{alert(alerttxt);return false;}
else {return true;}
}
}

The entire script, with the HTML form could look something like this:

<html>
<head>
<script type= “text/javascript”>
function validate_email(field,alerttxt)
{
with (field)
{
apos= value.indexOf(“@”);
dotpos= value.lastIndexOf(“.”);
if (apos<1||dotpos-apos<2)
{alert(alerttxt);return false;}
else{return true;}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_email(email, “Not a valid e-mail
address!”)==false)
{email.focus( );return false;}
}
}
</script>
</head>
<body>

<form action= “submit.htm” onsubmit= “return
validate_form(this);” method= “post”>

Email: <input type= “text” name= “email” size= “30”>
<input type= “submit” value= “Submit”>
</form>
</body>
</html>

JAVASCRIPT ANIMATION:

With JavaScript we can create animated images.

* It is possible to use JavaScript to create animated images.

* The trick is to let a JavaScript change between different images on different events.

* In the following example, we will add an image that should act as a link button on a web page. We will then add an onMouseOver event and an onMouseOut event that will run two JavaScript functions that will change between the images.

The HTML Code:

The HTML code looks like this:

<a href= “http://www.google.com” target= “_blank”>

<img border= “0” alt= “Visit Google!” src= “b_pink.gif” id=”b1”

onmouseOver= “mouseOver( )” onmouseOut= “mouseOut()”/></a>

The JavaScript Code:

The changing between the images is done with the following JavaScript:

<script type= “text/javascript”>
function mouseOver( )
{
document.getElementById(“b1”).src= “b_blue.gif”;
}
function mouseOut( )
{
document.getElementById(“b1”).src= “b_pink.gif”;
</script>

The function mouseOver( ) causes the image to shift to “b_blue.gif”.

The function mouseOut( ) causes the image to shift to “b_pink.gif”.

The Entire Code:

Example:

<html>
<head>
<script type= “text/javascript”>
function mouseOver( ){
document.getElementById(“b1”).src= “b_blue.gif”;}
function mouseOut( ){
document.getElementById(“b1”).src= “b_blue.gif”;}
</script>
</head>


<body>
<a href= “http://www.google.com
target= “_blank”>
<img border= “0” alt= “Visit Google!”
src= “b_pink.gif”
id= “b1”
nmouseover= “mouseOver( )”
onmouseout= “mouseOut( )”/></a>
</body>
</html>

JAVASCRIPT IMAGE MAPS:

An image-map is an image with clickable regions.

Adding some JavaScript:

We can add events (that can call a JavaScript) to the <area> tags inside the image map. The <area> tag supports the onClick, onDblClick, onMouseDown, onMouseUp, onMouseOver, onMouseMove, onMouseOut, onKeyPress, onKeyDown, onKeyUp, onFocus, and onBlur events.

Here’s the HTML image-map example, with some JavaScript added:

Example:

<html>
<head>
<script type= “text/javascript”>
function writeText(txt)
{
document.getElementById(“desc”).innerHTML= txt;
}
</script>
</head>


<body>
<img src= “planets.gif” width= “145” height= “126”
alt= “Planets” usemap= “#planetmap”/>
<map name= “planetmap”>
<area shape= “rect” coords= “0,0,82,126”
onMouseOver= “writeText(‘The Sun and the gas giant planets like Juipter are by far the largest objects in our Solar System.’)”
href= “sun.htm”target= “circle” coords= “90,58,3”
onMouseOver= “writeText(‘Until the 1960s, Venus was often considered a twin sister to the Earth because Venus is the nearest planet to us, and because the two planet seem to share many characteristics.’/>
</map>
<p id= “desc></p>
</body>
</html>

Our Suggested Article’s
ADVANTAGES AND DISADVANTAGES OF GADGETS IN OUR LIFE
What To Do If Mobile Is Stolen??
How To Choose Best Mobile Camera
How To Choose Best Processor For Mobile??
Best Top Ten Printers For Home & Office Use In 2020
How To Send Stickers In WhatsApp??
What Is Domain Name Servers?What Is Ip Address?? And Ip Address ClassesWhat Is A Modem? & Types Of ModemBest Wireless Earphones Under Rs 2000 -Tested & ReviewedConnecting To The Internet In Windows PcWhat Is Internet Definition And Evolution Of The Internet
Ten Best Bluetooth Earphones Under 1000 Rupees -Tested & ReviewedTen Best Wireless Mouse Under 1000 Rupees – Tested & ReviewedThe Best Mouse Under 500 Rupees – Tested And ReviewedBest Wireless Mouse Under 500 Rupees – Tested And Reviewed

Leave a Comment