0

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?

  • Is it that `update_text()` runs after the `confirm()`, or that any changes `update_text()` makes to the page are not repainted until after the `confirm()`? – nnnnnn Jul 28 '17 at 03:30
  • It seems `update_text` run before `confirm`. but `.html()` and `.val()` repaints after `confirm`. =D – Ken Yoro Ko Jul 28 '17 at 04:59

3 Answers3

0

This might be too simple, but it seems like it fixes the problem.

$('.input').keyup(function(event){
  update_text(); // $('div').html('blahblah');
})
$('.input').blur(function(event){
  update_text();
  if(confirm('Are you sure?')){
    // do somthing...
  }
});
Jacobjanak
  • 297
  • 1
  • 2
  • 9
0

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>
Spencer Wieczorek
  • 20,481
  • 7
  • 40
  • 51
0

update_text() happens on keyup event, which is triggered before the input is blurred, so if set up correctly it actually happens each time the user inputs another character.

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

update_text = function() {
  text = $('.input').val();
  $('#text').text(text);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='input'/>
<div id='text'>
Chava Geldzahler
  • 3,423
  • 1
  • 15
  • 31