1 of 25

Functions in JavaScript

  • a function is a set of statements that performs some tasks or does some computation and then return the result to the user.
  •  commonly or repeatedly done tasks together and make a function.
  • JavaScript also supports the use of functions. You must already have seen some commonly used functions in JavaScript like alert(), this is a built-in function in JavaScript. But JavaScript allows us to create user-defined functions also.
  • We can create functions in JavaScript using the keyword function.

2 of 25

Syntax:

function functionName(Parameter1, Parameter2, ..)

{

// Function body

}

Below are the rules for creating a function in JavaScript:

  • Every function should begin with the keyword function followed by,
  • A user defined function name which should be unique,
  • A list of parameters enclosed within parenthesis and separated by commas,
  • A list of statement composing the body of the function enclosed within curly braces {}.

function calcAddition(number1, number2)

{

return number1 + number2;

}

3 of 25

Example:

<!DOCTYPE HTML>

<html>

<body>

<script type = "text/javascript">

function welcomeMsg(name)

{

document.write("Hello" + name + “World");

}

var nameVal = "Admin";

welcomeMsg(nameVal);

</script>

</html>

</body>

4 of 25

JavaScript Events

  • The change in the state of an object is known as an Event. In html, there are various events which represents that some activity is performed by the user or by the browser.

  • When javascript code is included in HTML, js react over these events and allow the execution. This process of reacting over the events is called Event Handling. Thus, js handles the HTML events via Event Handlers.

  • For example, when a user clicks over the browser, add js code, which will execute the task to be performed on the event.

5 of 25

Some of the HTML events are

  • Mouse events
  • Keyboard events
  • Form events
  • Window/Document events

6 of 25

Mouse events:

7 of 25

Keyboard events

Window/Document events

8 of 25

Form events:

9 of 25

Ex: Click Event

<html>  

<head> Javascript Events </head>  

<body>  

<script language="Javascript" type="text/Javascript">  

    <!--  

    function clickevent()  

    {  

        document.write("This is OnClick event");  

    }  

    //-->  

</script>  

<form>  

<input type="button" onclick="clickevent()" value=“Click Here"/>  

</form>  

</body>  

</html>

10 of 25

Focus Event

<html>  

<head> Javascript Events</head>  

<body>  

<h2> Enter something here</h2>  

<input type="text" id="input1" onfocus="focusevent()"/>  

<script>  

<!--  

    function focusevent()  

    {  

        document.getElementById("input1").style.background=" aqua";  

    }  

//-->  

</script>  

</body>  

</html>  

11 of 25

Keydown Event

<html>  

<head> Javascript Events</head>  

<body>  

<h2> Enter something here</h2>  

<input type="text" id="input1" onkeydown="keydownevent()"/>  

<script>  

<!--  

    function keydownevent()  

    {  

        document.getElementById("input1");  

        alert("Pressed a key");  

    }  

//-->  

</script>  

</body>  

</html>  

12 of 25

Load event

<html>  

<head>Javascript Events</head>  

</br>  

<body onload="window.alert('Page successfully loaded');">  

<script>  

<!--  

document.write("The page is loaded successfully");  

//-->  

</script>  

</body>  

</html>  

13 of 25

DOM (Document Object Model)

  • The Document Object Model (DOM) is a programming interface for HTML and XML(Extensible markup language) documents. It defines the logical structure of documents and the way a document is accessed and manipulated.
  • DOM is a way to represent the webpage in a structured hierarchical way so that it will become easier for programmers and users to glide through the document. With DOM, we can easily access and manipulate tags, IDs, classes, Attributes, or Elements using commands or methods provided by the Document object.
  • Web documents are made available to Client-Side JavaScript via the Document Object Model (DOM).
  • The items contained in a Web document become objects in the browser's memory as the browser loads and interprets the HTML code that defines them.
  • Notice that the DOM is arranged in a hierarchical way with window as the highest-level object.

14 of 25

Why DOM is required?

  • HTML is used to structure the web pages and Javascript is used to add behavior to our web pages.
  • When an HTML file is loaded into the browser, the javascript can not understand the HTML document directly. So, a corresponding document is created(DOM). 
  • DOM is basically the representation of the same HTML document but in a different format with the use of objects.
  • Javascript interprets DOM easily i.e javascript can not understand the tags(<h1>H</h1>) in HTML document but can understand object h1 in DOM.
  • Now, Javascript can access each of the objects (h1, p, etc) by using different functions.

15 of 25

DOM Hierarchy: The Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web document.

16 of 25

Window object − Top of the hierarchy. It is the outmost element of the object hierarchy.

Document object − Each HTML document that gets loaded into a window becomes a document object. The document contains the contents of the page.

Form object − Everything enclosed in the <form>...</form> tags sets the form object.

Form control elements − The form object contains all the elements defined for that object such as text fields, buttons, radio buttons, and checkboxes.

17 of 25

Window Object

  • The window object represents the browser window. You can use it to open a Web page in a new window and to set the attributes for the window. There are only two main window properties.

They are:

status - set the status bar message

self - stores the name of the current window.

Methods:

open() - Opens a new browser window

close() - Closes the current window

focus() - Sets focus to the current window

blur() - Removes focus from the current window

print() - Prints the content of the current window

alert() - Displays an alert box with a message and an OK button

prompt() - Displays a dialog box that prompts the visitor for input

confirm() - Displays a dialog box with a message and an OK and a Cancel button

18 of 25

Document Object

  • The Document object represents the Web page that is loaded in the browser window, and the content displayed on that page, including text and form elements.

Methods: You can use the methods of the document object to work on a Wb page.

Here are the most common document methods:

write() - write a string to the Web page

open() - opens a new document

close() - closes the document

Properties: Use the properties of the document object to set the colors of the page, the title and display the date the document was last modified. JavaScript has about 150 defined color words you can use or you can provide the hexidecimal RGB codes.

Here are the most common document properties:

bgColor – to set the background color of the document.

fgColor – to set the foreground color of the document .

linkColor – to set the color for the links of the document.

title – to set the title for document.

19 of 25

Form Validation in Java Script

  • It is important to validate the form submitted by the user because it can have inappropriate values. So, validation is must to authenticate user.
  • JavaScript provides facility to validate the form on the client-side so data processing will be faster than server-side validation. Most of the web developers prefer JavaScript form validation.
  • JavaScript provides a way to validate form's data on the client's computer before sending it to the web server. Form validation generally performs two functions.
  • Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data.
  • Data Format Validation − Secondly, the data that is entered must be checked for correct form and value. Your code must include appropriate logic to test correctness of data.
  • Through JavaScript, we can validate name, password, email, date, mobile numbers and more fields.

20 of 25

Basic Form Validation

<script type = "text/javascript">

function validate()

{

if( document.myForm.Name.value == "" )

{

alert( "Please provide your name!" );

document.myForm.Name.focus() ;

return false;

}

if( document.myForm.EMail.value == "" )

{

alert( "Please provide your Email!" );

document.myForm.EMail.focus() ;

return false;

}

}

</script>

21 of 25

Data Format Validation

<script type = "text/javascript">

function validateEmail()

{

var emailID = document.myForm.EMail.value;

atpos = emailID.indexOf("@");

dotpos = emailID.lastIndexOf(".");

if (atpos < 1 || ( dotpos - atpos < 2 ))

{

alert("Please enter correct email ID") document.myForm.EMail.focus() ;

return false;

}

return( true );

}

</script>

22 of 25

JavaScript Form Validation Example

<script>  

function validateform(){  

var name=document.myform.name.value;  

var password=document.myform.password.value;  

 if (name==null || name==""){  

  alert("Name can't be blank");  

  return false;  

}else if(password.length<6){  

  alert("Password must be at least 6 characters long.");  

  return false;  

  }  

}  

</script>  

<body>  

<form name="myform" method="post“  onsubmit="return validateform()" >  

Name: <input type="text" name="name"><br/>  

Password: <input type="password" name="password"><br/>  

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

</form>  

23 of 25

24 of 25

JavaScript Retype Password Validation

<script type="text/javascript">  

function matchpass(){  

var firstpassword=document.f1.password.value;  

var secondpassword=document.f1.password2.value;  

  if(firstpassword==secondpassword){  

return true;  

}  

else{  

alert("password must be same!");  

return false;  

}  

}  

</script>  

 <form name="f1“ onsubmit="return matchpass()">  

Password:<input type="password" name="password" /><br/>  

Re-enter Password:<input type="password" name="password2"/><br/>  

<input type="submit">  

</form> 

25 of 25

JavaScript Number Validation

<script>  

function validate(){  

var num=document.myform.num.value;  

if (isNaN(num)){  

  document.getElementById("numloc").innerHTML="Enter Numeric value only";  

  return false;  

}

else{  

  return true;  

  }  

}  

</script>  

<form name="myform" onsubmit="return validate()" >  

Number: <input type="text" name="num"><span id="numloc"></span><br/>  

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

</form>