Delegate Function in JavaScript

Introduction

 
There is only a single listener for all of the above buttons. It is a delegate(), called on the parent element.
 
When the event occurs, 'this' refers to the object on which the event occurred.
 
In Head Section
  1. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>  
  2. <script type="application/x-javascript">  
  3. $(function() {  
  4.     $("#container").delegate("button""click"function(index) {  
  5.         paneToShow = "#" + $(this).text();  
  6.         $(".content-pane").hide();  
  7.         $(paneToShow).show();  
  8.     });  
  9. });  
  10. </script>  
  11. <style type="text/css">  
  12. .content-pane {  
  13.     display: none;  
  14.     padding: 5px;  
  15.     border: 2px solid #000;  
  16. }  
  17. </style> 
In body Section
  1. <div id="container">  
  2.     <h1>Click any button below...</h1>  
  3.     <button id="first">First</button>  
  4.     <button id="second">Second</button>  
  5.     <button id="third">Third</button>  
  6.     <button id="fourth">Fourth</button>  
  7.     <div id="First" class="content-pane">  
  8.         <h1>You clicked First Pane...</h1>  
  9.     </div>  
  10.     <div id="Second" class="content-pane">  
  11.         <h1>You clicked Second Pane...</h1>  
  12.     </div>  
  13.     <div id="Third" class="content-pane">  
  14.         <h1>You clicked Third Pane...</h1>  
  15.     </div>  
  16.     <div id="Fourth" class="content-pane">  
  17.         <h1>You clicked Fourth Pane...</h1>  
  18.     </div>  
  19. </div> 
Description
 
When the event occurs, 'this' refers to the object on which the event occurred. The advantage of this approach is that there is a single listener, which means less memory being consumed. I can still add listeners to the individual buttons, should the need arise. The downside is figuring how to get information on the clicked element. Fortunately, jQuery assigns 'this' to the clicked element, so we can use $(this) and treat it as a normal DOM element.