Thursday 2 January 2014

Javascript : Events

What is an Event ?
Occurrence of an activity termed as Event
JavaScript's interaction with HTML is handled through events
that occur when the user or browser works on a page.

When the page loads,even occurs. When the user clicks a button,
that click, too, is an event, pressing any key,
closing window, re sizing window etc.

Events are a part of the Document Object Model (DOM) Level 3 and every
HTML element have a certain set of events which can trigger JavaScript Code.

onclick Event Type:
This is the most frequently used event type which occurs when a user
clicks mouse left button. You can put your validation, warning etc against this event type.

Example:

<html>
<head>
<script type="text/javascript">

function begin() {
   alert("Hello World")
}

</script>
</head>
<body>
<input type="button" onclick="begin()" value="welcome" />
</body>
</html>
This will produce following result and when you click Hello
button then onclick event will occur which will trigger begin() function.

onsubmit event type:
Another most important event type is onsubmit.
This event occurs when you try to submit a form.
So you can put your form validation against this event type.

Here is simple example showing its usage. 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.

Example:

<html>
<head>
<script type="text/javascript">

function validation() {
   do validation ...
   .........
   return either true or false
}

</script>
</head>
<body>
<form method="POST" action="check.aspx" onsubmit="return validate()">
.......
<input type="submit" value="Submit" />
</form>
</body>
</html>
onmouseover and onmouseout:
These two event types will help you to create nice effects with images
or even with text as well. The onmouseover event occurs when you bring your
mouse over any element and the onmouseout occurs when you take your mouse out from that element.

Example:

Following example shows how a division reacts when we bring our mouse in that division:

<html>
<head>
<script type="text/javascript">

function onOver() {
   alert("Mouse Over");
}
function Onout() {
   alert("Mouse Out");
}

</script>
</head>
<body>
<div onmouseover="Onover()" onmouseout="Onout()">
<h2> This is inside the division </h2>
</div>
</body>
</html>

Events and their description :
                                                                 

No comments:

Post a Comment