Tuesday, July 4, 2017

Javascript Functions

Javascript Functions

Content
* Functions
* Syntax
* Return Statement
* Events
* List of Event Attributes
* Form Validation

Functions
* 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. 

Syntax

function functionname(var1,var2,...,var n)
{
  some code;
}

* The word function must be written in lowercase letters.
* If you declare a variable, using "var", 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. 
 
Example
<script type="text/javascript">
function area(length,breadth)
{
 var a=length*breadth;
document.write(“Area of Rectangle is “+a);
}
</script>

Return statement

* The return statement is used to specify the value that is returned from the function.
Example
<script type="text/javascript">
function area(length,breadth)
{
 var a=length*breadth;
return(a);
}
</script>

Events

* HTML events are "things" that happen to HTML elements.
* When JavaScript is used in HTML pages, JavaScript can "react" on these events
* An HTML event can be something the browser does, or something a user does
* JavaScript lets you execute code when events are detected
* HTML allows event handler attributes, with JavaScript code, to be added to HTML elements
* Examples of 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

* <'some-HTML-element' some-event='some JavaScript'>

Example

<html>
<body>
<button onclick="getElementById('sample').innerHTML=Date()">Date and Time</button>
<p id="sample"></p>
</body>
</html>

* In the above example, an onclick event attribute is added to a button element. As soon as user clicks the button, date and time will appear. Date() is a built-in function.
* Another way is to put everything in a javascript function can invoke on a button click.

Example

<html>
<body>
<p>Click the button to display the date.</p>
<button onclick="displayDate()">Date and Time</button>
<script>
function displayDate() {
    document.getElementById("sample").innerHTML = Date();
}
</script>
<p id="sample"></p>
</body>
</html>

List of Event Attributes

* There are several event attributes we can use with HTML tags and bind them with some javascript code.
* Here is the list of event attributes
Event Name - Description
* onclick  - The event occurs when the user clicks on an element
* ondblclick - The event occurs when the user double-clicks on an element
* onmousedown - The event occurs when a user presses a mouse button over an element
* onmouseover - The event occurs when the pointer is moved onto an element
* onmousemove - The event occurs when the pointer is moving while it is over an element
* onmouseout - The event occurs when a user moves the mouse pointer out of an element
* onmouseup  - The event occurs when a user releases a mouse button over an element
* onkeydown  - The event occurs when the user is pressing a key
* onkeypress - The event occurs when the user presses a key
* onkeyup - The event occurs when the user releases a key
* onload  - The event occurs when a document, frameset, or <object> has been loaded
* onresize  -  The event occurs when a document view is resized
* onscroll  -  The event occurs when a document view is scrolled
* onunload  -  The event occurs once a page has unloaded (for <body> and <frameset>)
* onblur - The event occurs when a form element loses focus
* onchange  -  The event occurs when the content of a form element, the selection, or the checked state have changed (for <input>, <select>, and <textarea>)
* onfocus - The event occurs when an element gets focus (for <label>, <input>, <select>, textarea>, and <button>)
* onselect  -  The event occurs when a user selects some  text (for <input> and <textarea>)
* onsubmit  -  The event occurs when a form is submitted

Example: Display Mouse position

<html>
 <head>
  <title>mouse Example</title>
  <style type="text/css">
  </style>
  <script type="text/javascript">
   function f1(event)
   {
    var ptag=document.getElementsByTagName("p");
    ptag[0].innerHTML="x="+event.clientX+"  y="+event.clientY;       
   }
  </script>
 </head>
 <body onmousemove="f1(event)">
  <h1> Move mouse to see mouse coordinates </h1>
   <p></p>
 </body> 
</html>

Example: Change background when mouse move over a paragraph

<html>
 <head>
  <script type="text/javascript">
   function effect1(para)
   {
     para.style.backgroundColor="pink";
   }
   function effect2(para)
   {
     para.style.backgroundColor="white";
   }
  </script>
 </head>
 <body>
  <h2>Move mouse on paragraph and see changes</h2>
  <p onmouseover="effect1(this)" onmouseout="effect2(this)">
ITRun is a premier organization founded in 1990, growing as an IT Training/service providers and determined to set high standards in IT industry. Initially started as an IT training institute, we have now expanded to include software development as well as IT Consultant Services. Currently we operate as three strategic business units focusing on – IT Training, IT Development, and IT Solutions.

There are several activities which we are carrying out simultaneously to achieve this goal. We are offering courses in hottest and most demanded technologies of this area like C, C++ C#(sharp), Oracle, VC++, Java, Advance Java, VB.Net, ASP.Net, PHP, Android, Networking and IPv6 Area (CCNA, CNE6 – Level 1(Silver) and CNE6 – Level 2 (Gold)) also. We also encourage students to learn and adopt standards of software development process. From its establishment onwards ITRun has created a niche for itself in the education and software sector.

We are working for the promotion of latest technologies in IT along with providing a solid basic foundation to a student to stand firmly in this competitive and cut through era.
  </p>
 </body>
