i want the draggable object to revert back to its original position when i click a button. i used \'destroy\' option but it doesnt seem to work. it disables the dragging but
How about this?
<script type="text/javascript">
jQuery(document).ready(function() {
$("#draggable").data("Left", $("#draggable").position().left)
.data("Top", $("#draggable").position().top);
$("#draggable").draggable();
$("#nextImg").bind('click', function() {
$("#draggable").animate(
{ "left": $("#draggable").data("Left"),
"top": $("#draggable").data("Top")
}, "slow");
$("#draggable").attr("src", "img"+(++imgnum)+".jpg");
});
});
</script>
I've made some assumptions, such as the nextImg object having an id of "nextImg" so that I can bind the click event using jQuery (one less step in the javascript event binding process?) I'm also assuming that you don't really want to destroy the drag functionality.
Would revert help you out?
http://docs.jquery.com/UI/Draggable#option-revert
Revert executes when dragging has stopped (with optional delay), not on click.
$(document).ready(function() {
var originalTop = $('#draggable').position().top;
var originalLeft = $('#draggable').position().left;
$('#Zoom').toggle(
function() {
$("#draggable").draggable({});},
function() {
$("#draggable").draggable('destroy');
$('#draggable').position().top = originalTop;
$('#draggable').position().left= originalLeft;
});
});
Revert option is set to false by default, you've to set it to true.
$("#draggable").draggable({
revert: true
});
this should do it actually...
EDIT: I'm pretty sure this will do the trick:
//reposition the draggable after it has finished
$(".selector").draggable({
stop: function(e,ui) {
ui.instance.element.css("left","0px");
ui.instance.element.css("top","0px");
}
});
function revertable($drag){
$drag.data({ top: $drag.css('top'), left: $drag.css('left') })
$('.'+$drag.attr('id')+'.revert').data({ revert: '#'+$drag.attr('id') })
.on('click',function(){
var $rev = $( $(this).data('revert') );
$rev.css({ top: $rev.data('top'), left: $rev.data('left') });
})
}
// simply call the function in the create event
var $drag = $('#my_draggable'); //your element
$drag.draggable({
create: revertable($drag)
});
//test it: change the top/left values, refresh, click the button to see it work.
<div id="my_draggable" style="position:absolute;top:100px;left:100px">
Drag Me Around
</div>
<button class="my_draggable revert">Revert My Draggable</button>
...tested, should work for any element (requires jquery 1.7 for .on() function)