-1
if (confirm('ARE YOU SURE?')) {console.log('sure');}
else {console.log('not sure');}

I want this functionality with my own confirm box and my own function

<div class='mdialog' id='mdialog'>
<div id='dgcancel' onclick="???">CANCEL</div>
<div id='dgok' onclick="???">OK</div>
<div id='dgquestion'>//here is the question</div>
</div>

if (conf('ARE YOU SURE?')) {console.log('sure');}
else {console.log('not sure');}

function conf(){
// ???
}

Could someone help me to accomplish this?

Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

0

You have the skeleton for your html.

Instead of ??? put there something replaceable, like {{cancelCallback}}, {{okCallback}}, {{question}}.

Then, create a Dialog class that you can instantiate. Here's a great place to start: What techniques can be used to define a class in JavaScript, and what are their trade-offs?

The class should take as parameters 3 things (not necessarily in this order):

  1. a function that gets called when the cancel is clicked
  2. a function that gets called when ok is clicked
  3. the actual question

This class, when instantiated, should display, or inject, the HTML skeleton in the DOM and at the same time replace the {{}} variables with the actual functions/string.

You should be able to have a "dispose" method to this class.

And prepare for the future: maybe you add more buttons - make it expandable. Etc.

Have fun!

And I hope you did not expect to actually provide the code for that, as that's not the purpose of StackOverflow :)

Adelin
  • 7,809
  • 5
  • 37
  • 65
0

The question you are trying to point is unclear. Using confirm function leads you to a confirmation dialog box answering ok and cancel.

Another is using a div tag for a confirmation of ok and cancel. You can change this into button.

I made some changes to your code an created a pen you can visit, and try to play around with it.

function myFunction(x) {
  if (x == "ok") {
    var conf = confirm("Are you sure You want to delete this item");

    if (conf == true) { //this block means the user clicked the "OK" in the confirmation dialog box.
      //Some statement here
      //example alert statement
      alert("Item has been successfully deleted!");
    }
  }
  if (x == "cancel") {
    var cancel = confirm("Are you sure you want to cancel");
    
    if (cancel == true) {
      alert("Item deletion has been cancelled");
    }
  }
}
<div class='mdialog' id='mdialog'>
  <div id='dgquestion'>
    <h1>Do you want to Delete this item?</h1>
  </div>
    <button onclick="myFunction('ok')">OK</button>
    <button onclick="myFunction('cancel')">CANCEL</button>
</div>
Victor G.S.
  • 61
  • 1
  • 10