Question

This code is for a drag and drop game. Currently, the alert("correct") comes up after each different piece is dragged to its target. How do I change this so that the alert only comes up once at the end of the game, saying how many were correct?

the html:

<img class="drag-me" id="drag1" src="images/drag1.png">
<img class="drag-me" id="drag2" src="images/drag2.png">
<img class="drag-me" id="drag3" src="images/drag3.png">
<img class="drag-me" id="drag4" src="images/drag4.png">

<img class="target" id="target1" src="images/target1.png">
<img class="target" id="target2" src="images/target2.png">
<img class="target" id="target3" src="images/target3.png">
<img class="target" id="target4" src="images/target4.png">

the jquery:

$('.drag-me').draggable({revert:"invalid", snap:".target"});
$('.target').droppable({
    drop: function( event, ui ) {
      itemsInPosition++;
      // get id of draggable and droppable id
      var draggableID = $(ui.draggable).attr("id");
      var droppableID = $(this).attr("id");
      if(draggableID[4]==droppableID[6]){
        alert("correct")
    testIfComplete();
        totalCorrect++;
      }
    }
});

var itemsInPosition = 0;
var totalItems = 4;
var totalCorrect = 0;

function testIfComplete(){
if(itemsInPosition==totalItems){
alert("You got " + totalCorrect + " right")
  }
}

Thanks !

Was it helpful?

Solution

May be , you should choose the suitable libraries: JS+CSS for jquery UI.

See this fiddle . it works. http://jsfiddle.net/abdennour/67SrS/

var itemsInPosition = 0;
var totalItems = 4;
var totalCorrect = 0;
$('.drag-me').draggable({revert:"invalid", snap:".target"});
$('.target').droppable({
    drop: function( event, ui ) {
      itemsInPosition++;
      // get id of draggable and droppable id
      var draggableID = $(ui.draggable).attr("id");
      var droppableID = $(this).attr("id");
      if(draggableID[4]==droppableID[6]){
        alert("correct")
    testIfComplete();
        totalCorrect++;
      }
    }
});

and you can conclude& download the suitables libraries from this fiddle :

http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/overcast/jquery-ui.css 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top