robertdd
robertdd

Reputation: 335

confirm only 1 time function with jquery

i have this function that will shuffle a list of images, when i press on a #shuffle button i want to trigger a message, if is confirmed the second time i will not want to ask again!

how to code this?

$('#shuffle').click(function(){
  if(confirm('This will shuffle all your bla bla bla')){
    $("#upimagesQueue li").shuffle();       
  }
});

Upvotes: 0

Views: 934

Answers (2)

SeanJA
SeanJA

Reputation: 10354

This is a better more readable way

$('#shuffle').bind('click', function(event){
    if(confirm('are you sure?')){
        $(this).unbind(event);
        $('#shuffle').bind('click', function(){
            $("#upimagesQueue li").shuffle();
        });
        $("#upimagesQueue li").shuffle();
    }
});

See: http://api.jquery.com/one/

Could also be written as:

$('#shuffle').bind('click', function(event){
    if(confirm('are you sure?')){
        $(this).unbind(event).click(function(){
            $("#upimagesQueue li").shuffle();
        })
        $("#upimagesQueue li").shuffle();
    }
});

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630379

You can use a variable, like this:

var confirmed = false;
$('#shuffle').click(function(){
  if(confirmed || confirm('This will shuffle all your bla bla bla')){
    $("#upimagesQueue li").shuffle();  
    confirmed = true;     
  }
});

This starts with the confirm not being acknowledged, but the first time it is, it's set to true. This means the first part of the condition1 OR condition2 in your if() would be true, so the confirm wouldn't pop up again.

Alternatively, you can use .data() to store the variable for this:

$('#shuffle').click(function(){
  if($(this).data('confirmed') || confirm('This will shuffle all your bla bla bla')){
    $(this).data('confirmed', true);   
    $("#upimagesQueue li").shuffle();   
  }
});

Upvotes: 4

Related Questions