Tuesday, August 5, 2014

jQuery Advanced Event Handling

Event handler remove, attach and event stop propagation.




<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="utf-8">
  <title>Working with events</title>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script>
   $(document).ready(function() {
    var myHandleFunc = function(e) {
     alert('Before `stopPropagation()`');
     e.stopPropagation();
     alert('After `stopPropagation()`');     
    };
    
    $('p').click(myHandleFunc);
  
    $('div.chapter').click(function() {
     alert('I\'m not executed unless you click on yellow or remove event handler for p element');
    });
    
    $('#remove').click(function() {
     $('p').off('click');
    });  
    
    $('#attach').click(function() {
     $('p').on('click', myHandleFunc);
    });              
   });
  </script>
 </head>
 <body>
  <div id="container">
   <div>
    <h2>Click on paragraph <button id="remove">Remove event</button> <button id="attach">Attach event</button></h2>
   </div>
   <div style="padding: 50px;background: yellow;"  class="chapter">
    <p style="background: white;">
     Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </p>
   </div>
  </div>
 </body>
</html>

No comments:

Post a Comment