Search code examples
jquerylivedroppable

Jquery Droppable add live event


I have an li which is Drag and Drop and works when page is refreshed but when I add an li using AJAX in the list, the droppable event does not get attached to it. How to attach a live droppable event to that li.

Here what i've tried so far,

$('.main-menu.workspaces li').droppable({
  hoverClass: "ui-state-hover",
  tolerance: "pointer",
  accept: '.notification-item.subtask',
  drop: function (event, ui) {
    var workspace_id = $(event.target).data('workspace');
    var task_id = $(ui.draggable[0]).data('taskid');
    $.post('{{route('workspace.assign', $subdomain)}}', { 
      workspace: workspace_id, 
      task: task_id   
    }).done(function(data) {
    });
  }
});

Solution

  • Thanks to @Rory McCrossan for the suggestion and this is what i did and it worked.

    (function($){
          var options = {
              hoverClass: "ui-state-hover",
              tolerance: "pointer",
              accept: '.notification-item.subtask',
              drop: function (event, ui) {
              var workspace_id = $(event.target).data('workspace');
                  var task_id = $(ui.draggable[0]).data('taskid');
                  var href = $('.notification-body.todotask').attr('data-assignlink');
                  $.post(href,{workspace: workspace_id, task: task_id})
                  .done(function(data){
                       //todo
                   });
                 }
               }
    
           $('.main-menu.workspaces li').droppable(options);
    
    
           // Attaching li to DOM using AJAX
           function attachLi(){
               $.ajax({
               url: 'store',
               method: 'POST',
               data: {
               task: searchString,
               },
               success: function (response) {
                   //attaching li to DOM
                   $('.task').append(response.html);
    
                   //Reinitializing Droppable 
                   $('.main-menu.workspaces li').droppable(options);
               }
              });
           }
    
          ...
          .
          .
    })(jQuery);