Search code examples
javascriptjquerycssjquery-ui-draggablejquery-ui-droppable

Change color of item being dropped in list after item is dropped


I want to change color of the item after it dragged and dropped into droppable field. How it can be done? Here is fiddle i have. So as I said i want to color of dropped item to be changed when its dropped. And javascript code:

$(function() {
  var x = $(".addtofavs li").length;
  var y = $(".addtoquicklinks li").length;
  $("#atf-count").text(x);
  $("#atq-count").text(y);
  $("#catalog ").accordion({
    heightStyle: "content",
    active: false,
    collapsible: true
  });
  $("#myAccordion li").draggable({
    connectToSortable: '.container',
    helper: 'clone',
    revertDuration: 0,
    create: function() {
      var eq = $(this).index();
      $(this).attr('data-index', eq);
    }
  });

  $(".container").sortable({
    connectWith: '.container',
    placeholder: "ui-state-highlight",
    receive: function(event, ui) {
      var uiIndex = ui.item.attr('data-index');
      var item = $(this).find('[data-index=' + uiIndex + ']');
      if (item.length > 1) {
        item.last().remove();
      }
    },
    revert: true
  });

  $(".container li").draggable({
    connectToSortable: '.container',
    placeholder: "ui-state-highlight",
    revert: true
  });
});

Solution

  • You can get the element that is drop to your container on receive event of sortable by ui.item and the change color for it.

    Try this

    $(".container").sortable({
            connectWith: '.container',
            placeholder: "ui-state-highlight",
            receive: function(event, ui) {
              var uiIndex = ui.item.attr('data-index');
              var item = $(this).find('[data-index=' + uiIndex + ']');
              if (item.length > 1) {
                item.last().remove();
              }
              $(ui.item).css("background", "red");
            },
            revert: true
          });
    

    Here is working fiddle https://jsfiddle.net/cqLv5n64/2/