0% found this document useful (0 votes)
16 views

JAVASCRIPT_EVENTS

Uploaded by

grojamani
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

JAVASCRIPT_EVENTS

Uploaded by

grojamani
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Example: Program on Array Methods – POP() & PUSH()

<html>
<body>
<button onclick="arrpop();">POP</button>
<button onclick="arrpush();"> PUSH </button>
<script>
function arrpop()
{
var numbers = ["1", "2", "3", "4", "5", "ABC"];
document.write(numbers.pop()+" "+"Removed"+"<br>");
//pop() removes the last element of an array

// Now we have [1,2,3,4,5]


document.write("Now length is: "+numbers.length); // ABC
removed
}
function arrpush()
{
var numbers = ["1","2","3","4","5","6"]
numbers.push("7");
// now we got ["1","2","3","4","5","6"]
document.write("Added element
is :"+" "+numbers[numbers.length-1])
// Now we have [1,2,3,4,5,6]
document.write("<br>"+"Now length is: "+numbers.length); // 7
Added
}
</script>
</body>
</html>

Output:
JAVA SCRIPT EVENTS : Live Demo

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

Output

onsubmit Event Type


onsubmit is an event that occurs when you try to submit a form. You can put your form validation against
this event type.

Example
The following example shows how to use onsubmit. Here we are calling a validate() function before
submitting a form data to the webserver. If validate() function returns true, the form will be submitted,
otherwise it will not submit the data.
Try the following example.

<html>

<head>

<script type = "text/javascript">

<!--

function validation() {

all validation goes here

.........

return either true or false

//-->

</script>

</head>

<body>

<form method = "POST" action = "t.cgi" onsubmit = "return validate()">

.......

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

</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.
Live Demo

<html>

<head>

<script type = "text/javascript">

<!--

function over() {

document.write ("Mouse Over");

function out() {

document.write ("Mouse Out");

//-->

</script>

</head>

<body>

<p>Bring your mouse inside the division to see the result:</p>

<div onmouseover = "over()" onmouseout = "out()">

<h2> This is inside the division </h2>

</div>

</body>

</html>

Output
HTML 5 Standard Events
Event Handlers

Event Description
Handler
onAbort It executes when the user aborts loading an image.

onBlur It executes when the input focus leaves the field of a text, textarea or a select
option.

onChange It executes when the input focus exits the field after the user modifies its text.

onClick In this, a function is called when an object in a button is clicked, a link is


pushed, a checkbox is checked or an image map is selected. It can return false
to cancel the action.

onError It executes when an error occurs while loading a document or an image.

onFocus It executes when input focus enters the field by tabbing in or by clicking but not
selecting input from the field.

onLoad It executes when a window or image finishes loading.

onMouseOver The JavaScript code is called when the mouse is placed over a specific link or an
object.

onMouseOut The JavaScript code is called when the mouse leaves a specific link or an object.

onReset It executes when the user resets a form by clicking on the reset button.

onSelect It executes when the user selects some of the text within a text or textarea
field.

onSubmit It calls when the form is submitted.

onUnload It calls when a document is exited.

Example : Simple Program on onload() Event handler


<html>
<head>
<script type="text/javascript">
function time()
{
var d = new Date();
var ty = d.getHours() + ":"+d.getMinutes()+":"+d.getSeconds();
document.frmty.timetxt.value=ty;
setInterval("time()",1000)
}
</script>
</head>
<body onload="time()">
<center><h2>Displaying Time</h2>
<form name="frmty">
<input type=text name=timetxt size="8">
</form>
</center>
</body>
</html>

Output:

Example: Simple Program on onsubmit() & onfocus() Event


handler
<html>
<body>
<script>
function validateform()
{
var uname=document.myform.name.value;
var upassword=document.myform.password.value;
if (uname==null || uname=="")
{
alert("Name cannot be left blank");
return false;
}
else if(upassword.length<6)
{
alert("Password must be at least 6 characters long.");
return false;
}
}
function emailvalidation()
{
var a=document.myform.email.value
if (a.indexOf("@")==-1)
{
alert("Please enter valid email address")
document.myform.email.focus()
}
}
</script>
<body>
<form name="myform" method="post" action="validpage.html"
onsubmit="return validateform()">
Email: <input type="text" size="20" name="email"
onblur="emailvalidation()"><br>
User Name: <input type="text" name="name"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Submit" >
</form>
</body>
</html>

validpage.html //File name

<html>
<body>
<script type="text/javascript">
alert("You are a Valid User !!!");
</script>
</body>
</html>

Output:
Built-in Objects

 Built-in objects are not related to any Window or DOM object model.
 These objects are used for simple data processing in the JavaScript.

1. Math Object

 Math object is a built-in static object.


 It is used for performing complex math operations.
Math Properties

Math Property Description

SQRT2 Returns square root of 2.

PI Returns Π value.

E\ Returns Euler's Constant.

LN2 Returns natural logarithm of 2.

LN10 Returns natural logarithm of 10.

LOG2E Returns base 2 logarithm of E.

LOG10E Returns 10 logarithm of E.

Math Methods

Methods Description

abs() Returns the absolute value of a number.

acos() Returns the arccosine (in radians) of a number.

ceil() Returns the smallest integer greater than or equal to a number.


cos() Returns cosine of a number.

floor() Returns the largest integer less than or equal to a number.

log() Returns the natural logarithm (base E) of a number.

max() Returns the largest of zero or more numbers.

min() Returns the smallest of zero or more numbers.

pow() Returns base to the exponent power, that is base exponent.

Example: Simple Program on Math Object Methods

<html>
<head>
<title>JavaScript Math Object Methods</title>
</head>
<body>
<script type="text/javascript">

var value = Math.abs(20);


document.write("ABS Test Value : " + value +"<br>");

var value = Math.acos(-1);


document.write("ACOS Test Value : " + value +"<br>");

var value = Math.asin(1);


document.write("ASIN Test Value : " + value +"<br>");

var value = Math.atan(.5);


document.write("ATAN Test Value : " + value +"<br>");
</script>
</body>
</html>

Output

ABS Test Value : 20


ACOS Test Value : 3.141592653589793
ASIN Test Value : 1.5707963267948966
ATAN Test Value : 0.4636476090008061

Example: Simple Program on Math Object Properties

<html>
<head>
<title>JavaScript Math Object Properties</title>
</head>
<body>
<script type="text/javascript">
var value1 = Math.E
document.write("E Value is :" + value1 + "<br>");

var value2 = Math.LN2


document.write("LN2 Value is :" + value2 + "<br>");

var value3 = Math.LN10


document.write("LN10 Value is :" + value3 + "<br>");

var value4 = Math.PI


document.write("PI Value is :" + value4 + "<br>");
</script>
</body>
</html>

Output:
E Value is :2.718281828459045
LN2 Value is :0.6931471805599453
LN10 Value is :2.302585092994046
PI Value is :3.141592653589793

2. Date Object

 Date is a data type.


 Date object manipulates date and time.
 Date() constructor takes no arguments.
 Date object allows you to get and set the year, month, day, hour, minute,
second and millisecond fields.
Syntax:
var variable_name = new Date();

Example:
var current_date = new Date();

Date Methods

Methods Description

Date() Returns current date and time.

getDate() Returns the day of the month.

getDay() Returns the day of the week.

getFullYear() Returns the year.

getHours() Returns the hour.

getMinutes() Returns the minutes.

getSeconds() Returns the seconds.

getMilliseconds() Returns the milliseconds.

getTime() Returns the number of milliseconds since January 1, 1970 at 12:00 AM.
getTimezoneOffset() Returns the timezone offset in minutes for the current locale.

getMonth() Returns the month.

setDate() Sets the day of the month.

setFullYear() Sets the full year.

setHours() Sets the hours.

setMinutes() Sets the minutes.

setSeconds() Sets the seconds.

setMilliseconds() Sets the milliseconds.

setTime() Sets the number of milliseconds since January 1, 1970 at 12:00 AM.

setMonth() Sets the month.

toDateString() Returns the date portion of the Date as a human-readable string.

toLocaleString() Returns the Date object as a string.

toGMTString() Returns the Date object as a string in GMT timezone.

valueOf() Returns the primitive value of a Date object.

Example : JavaScript Date() Methods Program

<html>
<body>
<center>
<h2>Date Methods</h2>
<script type="text/javascript">
var d = new Date();
document.write("<b>Locale String:</b> " + d.toLocaleString()
+"<br>");
document.write("<b>Hours:</b> " + d.getHours()+"<br>");
document.write("<b>Day:</b> " + d.getDay()+"<br>");
document.write("<b>Month:</b> " + d.getMonth()+"<br>");
document.write("<b>FullYear:</b> " + d.getFullYear()+"<br>");
document.write("<b>Minutes:</b> " + d.getMinutes()+"<br>");
</script>
</center>
</body>
</html>

Output:

3. String Object

 String objects are used to work with text.


 It works with a series of characters.
Syntax:
var variable_name = new String(string);

Example:
var s = new String(string);

String Properties
Properties Description

length It returns the length of the string.

prototype It allows you to add properties and methods to an object.

constructor It returns the reference to the String function that created the object.

String Methods

Methods Description

charAt() It returns the character at the specified index.

charCodeAt() It returns the ASCII code of the character at the specified position.

concat() It combines the text of two strings and returns a new string.

indexOf() It returns the index within the calling String object.

match() It is used to match a regular expression against a string.

replace() It is used to replace the matched substring with a new substring.

search() It executes the search for a match between a regular expression.

slice() It extracts a session of a string and returns a new string.

split() It splits a string object into an array of strings by separating the string into the substr

toLowerCase() It returns the calling string value converted lower case.

toUpperCase() Returns the calling string value converted to uppercase.


Example : JavaScript String() Methods Program

<html>
<body>
<center>
<script type="text/javascript">
var str = "CareerRide Info";
var s = str.split();
document.write("<b>Char At:</b> " + str.charAt(1)+"<br>");
document.write("<b>CharCode At:</b> " +
str.charCodeAt(2)+"<br>");
document.write("<b>Index of:</b> " + str.indexOf("ide")+"<br>");
document.write("<b>Lower Case:</b> " + str.toLowerCase()
+"<br>");
document.write("<b>Upper Case:</b> " + str.toUpperCase()
+"<br>");
</script>
<center>
</body>
</html>

Output:

Introducing DOM

 Document Object Model (DOM) is a standard object model and


programming interface for HTML.
 It defines a standard for accessing documents.
 It is a World Wide Consortium standard.
 It is a platform and language-neutral interface that allows programs and scripts
to dynamically access and update the content, structure and style of a
document.

1. DOM Object
DOM Properties

Properties Description

Cookie It returns all name or value pairs of cookies in the document.

documentMode It returns the mode used by the browser to render the document.

Domain It returns the domain name of the server that loaded the document.

lastModified It returns the date and time of last modified document.

readyState It returns the status of the document.


Referrer It returns the URL of the document that loaded the current document.

Title It sets or returns the title of the document.

URL It returns the full URL of the document.

DOM Methods

Methods Description

close() It closes the output stream previously opened with document.open().

clear() It clears the document in a window.

getElementById() It accesses the first element with the specified ID.

getElementByName() It accesses all the elements with a specified name.

getElementByTagName() It accesses all elements with a specified tagname.

open() It opens an output stream to collect the output from document.write().

write() It writes output (JavaScript code) to a document.

writeln() Same as write(), but adds a newline character after each statement.

Example : Program on DOM() Methods

<html>
<head>
<script type="text/javascript">
function check()
{
var username = document.getElementById("uname");
var password = document.getElementById("pass");
if(username.value=="abc" && password.value=="123")
alert("Hello!!! You are successfully signed in");
else
alert("Invalid Username and Password!!!");
}
</script>
</head>
<body>
<h2>Login</h2>
Username:<input type = "text" id="uname"><br>
Password:<input type = "password" id="pass"><br>
<input type="button" onClick="check()" Value="Sign In">
</body>
</html>

Output:
2. Element Object
Element object contains references of all elements in a form.

Element Object Properties

Property Description

Id It sets and returns the Id of an element.

Value It returns the value of an element.

innerHTM It sets or returns the HTML contents of an element.


L If you want to access the text within a non <input> HTML element, then you have to use i
property instead of value.

Length It returns the number of entries in the element array.

tagName It returns the tagname of an element as a string in uppercase.


Example : Simple Program on Element Object

<html>
<head>
<script type="text/javascript">
function welcome()
{
var fname = document.getElementById('fname');
var buttxt = document.getElementById('buttxt');
buttxt.innerHTML = fname.value;
}
</script>
</head>
<body>
<p>Welcome <b id = 'buttxt'></b></p>
Your Name : <input type = "text" id="fname"><br>
<input type = "button" onClick="welcome()" value="Enter">
</body>
</html>

Output:

3. Anchor Object
 Anchor object represents an HTML hyperlink.
 It allows you to create a link to another document with the 'href' attribute.
 You can access an anchor by using getElementById() or by searching through
the anchors[ ] array of the Document object.
 You can add anchors to the anchors[ ] array but you cannot delete, replace or
modify them.
Anchor Object Properties

Property Description

Href It sets or returns the value of the href attribute of a link.

name It sets or returns the value of the name attribute of a link.

Example : Simple Program on Window Object

open_window.html //File name

<html>
<head>
<script type="text/javascript">
function openwindow()
{
window.open("welcome.html");
}
</script>
</head>
<body>
<form>
<input type="button" value="Open" onClick=window.alert()>
<input type="button" onClick="openwindow()" value="Open Window">
</form>
</body>
</html>

welcome.html //File name

<html>
<body>
<script type="text/javascript">
{
document.write("<b>Welcome to TutorialRide !!!</b>");
}
</script>
</body>
</html>

Output:


In the above JavaScript program, when you click on the 'Open Window', you will see the
'welcome.html' opened in another window.
 When you click on the 'Open' button, you will see the alert message box.

You might also like