</html>

Example: Add two numbers on a click of button

<html>
 <head>
  <title> JAVASCRIPT </title>
  <script type="text/javascript" >
  function add()
  {
   var x=parseInt(document.getElementById("i1").value);
   var y=parseInt(document.getElementById("i2").value);
   var z=x+y;    
   document.write("Sum is "+z);
  } 
  </script>
 </head>
 <body>
  First  Number:<input id="i1" type="text" /><br/>
  Second Number:<input id="i2" type="text" /><br/>
  <button onclick="add()">Add</button>
 </body>
</html>


Form Validation

* JavaScript can be used to validate data in HTML forms before sending off the content to a server
* Javascript can check
 - the user left required fields empty
 - the user entered a valid e-mail address
 - the user entered a valid date
 - the user entered text in a numeric field 
* Create a javascript function and get input element.
* Use decision control and compare input value with empty string ("") or null.
* Use isNaN() method of javascript to check if data is not a number.

Example: Checking an email

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;
  }
}

Example: A Complete example of form validation
form.html
<html>
 <head>
  <title>Form Validation </title>
  <link rel="stylesheet" href="formstyle.css"/> 
  <script type="text/javascript" >
   function focus1()
   {
     document.getElementsByName("name")[0].focus();
   }

   function validation()
   {
    var err=0;
    var n1=document.getElementsByName("name");
    var n2=document.getElementsByName("mobile");
    var n3=document.getElementsByName("gender");
    var n4=document.getElementsByName("pwd");
    if(n1[0].value.length==0)
    {
     document.getElementById("s1").innerHTML="*";
     document.getElementById("s1").style.color="red";
     err=1;
    }
    else
     document.getElementById("s1").innerHTML="";
    if(n2[0].value.length!=10)
    {
     document.getElementById("s2").innerHTML="*";
     document.getElementById("s2").style.color="red";
     err=1;
    }
    else
     document.getElementById("s2").innerHTML="";
        
    if(n3[0].checked==false && n3[1].checked==false)
    {
     document.getElementById("s3").innerHTML="*";
     document.getElementById("s3").style.color="red";
     err=1;
    }
    else
     document.getElementById("s3").innerHTML="";
   
    if(n4[0].value.length<4)
    {     
     document.getElementById("s4").innerHTML="*";
     document.getElementById("s4").style.color="red";
     err=1;
    }
    else
     document.getElementById("s4").innerHTML="";   
  
    var n5=document.getElementsByName("c");
    var n6=document.getElementsByName("cpp");
    var n7=document.getElementsByName("php");
    if(n5[0].checked==false&&n6[0].checked==false&&n7[0].checked==false)
    {
     document.getElementById("s5").innerHTML="*";
     document.getElementById("s5").style.color="red";
     err=1;
    }
    else
     document.getElementById("s5").innerHTML="";
    if(err==1)
     return(false);
    
    return(true);    
   }
  </script>
 </head>
 <body onload="focus1()">
  <form action="validate.php" method="get" >
  <table>
    <caption>Registration Form </caption>
   <tr>
    <td>Name</td>
    <td><input type="text" name="name"/><span id="s1"></span></td>
   </tr>
   <tr>
    <td>Mobile</td>
    <td><input type="text" name="mobile"/><span id="s2"></span></td>
   </tr>
   <tr>
    <td>Gender</td>
    <td>
       <input type="radio" name="gender" value="male"/>Male<span id="s3"></span><br/>
       <input type="radio" name="gender" value="female"/>Female 
    </td>
   </tr>
   <tr>
    <td>Password</td>
    <td><input type="password" name="pwd"/><span id="s4"></span></td>
   </tr>
   <tr>
    <td>Courses</td>
    <td><input type="checkbox" name="c"/>C<span id="s5"></span><br/>
        <input type="checkbox" name="cpp"/>C++<br/>
        <input type="checkbox" name="php"/>PHP<br/>
    </td>
   </tr>
   <tr>
    <td>City</td>
    <td>
     <select name="city">
      <option> Bhopal</option>
      <option> Indore</option>
      <option> Jabalpur</option>
      <option> Indore</option>
     </select>
    </td>
   </tr>
   <tr>
    <td></td>
    <td><input id="submit" type="submit" value="submit" name="submit" onclick="return validation()"/></td>
   </tr>
  </table>
  </form>
 </body>
</html>

formstyle.css

body
{
 background-color:lightblue;
}
table
{
 position:fixed;
 left:300px;
 border:2px solid black;

}
table caption
{
 font-size:30px;
 color:navy;
}
table tr
{
 background-color:lightgreen;
 height:40px;
}
table tr td
{
 padding:5px;
 font-weight:bold;
 color:brown;
}
form
{
 position:fixed;
 left:265px; 
 border:2px solid red;
 height:400px;
 width:300px;
}
#submit
{
 background-color:green;
 color:yellow;
 font-weight:bold;
}

<<Prev     Home     Next>>

No comments:

Post a Comment