tags:

views:

148

answers:

2

Hi,

I'm new to JQuery, so this is probably a very dumb question.

I've used JQuery to make the elements in a table draggable. I asked a question about how to make it faster, and the best response I had so far was to disable droppable for all the cells, and only enable them when something is being dragged.

Actually, for me, this makes a lot of sense as I only want to be able to drag a cell onto another cell in the same row. So I only need to apply droppable to the cells in the same row. So, I do this:

$(document).ready
(
  function()
  {
    $('.draggable_div').draggable
    (
      {
        addClasses: false,
        scroll: false,
        axis: 'x',
        start: function(event, ui)
        {
          $(this).css('background-color','#ddddff');
          var $cells = $(this).parent().parent().children();
          $cells.addClass("droppable_td");
        }
      }
    );

...

Firebug is telling me that I've successfully added the "draggable_td" class to the cells in the right row. But how do I make that trigger the change? The way I have the code set up at the moment, droppable is attached like this:

  $('.droppable_td').droppable
  (
    {
      addClasses: false,
      over: function(event, ui)
      {
        $(this).css('background-color', '#ccffcc');
      },
      out: function(event, ui)
      {
        $(this).css('background-color', null);
      },
      drop: function(event, ui)
      {

etc...

I know that code works, because if I put that class in the appropriate < td> elements in the HTML it all works (just very slowly).

In other words: If I have all cells droppable from the start, it works. How can I dynamically change a cell to make it droppable as a result of an event?

Thanks,

Ben

+2  A: 

Setup which cells are droppable inside your draggable's start event.

start: function(event, ui)
{
  $(this).css('background-color','#ddddff');
  var $cells = $(this).parent().parent().children();
  $cells.addClass("droppable_td");
  $cells.droppable({...});
}
alphadogg
D'oh! So simple. It worked. Thanks!
Ben
Hey, we've all been there... :)
alphadogg
Don't forget to turn off droppable at some other point..droppable( 'destroy' )
Tom Martin
@Tom martin: Good point -- I did forget that at first!
Ben
+1  A: 

I think it is when you called droppable() that you made the cells droppable so you need to call droppable in your drag handler function.

e.g.

 start: function(event, ui)
    {
      $(this).css('background-color','#ddddff');
      var $cells = $(this).parent().parent().children();
      $cells.addClass("droppable_td");
      $('.droppable_td').droppable
      (
        {
          addClasses: false,
          over: function(event, ui)
         {
           $(this).css('background-color', '#ccffcc');

etc.

I'd suggest making all that into a function though.

Tom Martin