Jerry Malcolm
Jerry Malcolm

Reputation: 35

javascript confirm prevents screen update in Chrome

I have a javascript function that does two things:

It works fine on Firefox. On Chrome, the popup appears. But the background does not change color until AFTER I dismiss the confirm() box which kinda defeats the objective of letting the user know what row is to be deleted.

I'm sure it has to do with the asynchronous nature of javascript. But I need to know how to get around it. Right now, the two lines of code are:

  $(icon).closest( "tr" ).css( "background-color", "yellow" );
  if ( confirm( message )) {.......}

What do I need to do to make sure the row is yellow while the popup is displayed and doesn't wait to change to yellow until after the popup goes away? I can try delays, etc. But that's grasping at straws. Is there a 'correct' way to handle this?

Again, works fine on Firefox.... nada on Chrome. Haven't tried other browsers.

Thanks. Jerry

Upvotes: 2

Views: 1124

Answers (2)

Nigel
Nigel

Reputation: 1

I had the same issue. When I showed a confirm dialog in Chrome, my earlier DOM changes were not yet visible. The user needed to see those DOM changes in order to reply to the confirm dialog.

To fix this I used a delay as follows.

function outerFunction() {
  console.log("do stuff");

  setTimeout(innerFunction, 0);
  return;

  function innerFunction() {
    if (confirm("really?")) {
      console.log("do more stuff");
    }
  }
}

Note that by using a nested function you don't need to pass any parameters.

Note also that the Chromium team highly recommends that you not use JavaScript dialogs--see Chromium policy on JavaScript dialogs

Upvotes: 0

Brad
Brad

Reputation: 163262

I can try delays, etc. But that's grasping at straws.

Not really.

It's entirely up to the browser when to render things. Each browser engine has its own optimizations. The only way to handle this is a short delay.

One reliable form of delay is requestAnimationFrame(). I think you can be reasonably sure that once this is fired, the browser will have repainted anything previously. Untested, but try something like this:

$(icon).closest('tr').css('background-color', 'yellow');
requestAnimationFrame(function () {
  if (confirm(message)) {

  }
});

Also note that you don't have any control over where that confirm box appears. It could be on top of your content. It's up to the browser to decide how to present that, whether it be a traditional tool-style window, or a full-screen modal.

Upvotes: 1

Related Questions