Search code examples
jquery-uijquery-ui-droppable

jQuery UI different drop events, depending on droppable class


I have 2 different droppable classes. I want to perform different drop events (dropBar, dropTile) depending on which droppable class element was dropped on. Here is my code:

$(".droppable-tile").droppable({
      accept: '.draggable-task, .task, .daily-task',
      tolerance:  'pointer',
      hoverClass: "tile-draggable-hover",
      drop: dropTile 
    });
$(".droppable-bar").droppable({
      accept: '.draggable-task, .task, .daily-task',
      hoverClass: "tile-draggable-hover",
      tolerance:  'pointer',
      drop: dropBar
});

As you can see these 2 droppables are nearly identical, the only difference is the event drop. Is there a way to merge these droppable statements so as not to repeat the code? I need to add that in these ondrop functions I use event,ui, $(this) variables/keywords.


Solution

  • You can do it like this:

    $(".droppable-bar,.droppable-tile").droppable({
            accept: '.draggable-task, .task, .daily-task',
            hoverClass: "tile-draggable-hover",
            tolerance: 'pointer',
            drop: function (ev, ui) {
                // Check droppable element by class
                if ($(this).hasClass('droppable-tile')) {
                    // your droppable-tile code
                }
                else if ($(this).hasClass('droppable-bar')) {
                    // your droppable-bar code
                }
            },
    
        });
    

    Online output (jsfiddle)