Search code examples
javascriptjquerydialogconfirm

Do function before confirm jquery


here is my jquery code

$('.input').keyup(function(event){
    update_text(); // $('div').html('blahblah');
})
.blur(function(event){
    $(this).keyup();
    if(confirm('Are you sure?')){
        // do somthing...
    }
});

my problem is when input blur, confirm box should be show after doing update_text();

but update_text() seems run after confirm...

How to make it do update_text() first, then show confirm dialog?


Solution

  • Actually your method does run before confirm(), the issue here is that your browser repaints the DOM asynchronously even though the method .html() is in itself synchronous. So while it doesn't appear to run first visually it indeed is.

    For example a more simple version will have the same functionality, which can vary by browser:

    $("div").html("foo");
    confirm('Are you sure?');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div></div>

    One way to get around this is to force the DOM to repaint rather than letting the browser do it. For example:

    $("div").html("foo");
    $("div").hide().show(function(){
      confirm('Are you sure?'); 
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div></div>