I’m teaching myself javascript/jquery and decided as a side project to create a drag and drop game. I’ve based it on other tutorials I’ve found and just adapted it really, so go easy on the code – hopefully its not too scary.
I’m using the jquery ui dropable library to implement the game and currently I check once the item is dropped if it is in the correct place, if it is I increment the score by one.
However the problem I have is I can’t get the score to go down by one when the item is dropped in the wrong place.
If a square is placed on the correct placeholder it adds 1 to the score but if that same square gets removed from the correct place holder then it needs to take 1 off the score.
Heres a demo here of what I’ve done so far
http://creativelabel.co.uk/drag-and-drop/
Any ideas?
One way to approach this is to store in the dropped element whether it was placed in a valid square. This means when it is moved to an invalid square you can check if it was previously in a valid one and if this is the case reduce the score by one.
Hope this is clear!
See http://jsfiddle.net/pET3y/ for a live demo
Relevant code:
Note: the the fiddle has an alert
alert(ui.draggable.data("valid"));for debug—
Changing for on drag the score goes down
What you do now is listen for the drag event (called
activate), and when this is called run a function. The function checks if the element being dragged was previously in the correct position and if it was, marks it as not in the correct position and decreases the score.See: http://jsfiddle.net/3NkwJ/1/
And add the below: