Prototype event has several methods these methods are supported in latest version of prototype.js i.e version 1.6 and following are some event methods are explained.
Element()
Which is used to returns the DOM element when the event get occurred The syntax of the DOM element as shown below.
[code]
Event.element();
[/code]
The code below demonstrates click anywhere on the page if user clicks directly on paragraphs then which hides them as shown below.
[html]
<html>
<head>
<title>Prototype examples</title>
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script>
Event.observe(document, 'click', respondToClick);
function respondToClick(event) {
var element = event.element();
alert("Tag Name : " + element.tagName );
if ('P' == element.tagName) {
element.hide();
}
}
</script>
</head>
<body>
<p id = "note"> Click on any part to see the result.</p>
<p id = "para">This is paragraph</p>
<div id = "division">This is divsion.</div>
</body>
</html>
[/html]
Result
By running the above code in a preferred browser user can get the following output as shown in below image.
Observe()
In order to register a function in an event handler then if user need to observe the element already exist in the DOM. The syntax of the observe() as shown below.
[code]
Event.observe(element,eventName,handler[,useCapture=false]);
[/code]
In the above syntax parameters are explained below.
- Element
Which is the DOM element user want to observe in prototype element can be an actual DOM reference or ID string for the element.
- eventName
As per the DOM level standard standardized event name supported by the browser.
- Handler
Which is an handler function which can be anonymous function create on-the-fly.
- Usecapture
User can request for capturing instead of bubbling.
The code below demonstrates to observe the click event and which takes action occurs when ever action occurs.
[html]
<html>
<head>
<title>Prototype examples</title>
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script>
// Register event 'click' and associated call back.
Event.observe(document, 'click', respondToClick);
// Callback function to handle the event.
function respondToClick(event) {
alert("You pressed the button...." );
}
</script>
</head>
<body>
<p id = "note"> Click anywhere to see the result.</p>
<p id = "para1">This is paragraph 1</p>
<p id = "para2">This is paragraph 2</p>
<div id = "division">This is divsion.</div>
</body>
</html>
[/html]
Result
By running the above code in a preferred browser user can get the following output as shown in below image.