Robert Winchester
Robert Winchester

Reputation: 23

Change CSS class with if/else on droppable

Solution: I changed
$(this).removeClass('inactivetile').addClass('incorrecttile');
to
ui.draggable.removeClass('inactivetile').addClass('incorrecttile');
doi

I've tried a few different things here, but I'm coming up empty.
Basically I want to have a droppable that will check to see what id is dropped on it and change the css accordingly. For example sake let's say I have two draggables: #drag1 and #drag2 and one droppable: #drop1.
When #drag1 is dropped on #drop1 the css class changes from .droptile to .correcttile - if #drag2 is dropped, then the css class changes from .droptile to .incorrecttile. Sounds simple enough, but I can't seem to get past this:

  $('#drop1').droppable({
  hoverClass: 'hovered'});

  $('#drop1').on('drop', function (event, ui) {

  var itemid = $(ui.draggable).attr('id'); //tried this and then called it in the else statement with no luck

      if ($(ui.draggable).attr('id') == 'drop1') {
          ui.draggable.position({ of: $(this) });
          $('#drop1').removeClass('droptile').addClass('correcttile')
      }
      else {
          ui.draggable.position({ of: $(this) });
          $(this).removeClass('droptile').addClass('incorrecttile');
      }

  });

Thanks in advance!

Upvotes: 2

Views: 516

Answers (3)

Aryeh Armon
Aryeh Armon

Reputation: 2175

you need to do something like this:

$(function() {
    $( "#draggable1" ).draggable();
    $( "#draggable2" ).draggable();

    $( "#droppable" ).droppable({
      drop: function( event, ui ) {
          if( ui.draggable.attr('id') == 'draggable1' ){
              $( this ).addClass( "ui-state-highlight" ).find( "p" ).html("Dropped!" );
          }
      }
    });
  });

https://jsfiddle.net/ygk4k7gc/ full example

Upvotes: 0

Robert Winchester
Robert Winchester

Reputation: 23

Solution: I changed
$(this).removeClass('inactivetile').addClass('incorrecttile');
to
ui.draggable.removeClass('inactivetile').addClass('incorrecttile');
doi

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

In the if condition you are using drop1 instead of drag1

$('#drop1').on('drop', function (event, ui) {

    var dragId = $(ui.draggable).attr('id');

    ui.draggable.position({
        of: $(this)
    });

    $(this).removeClass('droptile').addClass(dragId == 'drag1' ? 'correcttile' : incorrecttile)
});

Demo: Fiddle

Upvotes: 1

Related Questions