Search code examples
jqueryjquery-uijquery-ui-draggablejquery-ui-droppable

How to create event handlers dynamically in jquery


I have a draggable table for which I'm trying to drag a tr and I want to drop it to one of the droppable tables. The code is working as expected but I want to make this code dynamic. How can it be possible? Here is my code

jQuery('#pipeline_lead_card_table_1').droppable({ 
   tolerance: 'pointer',
   drop: function(event, ui) {   
    jQuery('#pipeline_lead_card_table_1 .pipeline_lead_card_table      
    tbody').append(ui.helper.children());
  }
}); 

jQuery('#pipeline_lead_card_table_2').droppable({ 
  tolerance: 'pointer',
  drop: function(event, ui) {   
    jQuery('#pipeline_lead_card_table_2 .pipeline_lead_card_table    
    tbody').append(ui.helper.children());
  }
}); 

jQuery('#pipeline_lead_card_table_3').droppable({ 
  tolerance: 'pointer',
  drop: function(event, ui) {   
    jQuery('#pipeline_lead_card_table_3 .pipeline_lead_card_table 
      body').append(ui.helper.children());
     }
  }); 

 jQuery('#pipeline_lead_card_table_4').droppable({ 
   tolerance: 'pointer',
   drop: function(event, ui) {   
     jQuery('#pipeline_lead_card_table_4 .pipeline_lead_card_table     
       tbody').append(ui.helper.children());
      }
  }); 

What I want to make this code dynamic as I don't know how many tables will be generated dynamically.


Solution

  • Expanding upon my comment, you could simplify the code like so:

    (function($) {
    
      function makeDrop($o) {
        $o.droppable({
          tolorance: "pointer",
          drop: function(e, ui) {
            $(".pipeline_lead_card_table tbody", this).append(ui.helper.children());
          }
        });
      }
    
      makeDrop($('#pipeline_lead_card_table_1'));
      makeDrop($('#pipeline_lead_card_table_2'));
      makeDrop($('#pipeline_lead_card_table_3'));
      makeDrop($('#pipeline_lead_card_table_4'));
    })(jQuery);
    

    No, if each of your tables has a Class attribute, E.G.: can-change, you could simplify the code even further:

    (function($) {
    
      function makeDrop($o) {
        $o.droppable({
          tolorance: "pointer",
          drop: function(e, ui) {
            $(".pipeline_lead_card_table tbody", this).append(ui.helper.children());
          }
        });
      }
    
      makeDrop($('.can-change'));
    })(jQuery);