I’m creating a simple drag and drop game with jquery’s draggable plugin.
There are 4 shapes, circle, square, triangle and star, and 4 drop off areas in divs:
<div class="drag">
<div class="container">
<div id="circle"></div>
</div>
<div class="container">
<div id="square"></div>
</div>
<div class="container">
<div id="triangle"></div>
</div>
<div class="container">
<div id="star"></div>
</div>
</div>
<div class="drop">
<div class="container">
<div id="circle"></div>
</div>
<div class="container">
<div id="square"></div>
</div>
<div class="container">
<div id="triangle"></div>
</div>
<div class="container">
<div id="star"></div>
</div>
</div>
This for example is the info for circle (please imagine the same with the rest of the shapes):
function init() {
$('.drag #circle').data('shape','circle').draggable({
cursor: 'move',
stack: '#circle',
revert: true
});
$('.drop #circle').data('shape','circle').droppable( {
accept: '#circle',
drop: handleDropEvent
} );
};
init();
This is the handle drop event:
function handleDropEvent( event, ui ) {
var item = $(this).data('shape');
var drop = $(this).data('shape');
var dragItem = ui.draggable;
if (item==drop){
dragItem.position( { of: $(this), my: 'left top', at: 'left top' } );
dragItem.draggable( 'option', 'revert', false );
dragItem.draggable( 'disable' );
$(this).droppable( 'disable' );
correctMatch++;
}
if ( correctMatch == 4 ) {
$('.replay').show();
$('.replay').click(function(){
init();
});
}
}
Now in the replay class is a replay button. How do I have my shapes revert back to their original position?
You could rebuild all from scratch, if you saved the original position, and then make it all draggable again. The easiest way is of course reloading the page, but I’m assuming you don’t want to do that. Therefore, I can think of several ways to go:
1) When the document is ready, save enough information to rebuild the items from scratch in an array. I see you have 4 classes: circle, square, triangle and star. Just store the IDs in order in an array
and then whenever the user clicks in the replay button you use this info to rebuild.
then you would have to bind again the draggable function, because the DOM has changed.
2)Use the same array but MOVE the actual items to their positions. This can become a nightmare of selectors, but it is possible. You can always asign a DOM element to a var, and then move it at will through the page:
With eq you select the first/second/etc element from a set of elements. You have to make sure you are selecting just one element for your code to behave properly. Take into consideration that you have repeated ids in your html code. This is something you want to avoid, change them to classes or this kind of manipulation will become tricky at best.