1
votes

I am trying to develop a simple drag and drop 'game'. In simple terms all you do is drag and drop various items into a area and it will say correct or wrong depending on the item dragged. This is what I have so far and its not working at all and I dont know why. My knowledge of JS and jQuery leaves a lot to be desired too.

<script>
$(function() {
    $( "#draggable" ).draggable();
    $( "#wrong" ).draggable();

    $( "#droppable" ).droppable({    
        drop: function( event, ui ) {
            var currentId = $(this).attr('id');
            if (currentId == "draggable") {
                $( this )
                    .addClass( "highlight" )
                    .find( "p" )
                    .html( "Correct! :)" );
            } else {
                $( this )
                    .find( "p" )
                    .html( "Wrong! :(" );
            }
        }
    }); 
});
</script>

Now that I have it working I need more instances of the draggable images but when I add more the the new ones that have been added don't work.

http://jsfiddle.net/KcruJ/9/

3
can you do a jsfiddle of your code? or use firebug to check if you have any javascript errors. - Kishore
in your fiddle: you don't want elements with the same id. use class instead - Valentin

3 Answers

0
votes
var currentId = $(this).attr('id');
if (currentId == "draggable")
    ...

Will never result true, as $(this) represents the droppable the draggable is dropped on. ui.draggable represents the draggable[1]

Try:

var currentId = $(ui.draggable).attr('id');
if (currentId == "draggable")
    ...
0
votes

This works: http://jsfiddle.net/T6nu3/2/


$(this).attr('id');

Will always return droppable. You need to access the dragged element:

$(ui.draggable).attr('id');

Take a look at the jQuery UI Documentation for more information.

Code:

$(function() {
    $("#draggable").draggable();
    $("#wrong").draggable();

    $("#droppable").droppable({
        drop: function(event, ui) {
            var currentId = $(ui.draggable).attr('id');
            if (currentId == "draggable") {
                $(this).addClass("highlight").find("p").html("Correct! :)");
            } else {
                $(this).find("p").html("Wrong! :(");
            }
        }
    });
});
0
votes

haha well, Alex seems to have this one on lock.

There's the answer: http://jsfiddle.net/aGqHh/1/