Reputation: 639
I have a delete button to delete a photo. The first click animates a div
on top with the message: "Click again if you really want delete this photo." A second click deletes the photo. If you don't click again in 3sec since the first click, the message will disappear. But then if it disappears and you click the button again, it will still be deleted. I need to stop the script when message disapper to stop post $.ajax()
$(".delete").toggle(function(){
$("#top").html("Click again if you really want delete this photo.");
$("#top").animate({top: "0"}).delay(3000).animate({top: "-50"});
return false;
}, function() {
$("#top").animate({top: "-50px"});
var id = $(this).attr("id");
$.ajax({
...
});
});
Upvotes: 1
Views: 1555
Reputation: 639
So i edit it and it works
var allowDel;
$(".delete").click(function(){
if(allowDel){
$.ajax();
allowDel = false;
}else{
allowDel = true;
setTimeout(function() {
$("#top").slideUp();
}, 3000);
return false;
}
});
Upvotes: 0
Reputation: 66693
Another solution, this time without any additional variables OR attributes/properties (not that there is any significant advantage, maybe a tad cleaner). This one uses the message DIV's Y coordinate to determine whether to allow deletion.
Demo: http://jsfiddle.net/Eu2vu/
Code:
$(".delete").click(function() {
var top = $('#top');
if (top.position().top >= 0) {
top.animate({top: "-50px"});
console.log('do delete');
}
else {
top.html("Click again if you really want delete this photo.");
top.animate({top: "0"}).delay(3000).animate({top: "-50"});
}
});
Upvotes: 0
Reputation: 70528
You could just put a variable in the closure like this:
var allowDel;
$(".delete").toggle(function(){
allowDel = true;
$("#top").html("Click again if you really want delete this photo.");
$("#top").animate({top: "0"}).delay(3000).animate({top: "-50"});
setTimeout(function() { allowDel = false; }, 3000);
return false;
}, function(){
if (!allowDel) return;
$("#top").animate({top: "-50px"});
var id = $(this).attr("id");
$.ajax({
...
});
});
Upvotes: 1
Reputation: 24526
Something like this (untested):
$(".delete").click(function()
{
if ($(this).attr('canDelete') == 'y')
{
$("#top").animate({top: "-50px"});
... do delete
}
else
{
$("#top").html("Click again if you really want delete this photo.");
$("#top").attr('canDelete', 'y')
.animate({top: "0"})
.delay(3000)
.attr('canDelete', 'n')
.animate({top: "-50"});
}
});
Upvotes: 4
Reputation: 11429
Why not do something like this?
$(".delete").click(function() {
if ( $(this).hasClass("confirm") ) {
//When the button is clicked again within 3 seconds it will have
//the confirm class and will go here
} else {
//The button will go here when clicked first time, a class
//of confirm is added for 3 seconds.
$(this).addClass("confirm");
setTimeout(function() {
$(this).removeClass("confirm");
}, 3000);
}
});
Upvotes: 3