Prototype - Event observe() Method


Advertisements


This method registers an event handler on a DOM element.

To register a function as an event handler, the DOM element that you want to observe must already exist in the DOM.

Syntax

Event.observe(element,eventName,handler[,useCapture=false]);

Here are the explanations about the passed parameters −

  • element − The DOM element you want to observe; as always in Prototype, this can be either an actual DOM reference, or the ID string for the element.

  • evenetName − The standardized event name, as per the DOM level supported by your browser. This includes click, mousedown, mouseup, mouseover, mousemove and mouseout.

  • handler − This is the event handler function. This can be an anonymous function you create on-the-fly.

  • useCapture − Optionally, you can request capturing instead of bubbling. The details are in the http://www.w3.org/TR/DOM-Level-2Events/events.html.

Return Value

NA.

Example

Here is an example, which observe click event and take an action whenever a click event occurs.

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

Output


prototype_event_handling.htm

Advertisements