Search code examples
javascriptjqueryconfirm

confirm not working after first click: confirm is not a function


I have this jQuery code which pops out the confirm box when a user clicks any link within a div. But if I click a link the confirm box at first, it pops up, if I click cancel the operation is cancelled and the console.log says confirm is not a function and if I click OK the operation is executed and the console.log says confirm is not a function also then if I click a link again the confirm box doesn't pops up again until I reload the page.

Please do anyone know what I am getting wrong?

$("#aye a").click(function() {
  str = "Removing this Photo, It can not be reversed\nAre You sure You want to remove it?";
  confirm = confirm(str);
  if (confirm) {
    $("#div").html("deleted");
  }
});
<div id="aye">
  <a href="javascript:;">link 1</a>
  <a href="javascript:;">link 2</a>
  <a href="javascript:;">link 3</a>
  <a href="javascript:;">link 4</a>
</div>
<div id="div"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>

View on jsFiddle


Solution

  • You are shadowing window.confirm with a global variable named confirm.

    Here is one solution, where I call your local variable confirm2

    $("#aye a").click(function(){
        var str = "Removing this Photo, It can not be reversed\nAre You sure You want to remove it?";
        var confirm2 = confirm(str);
        if(confirm2){
            $("#div").html("deleted");
        }
    });
    

    Note that I've also added the var keyword to keep those variables from leaking into global space.