Search code examples
javascriptpromiseconfirm

Stop function until clicked ok or cancel - JQUERY


i created custom confirm box like this:

function formPopup(message, callback) {
    message = message + '<div class="clear"></div><button class="mybutton" name="check" value="true">Yes</button>' +
            '<button class="mybutton mybutton2" name="check" value="false">No</button>';
    createPopup("Message", message);

    $(".popup .body button[name='check']").bind("click", function (e) {
        val = $(this).val();
        if (val == "true") {
            $(".popup").find(".close").trigger("click");
            typeof (callback) != "undefined" ? callback() : null;
        } else {
            $(".popup").find(".close").trigger("click");
        }
    });
}

i want when i run formPopup function the page wait like "confirm" or "alert" until i will click on $(".popup .body button[name='check']").

i tried with

promise and when

but its didnt helped.

tnx a lot


Solution

  • Do you mean something like this?

    jQuery could not get "this" in your click function, i replaced it with e.target, so event.target == the button that you are clicking.

    function showPopup(message, callback) {
        $(".popup").css("display", "block");
        $(".title").html(message);
        
        // only button 1, value will be true anyways, but just to show how to access the button object
        $(".b1").on("click", (e) => {
            var val = $(e.target).val();
            if (val == "true") {
              closePopup();
              typeof (callback) != "undefined" ? callback() : null;
    
            } else {
              closePopup();
            }
        });
        
        // button 2, try to split as much as you can, makes everything alot easier
        $(".b2").on("click", (e) => {
           closePopup();
        });
    }
    
    function closePopup() {
        $(".popup").css("display", "none");
        setTimeout(() => {
          showPopup("back again", () => { console.log("callback"); });
        }, 2000);
    }
    
    showPopup("message", () => { console.log("callback"); });
    .popup {
      position: fixed;
      display: none;
      left: 0;
      top: 0;
      bottom: 0;
      right: 0;
      background: rgba(0, 0, 0, 0.2);
      z-index: 1;
    }
    
    .popup-content {
      position: absolute;
      color: red;
      background: green;
      width: 300px;
      left: calc(50% - 150px);
      height: 100px;
      top: calc(50% - 50px);
      z-index: 2;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="clear">
    </div>
    <div class="popup">
      <div class="popup-content">
        <h1 class="title"></h1>
        <button class="b1" name="check" value="true">Yes</button>
        <button class="b2" name="check" value="false">No</button>
      </div>
    </div>