Javascript DOM Event Handler Registration

Description

Javascript DOM Event Handler Registration

View in separate window

<html>
   <head>
      <title>Event Registration Models</title>
      <style type = "text/css">
         div { padding: 5px;
               margin: 10px;
               border: 3px solid #0000BB;
               width: 12em }
      </style>
      <script type = "text/javascript">
         // handle the onclick event regardless of how it was registered
         function handleEvent()/*w  ww  .  ja v a 2  s.c o m*/
         {
            console.log( "The event was successfully handled." );
         }

         // register the handler using the traditional model
         function registerHandler() 
         {
            let traditional = document.getElementById( "traditional" ); 
            traditional.onclick = handleEvent;
         }
      </script>
   </head>
   <body onload = "registerHandler()">
      <!-- The event handler is registered inline -->
      <div id = "inline" onclick = "handleEvent()">
         Inline registration model</div> 

      <!-- The event handler is registered by function registerHandler -->
      <div id = "traditional">Traditional registration model</div>
   </body>
</html>



PreviousNext

Related