Java Script
Java Script
• HIGH LEVEL
• DYNAMICALLY TYPED
• INTERPETTED
• OBJECT ORIENTED
• FULLY PROGRAMMING LANGUAGE
• JAVASCRIPT IS NOT COMPILED BUT
TRANSLATED.
• THE JAVASCRIPT TRANSLATOR (EMBEDDED IN
BROWSER) IS RESPONSIBLE TO TRANSLATE THE
JAVASCRIPT CODE.
Where we used JavaScript
• JavaScript is used to create interactive websites.
It is mainly used for:
• Client-side validation
• Dynamic drop-down menus
• Displaying data and time
• Displaying popup windows and dialog boxes (like
alert dialog box, confirm dialog box and prompt
dialog box)
• Displaying clocks etc.
JavaScript Overview
Client-Side Javascript
Server-Side Javascript
Output :
JavaScript Placement in HTML File
• There is a flexibility given to include JavaScript code
anywhere in an HTML document. But there are
following most preferred ways to include JavaScript
in your HTML file.
– Script in <head>...</head> section.
– Script in <body>...</body> section.
– Script in <body>...</body> and <head>...</head>
sections.
– Script in and external file and then include in
<head>...</head> section.
JavaScript in <head>...</head> section:
JavaScript in <body>...</body> section:
JavaScript in <body> and <head> sections:
JavaScript in External File :
Whitespace and Line Breaks:
• JavaScript ignores spaces, tabs, and newlines that
appear in JavaScript programs..
• Semicolons are Optional:
}
Internals of global variable in
JavaScript
• When you declare a variable outside the function, it is added
in the window object internally.
• You can access it through window object also.
• For example:
var value=50;
function a(){
• Arithmetic Operators
• Comparison (Relational) Operators
• Bitwise Operators
• Logical Operators
• Assignment Operators
• Special Operators
JavaScript Arithmetic Operators
• Arithmetic operators are used to perform arithmetic operations on
the operands. The following operators are known as JavaScript
arithmetic operators.
JavaScript Comparison Operators
• The JavaScript comparison operator compares the two operands.
The comparison operators are as follows:
JavaScript Bitwise Operators
JavaScript Logical Operators
JavaScript Assignment Operators
JavaScript Special Operators
JavaScript If-else
• The JavaScript if-else statement is used to
execute the code whether condition is true or false.
• If Statement
• If else statement
• if else if statement
if statement:
• The if statement is the fundamental control
statement that allows JavaScript to make decisions
and execute statements conditionally.
• Syntax:
• Example :
if...else statement:
• The if...else statement is the next form of control
statement that allows JavaScript to execute
statements in more controlled way.
• Syntax:
• Example :
if...else if... statement:
• The if...else if... statement is the one level advance
form of control statement that allows JavaScript to
make correct decision out of several conditions.
• Syntax :
Example :
JavaScript Switch Case
• The JavaScript switch statement is used to execute
one code from multiple expressions.
• Syntax:
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>
Javascript -
document.getElementById() method
• The document.getElementById() method returns the element of
specified id.
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
Javascript - document.getElementsByName()
method
• The document.getElementsByName() method returns all the element of
specified name.
<script type="text/javascript">
function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">
<input type="button" onclick="totalelements()" value="Total Genders">
</form>
document.getElementsByTagName()
method
• The document.getElementsByTagName() method returns all the
element of specified tag name.
<script type="text/javascript">
function countpara()
{
var totalpara=document.getElementsByTagName("p");
alert("total p tags are: "+totalpara.length);
}
</script>
<p>This is a pragraph</p>
<p>Here we are going to count total number of paragraphs by getEl
ementByTagName() method.</p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button>
Javascript - innerHTML
document.getElementById('mylocation').innerHTML=data;
}
</script>
<form name="myForm">
<input type="button" value="comment" onclick="showcommentform()">
<div id="mylocation"></div>
</form>
Javascript - innerText
• The innerText property can be used to write the
dynamic text on the html document. Here, text
will not be interpreted as html text but a normal
text.
• It is used mostly in the web pages to generate the
dynamic content such as writing the validation
message, password strength etc.
<script type="text/javascript" >
function validate() {
var msg;
if(document.myForm.userPass.value.length>5){
msg="good";
}
else{
msg="poor";
}
document.getElementById('mylocation').innerText=msg;
}
</script>
<form name="myForm">
<input type="password" value="" name="userPass"
onkeyup="val idate()">
Strength:<span id="mylocation">no strength</span>
</form>
JavaScript Form Validation
<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" action="abc.jsp" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
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>
if(name.length<1){
document.getElementById("nameloc").innerHTML=
" <img src='unchecked.gif'/> Please enter your name";
status=false;
}
else{
document.getElementById("nameloc").innerHTML=" <img src='checked.gif'/>";
status=true;
}
if(password.length<6)
{
document.getElementById("passwordloc").innerHTML=
" <img src='unchecked.gif'/> Password must be at least 6 char long";
status=false;
}
else{
document.getElementById("passwordloc").innerHTML=" <img src='checked.gif'/>";
}
return status;
}
</script>
<span id="passwordloc"></span></td></tr>
<tr><td colspan="2"><input type="submit" value="register"/></td></tr>
</table>
</form>
JavaScript email validation
<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){
• This is the most frequently used event type which occurs when a user clicks the left button of his mouse. You can put your
validation, warning etc., against this event type.
• Example
<html>
<head>
<script type="text/javascript">
<!–
function sayHello() {
alert("Hello World") ;
}
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello" />
</form>
</body>
</html>
INPUT EVENTS
onblur : it triggers only when a user leaves input field.
<html>
<head>
<script>
function myFunction() {
var x = document.getElementById("name");
x.value = x.value.toLowerCase();
}
</script>
</head>
<body>
</body>
</html>
onchange : it triggers only when a user changes the content of input field.
<html>
<head>
<script>
function nameFunction() {
var x = document.getElementById("name");
x.value = x.value.toUpperCase();
}
</script>
</head>
<body>
</body>
</html>
onchange : it triggers only when a user selects dropdown values.
<html>
<head>
<script>
function preferedBrowser()
{
var prefer = document.forms[0].browsers.value;
alert("You prefer browsing internet with " + prefer);
}
</script>
</head>
<body>
<form>
Choose which browser you prefer:
<select id="browsers" onchange="preferedBrowser()">
<option value="Chrome">Chrome</option>
<option value="Internet Explorer">Internet Explorer</option>
<option value="Firefox">Firefox</option>
</select>
</form>
</body>
</html>
Onfocus : inputfield get focus when user clicks input field.
<html>
<head>
<script>
function myFunction(x) {
x.style.background = "yellow";
}
</script>
</head>
<body>
</body>
</html>
Onsubmit : when the user clicks submit button.
<html>
<head>
<script>
function confirmInput() {
fname = document.forms[0].name.value;
alert("Hello " + fname + "! You will now be redirected to www.google.com");
}
</script>
</head>
<body>
<form onsubmit="confirmInput()" action="http://www.google.com/">
Enter your name: <input id="name" type="text" size="20">
<input type="submit">
</form>
</body>
</html>
Onreset : when the user clicks reset button.
<html>
<head>
<script>
function message() {
alert("This alert box was triggered by the onreset event handler");
}
</script>
</head>
<body>
<form onreset="message()">
Enter your name: <input type="text" size="20">
<input type="reset">
</form>
</body>
</html>
Onkeydown/onkeypress : it trriggers only when user pressing or holding
key.
<html>
<head>
<script>
function myFunction() {
alert("You pressed a key inside the input field");
}
</script>
</head>
<body>
<p>A function is triggered when the user is pressing a key in the input field.</p>
</body>
</html>
Onkeyup : it triggers when user releases a key.
<html>
<head>
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</head>
<body>
<p>A function is triggered when the user releases a key in the input field. The
function transforms the character to upper case.</p>
Enter your name: <input type="text" id="fname" onkeyup="myFunction()">
</body>
</html>
Onkeyup and onkeydown both
<html>
<head>
<script>
function color(color) {
document.forms[0].myInput.style.background = color;
}
</script>
</head>
<body>
<form>
Write a message:<br>
<input type="text" onkeydown="color('yellow')“ onkeyup="color('green')"
name="myInput">
</form>
</body>
</html>
Mouse Events
Onmouseover/onmouseout : it triggers when mouse
passes over an element.
<html>
<body>
</body>
</html>
Onmousedown/onmouseup : it triggers when pressing a mouse button.
<html>
<head>
<script>
function myFunction(elmnt, clr) {
elmnt.style.color = clr;
}
</script>
</head>
<body>
Click the text to change the color. A function, with parameters, is triggered when the mouse
button is pressed down, and again, with other parameters, when the mouse button is
released.
</p>
</body>
</html>
Load Events
Onload: it triggers when page loaded.
<html>
<head>
<script>
function myFunction() {
alert("Page is loaded");
}
</script>
</head>
<body onload="myFunction()">
<h1>Hello World!</h1>
</body>
</html>
<html>
<head>
<script>
function loadImage() {
alert("Image is loaded");
}
</script>
</head>
<body>
</body>
</html>
Onerror : error occurs when image loads, liking of pages etc
<html>
<head>
<script>
function imgError() {
alert('The image could not be loaded.');
}
</script>
</head>
<body>
</body>
</html>
Onresize : error occurs when browser window resize.
<html>
<head>
<script>
function myFunction() {
var w = window.outerWidth;
var h = window.outerHeight;
var txt = "Window size: width=" + w + ", height=" + h;
document.getElementById("demo").innerHTML = txt;
}
</script>
</head>
<body onresize="myFunction()">
</body>
</html>
Window screenX and screenY Properties
<html>
<head>
<script>
function myFunction() {
var myWindow = window.open("", "myWin", "left=700, top=350, width=200,
height=100");
myWindow.document.write("<p>This is 'myWin'");
myWindow.document.write("<br>ScreenX: " + myWindow.screenX);
myWindow.document.write("<br>ScreenY: " + myWindow.screenY + "</p>");
}
</script>
</head>
<body>
</body>
</html>
Window setTimeout() Method
The setTimeout() method calls a function or evaluates an
expression after a specified number of milliseconds.
• 1000 ms = 1 second.
• The function is only executed once. If you need to repeat
execution, use the setInterval() method.
• Use the clearTimeout() method to prevent the function
from running.
Syntax
setTimeout(function,milliseconds,param1,param2,...)
<html>
<body>
<script>
function timedText() {
var x = document.getElementById("txt");
setTimeout(function(){ x.value="2 seconds" }, 2000);
setTimeout(function(){ x.value="4 seconds" }, 4000);
setTimeout(function(){ x.value="6 seconds" }, 6000);
}
</script>
</body>
</html>
<html>
<body>
<script>
function openWin() {
myWindow.document.write("<p>This is 'myWindow'</p>");
</script>
</body>
</html>
Auto Refresh
<html>
<head>
<script type="text/JavaScript">
<!--
function AutoRefresh( t ) {
setTimeout("location.reload(true);", t);
}
// -->
</script>
</head>
<body onload="JavaScript:AutoRefresh(4000);">
<p>This page will refresh every 4 seconds.</p>
</body>
</html>
CONFORMATION BOX
<html>
<head>
<script type="text/javascript">
<!--
function Confirmation(){
var retVal = confirm("Do you want to continue ?");
if( retVal == true ){
document.write ("User wants to continue!");
return true;
}
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="Confirmation();" />
</form>
</body>
</html>
PROMPT DIALOG BOX
<html>
<head>
<script type="text/javascript">
<!--
function getValue(){
var retVal = prompt("Enter your name : ", "your name here");
document.write("You have entered : " + retVal);
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="getValue();" />
</form>
</body>
</html>
VOID
<html>
<head>
<script type="text/javascript">
<!--
function getValue(){
var a,b,c;
a = void ( b = 5, c = 7 );
document.write('a = ' + a + ' b = ' + b +' c = ' + c );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="getValue();" />
</body>
</html>
PAGE PRINTING
<head>
<script type="text/javascript">
<!--
//-->
</script>
</head>
<body>
<form>
<input type="button" value="Print" onclick="window.print()" />
</form>
</body>
Page Re-direct
<html>
<head>
<script type="text/javascript">
<!--
function Redirect() {
window.location="http://www.google.com";
}
//-->
</script>
</head>
<body>
<p>Click the following button, you will be redirected to home page.</p>
<form>
<input type="button" value="Redirect Me" onclick="Redirect();" />
</form>
</body>
</html>
<html>
<head>
<script type="text/javascript">
<!--
function Redirect() {
window.location="http://www.google.com";
}
</head>
<body>
</body>
</html>
JavaScript Objects
• A javaScript object is an entity having state
and behavior (properties and method).
• For example: car, pen, bike, chair, glass,
keyboard, monitor etc.
• JavaScript is an object-based language.
• Everything is an object in JavaScript.
• JavaScript is template based not class based.
• Here, we don't create class to get the object.
But, we direct create objects.
Creating Objects in JavaScript
• By object literal
• By creating instance of Object directly (using
new keyword)
• By using an object constructor (using new
keyword)
JavaScript Object by object literal
Syntax
object={property1:value1,property2:value2.....propertyN:valueN}
• property and value is separated by : (colon).
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
By using an Object constructor
• The this keyword refers to the current object.
• The example of creating object by object constructor is given
below.
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
• But before defining method, we need to add property in the function with same name as method.
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
this.changeSalary=changeSalary;
function changeSalary(otherSalary){
this.salary=otherSalary;
}
}
• By array literal
• By creating instance of Array directly (using new
keyword)
• By using an Array constructor (using new keyword)
JavaScript array literal
Syntax
var arrayname=[value1,value2.....valueN];
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
JavaScript Array directly (new keyword)
Syntax
var arrayname=new Array();
• new keyword is used to create instance of array.
Example of creating array directly.
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
JavaScript array constructor (new
keyword)
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
JavaScript String
• The JavaScript string is an object that represents
a sequence of characters.
• By string literal
• By string object (using new keyword)
By string literal
• The string literal is created using double quotes.
• The syntax of creating string using string literal is
given below:
var stringname="string value";
• Simple example of creating string literal.
<script>
var str="This is string literal";
document.write(str);
</script>
By string object (using new keyword)
Syntax
var stringname=new String("string literal");
• charAt(index)
• concat(str)
• indexOf(str)
• lastIndexOf(str)
• toLowerCase()
• toUpperCase()
• slice(beginIndex, endIndex)
• trim()
JavaScript String charAt(index) Method
var n=s1.indexOf("from");
document.write(n);
</script>
JavaScript String lastIndexOf(str) Method
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
setTimeout(function(){getTime()},1000);
}
//setInterval("getTime()",1000);//another way
function checkTime(i){
if (i<10){
i="0" + i;
}
return i;
}
</script>
JavaScript Math Object
• The JavaScript math object provides several
constants and methods to perform mathematical
operation.
• Unlike date object, it doesn't have constructors.
Math.sqrt(n)
• The JavaScript math.sqrt(n) method returns the
square root of the given number.
Example
Square Root of 17 is: <span id="p1"></span>
<script>
document.getElementById('p1').innerHTML=Math.sqrt(17);
</script>
output:
• Square Root of 17 is: 4.123105625617661
Math.random()
• The JavaScript math.random() method returns
the random number between 0 to 1.
Example
Random Number is: <span id="p2"></span>
<script>
document.getElementById('p2').innerHTML=Math.random();
</script>
Output:
• Random Number is: 0.5215753003356656
Math.pow(m,n)
• The JavaScript math.pow(m,n) method returns
the m to the power of n that is mn.
Example
3 to the power of 4 is: <span id="p3"></span>
<script>
document.getElementById('p3').innerHTML=Math.pow(3,4);
</script>
Output:
3 to the power of 4 is: 81
Math.floor(n)
• The JavaScript math.floor(n) method returns the lowest
integer for the given number.
• For example 3 for 3.7, 5 for 5.9 etc.
Example
Floor of 4.6 is: <span id="p4"></span>
<script>
document.getElementById('p4').innerHTML=Math.floor(4.6);
</script>
Output:
• Floor of 4.6 is: 4
Math.ceil(n)
• The JavaScript math.ceil(n) method returns the
largest integer for the given number.
• For example 4 for 3.7, 6 for 5.9 etc.
Example
Ceil of 4.6 is: <span id="a"></span>
<script>
document.getElementById("a").innerHTML=Math.ceil(4.6);
</script>
Output:
• Ceil of 4.6 is: 5
Math.round(n)
• The JavaScript math.round(n) method returns the rounded integer
nearest for the given number. If fractional part is equal or greater
than 0.5, it goes to upper value 1 otherwise lower value 0.
• For example 4 for 3.7, 3 for 3.3, 6 for 5.9 etc.
Example
Round of 4.3 is: <span id="p6"></span><br>
Round of 4.7 is: <span id="p7"></span>
<script>
document.getElementById('p6').innerHTML=Math.round(4.3);
document.getElementById('p7').innerHTML=Math.round(4.7);
</script>
Output:
• Round of 4.3 is: 4
Round of 4.7 is: 5
Math.abs(n)
• The JavaScript math.abs(n) method returns the
absolute value for the given number.
• For example 4 for -4, 6.6 for -6.6 etc.
Example
Absolute value of -4 is: <span id="p8"></span>
<script>
document.getElementById('p8').innerHTML=Math.abs(-4);
</script>
Output:
• Absolute value of -4 is: 4
Math Methods
JavaScript Number Object
• The JavaScript number object enables you to represent a numeric
value. It may be integer or floating-point.
• JavaScript number object follows IEEE standard to represent the
floating-point numbers.
• By the help of Number() constructor, you can create number object in
JavaScript. For example:
var n=new Number(value);
• If value can't be converted to number, it returns NaN(Not a Number) that
can be checked by isNaN() method.
For example:
• var x=102;//integer value
• var y=102.7;//floating point value
• var z=13e4;//exponent value, output: 130000
• var n=new Number(16);//integer value by number object
JavaScript Number Constants
JavaScript Number Methods
JavaScript Boolean
• JavaScript Boolean is an object that represents value in
two states: true or false.
• We can create the JavaScript Boolean object by Boolean()
constructor as given below.
Boolean b=new Boolean(value);
• The default value of JavaScript Boolean object is false.
JavaScript Boolean Example
<script>
document.write(10<20);//true
document.write(10<5);//false
</script>
JavaScript Boolean Properties
Output:
'bits' appears in
position 3
Character and Character-Class Patterns
\|()[]{}^$*+?.
Character and Character-Class Patterns
The following examples show patterns that use predefined character classes:
Character and Character-Class Patterns
➢ /x*y+z?/ pattern matches == > • strings that begin with any number of x’s
(including zero), followed by one or
more y’s, possibly followed by z:
Character and Character-Class Patterns
• \b (boundary), which matches the boundary position between a word character (\w)
and a nonword character (\W), in either order.
➢ /pearl/g pattern matches == > • Perform a global match (find all matches)
Pattern Modifiers
• Modifiers can be attached to patterns to change how they are used,
• The modifiers are specified as letters just after the right delimiter of the pattern.
➢ /pearl/g pattern matches == > • Perform a global match (find all matches)
Other Pattern-Matching Methods of String
• The replace method is used to replace substrings of the String object that match the
given pattern.
• The replace method takes two parameters: the pattern and the replacement string.
• The g modifier can be attached to the pattern if the replacement is to be global in the
string, in which case the replacement is done for every match in the string.
• The split method of String splits its object string into substrings on the basis of a given
string or pattern.
• The substrings are returned in an array.
Other Pattern-Matching Methods of String
Write a function in javascript : that Uses pattern matching to check a given string that is
supposed to contain a phone number. In a form
777-4567
777-111-1234
Document Object Model :
• DOM is an Application Programming Interface (API) that defines an
interface between HTML documents and application programs.
• Documents in the DOM have a treelike structure, but there can be more
than one tree in a document (although that is unusual).
• Because the DOM is an abstract interface, it does not dictate that
documents be implemented as trees or collections of trees.
• JavaScript binding to the DOM, the elements of a document are
objects, with both data and operations.
• The data are called properties, and the operations are, naturally,
called methods.
For example, the following :
• HTML element would be represented as an object with two
properties, type and name, with the values "text" and "address",
respectively:
<input type = "text" name = "address">
• In most cases, the property names in JavaScript are the same as their
corresponding attribute names in HTML.
Events and Event Handling:
• Event: a notification that something specific occurred --
by browser or user.
• Event handler: a script implicitly executed in response to
event occurrence.
• Event-driven: code executed resulting to user or browser
action.
• Registration: the process of connecting event handler to
event.
• Events are JavaScript objects --> names are case sensitive, all use
lowercase only.
(Method write should never be used in event handler. May cause
document to be written over.)
• JavaScript events associated with HTML tag attributes which can be
28
• JavaScript's interaction with HTML is handled through events that occur
when the user or the browser manipulates a page.
First Way :
• event model. One of these is by assigning the event handler script to an event tag
attribute, as in the following example:
<input type = "button" id = "myButton“ onclick = "alert('You clicked the button!');" />
• An event handler function could also be registered by assigning its name to the
associated event property on the button object, as in the following example:
• document.getElementById("myButton").onclick =myButtonHandler;
• This statement must follow both the handler function and the form element so
that JavaScript has seen both before assigning the property.
• The name of the handler function is assigned to the property—it is neither a
string nor a call to the function.
• Third way is via addevent listener
Third way is ADDEVENTLISTENER
38
Event handler
example [WE CAN REGISTER AN EVENT BY USING ON[EVENT] -EG: ONCLICK OR ADDEVENTLISTENER
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>This example uses the addEventListener() method to attach a click event to a button.</p>
<button id="myBtn" onclick=”displayDate();” >Try it</button>
<input type=“radio” id =“rdclk” name=“dept” value=“1” onclick=“deptchoice();”> CSE
<p id="demo"></p>
<script>
//document.getElementById("myBtn").onclick=displayDate;
document.getElementById("myBtn").addEventListener("click", displayDate);
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
</body>
</html>
Event handler
43
<!DOCTYPE html>
<html lang = "en">
<head>
<title> nochange.html </title>
<meta charset = "utf-8" />
<script type = "text/javascript" src = "nochange.js" >
</script>
<style type = "text/css"> td, th, table {border: thin solid black}
</style>
</head>
<body>
<form action = "">
<h3> Coffee Order Form </h3>
<!-- A bordered table for item orders -->
<table>
<!-- First, the column headings --> <tr>
<tr> <th> Colombian (1 lb.) </th>
<th> Product Name </th> <td> $4.59 </td>
<th> Price </th> <td> <input type = "text" id = "colombian“ size = "2"
<th> Quantity </th> /></td>
</tr> </tr>
<!-- Now, the table data entries --> </table>
<tr> <!-- Button for precomputation of the total cost -->
<th> French Vanilla (1 lb.) </th>
<td> $3.49 </td>
<td> <input type = "text" id = "french“ size ="2" /> </td>
</tr>
<tr>
<th> Hazlenut Cream (1 lb.) </th>
<td> $3.95 </td>
<td> <input type = "text" id = "hazlenut“ size = "2" /> </td>
</tr>
<p>
<input type = "button" value = "Total Cost“ onclick =
"computeCost();" />
<input type = "text" size = "5" id = "cost“ onfocus = "this.blur();"
/>
</p>
<!-- The submit and reset buttons -->
<p>
<input type = "submit" value = "Submit Order" />
<input type = "reset" value = "Clear Order Form" />
</p>
</form>
</body>
nochange.js:
function computeCost() {
var french = document.getElementById("french").value;
var hazlenut =
document.getElementById("hazlenut").value;
var colombian =
document.getElementById("colombian").value;
document.getElementById("cost").value =
totalCost = french * 3.49 + hazlenut * 3.95
+colombian * 4.59;
}
Example on password validation
<!DOCTYPE html> <form id = "myForm" action = "" >
<!-- pswd_chk.html <p>
A document for pswd_chk.ps <label> Your password
Creates two text boxes for passwords <input type = "password" id = "initial“ size = "10"
--> />
</label>
<html lang = "en">
<head> <br /><br />
<title> Illustrate password checking> <label> Verify password
</title>
<input type = "password" id = "second“ size =
<meta charset = "utf-8" />
<script type = "text/javascript" src "10" />
= "pswd_chk.js" > </label>
</script>
</head> <br /><br />
<input type = "reset" name = "reset" />
<body> <input type = "submit" name = "submit" />
<h3> Password Input </h3> </p>
Validating Form Input
// pswd_chk.js
// An example of input password checking using the submit event
// The event handler function for password checking
function chkPasswords() {
var init = document.getElementById("initial");
var sec = document.getElementById("second");
if (init.value == "") {
alert("You did not enter a password \n" + "Please enter one now");
return false;
}
if (init.value != sec.value) {
alert("The two passwords you entered are not the same \n" +"Please re-enter both
now");
return false;
} else
pswd_chkr.js
// Register the event handlers for pswd_chk.html
document.getElementById("second").onblur =chkPasswords;
document.getElementById("myForm").onsubmit =
chkPasswords;
• This figure shows a browser display of
pswd_chk.html after the two password
elements have been input but before Submit
Query has been clicked.
onClick = "myHandler();
1. Assigning them to properties of JavaScript object associated with HTML elements.
• The load event: the completion of loading of a document by browser
• The onload attribute of <body> used to specify event handler:
• The unload event: used to clean up things before a document is unloaded.
56
Example:onclick
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function sayHello(){}
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello" />
</form>
</body>
</html>
57
onSubmit Event Type:
function validate(){
if ((document.example2.naming.value=="") ||
(document.example2.feed.value=="")){
alert("You must fill in all of the required fields!")
return false
} <form name="example2" onsubmit="return validate()">
else
return true <input type="text" size="20" name="naming">
} <strong>Feedback please: (*required)</strong>
<textarea name="feed" rows="3" cols="25"></textarea>
</script> <strong>Your home address (*NOT required)</strong>
<input type="text" size="35" name="address">
<html>
<head>
<script type="text/javascript">
function validate()
</script>
</head>
<body>
.......
</form>
</body>
</html>
onmouseover and
onmouseout :
• These two event types will help you create nice effects with images or
even with text as well.
• The onmouseover event triggers when you bring your
mouse over any element and the onmouseout triggers
when you move your mouse out from that element.
• Try the following example.
63
<html>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover="over()" onmouseout="out()">
<h2 id="l1"> This is inside the division </h2>
</div>
<script >
function over()
{
document.getElementById("l1").innerHTML="Welcome ABC";
}
function out()
{
document.getElementById("l1").innerHTML="";
}
</script>
</body>
</html>
64
Focus & Blur Event Example:
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
</head>
<body>
<h1>Hello How Are You...?</h1>
<form>
Click This Button<br/>
<input type="button" value="Click Me!"
onclick="myFun()"/><br/>
<input type="text" id="username" onfocus="this.blur()"/><br/>
</form> [fig.1 Before Click On That Button]
<script type="text/javascript">
function myFun()
{
document.getElementById("username").value="Dhruv";
}
</script>
</body>
</html>
66
The addEventListener() method attaches an event handler to the specified element.
The addEventListener() method attaches an event handler to an element without overwriting existing event
handlers.
You can add many event handlers of the same type to one element, i.e two "click" events.
You can add event listeners to any DOM object not only HTML elements. i.e the window object.
The addEventListener() method makes it easier to control how the event reacts to bubbling.
When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better
readability and allows you to add event listeners even when you do not control the HTML markup.
You can easily remove an event listener by using the removeEventListener() method.
Syntax
68
removeEventListener:
69
Syntax
target.removeEventListener(type, listener[, options]);
target.removeEventListener(type, listener[,
useCapture]);
70
<!DOCTYPE html>
<html>
<head><title>Display Page</title></head> An Example of onclick
<body>
<hr color="orange" />
<center><h1 id="htag">Welcome To ADIT</h1></center>
<hr color="blue" />
<center><button type="button" onclick="Change()">Change</button>
<button type="button" onclick="Hide()">Hide</button>
<button type="button" onclick="Display()">Display</button>
<button type="button" onclick="ChangeColor()">Color Change</button></center>
<hr color="green" />
<script type="text/javascript">
function Change()
{ document.getElementById("htag").innerHTML="Welcome ABC"; }
function Display()
{ document.getElementById("htag").style.display="block"; }
function Hide()
{ document.getElementById("htag").style.display="none"; }
function ChangeColor()
{ document.getElementById("htag").style.color="blue"; }
</script>
</body>
</html>
71
Event handler example
revise :Event handler example [WE CAN
REGISTER AN EVENT BY USING ON[EVENT]
EG ONCLICK OR ADDEVENTLISTENER
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>This example uses the addEventListener() method to attach a click event to a button.</p>
//document.getElementById("myBtn").onclick=displayDate;
document.getElementById("myBtn").addEventListener("click", displayDate);
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
</body>
</html>
using addEventListeneter calling two
functions on the element
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>This example uses the addEventListener() method to add two click events to the same button.</p>
<button id="myBtn">Try it</button>
<script>
var x = document.getElementById("myBtn");
x.addEventListener("click", myFunction);
x.addEventListener("click", someOtherFunction);
function myFunction() {
alert ("Hello World!");
}
function someOtherFunction() {
alert ("This function was also executed!");
}
</script>
</body>
addEventListener and removeEventListener
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
background-color: coral;
border: 1px solid;
padding: 50px;
color: white;
font-size: 20px;
}
</style>
</head>
<body>
<h2>JavaScript removeEventListener()</h2>
addEventListener and removeEventListener
<div id="myDIV">
<p>This div element has an onmousemove event handler that displays a random number every time you move your mouse
inside this orange field.</p>
<p>Click the button to remove the div's event handler.</p>
<button onclick="removeHandler()" id="myBtn">Remove</button>
</div>
<p id="demo"></p>
<script>
document.getElementById("myDIV").addEventListener("mousemove", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = Math.random();
}
function removeHandler() {
document.getElementById("myDIV").removeEventListener("mousemove", myFunction);
}
</script>
</body>
</html>
Focus and blur on EventListener
<!DOCTYPE html>
<html>
<body>
<p>When you enter the input field (child of FORM), a function is triggered which sets the background color to yellow. When you leave the
input field, a function is triggered which removes the background color.</p>
<form id="myForm">
<input type="text" id="myInput">
</form>
<script>
var x = document.getElementById("myForm");
x.addEventListener("focus", myFocusFunction, true);
x.addEventListener("blur", myBlurFunction, true);
function myFocusFunction() {
document.getElementById("myInput").style.backgroundColor = "yellow";
}
function myBlurFunction() {
document.getElementById("myInput").style.backgroundColor = "";
}
</script>
</body>
Output
addEventListener on window object
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>This example uses the addEventListener() method on the window object.</p>
<p>Try resizing this browser window to trigger the "resize" event handler.</p>
<p id="demo"></p>
<script>
window.addEventListener("resize", function(){
document.getElementById("demo").innerHTML = Math.random();
});
</script>
</body>
</html>