Search code examples
javascriptjqueryconfirm

do something before confirm dialog pops up


$('.lorem').on('click', function(){
    $(this).hide();
    if(prompt('DO SOMETHING') != null) {console.log('something');}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='lorem'>lorem</div>

So I firstly want to hide the div and then pop up the confirm dialog. Is it possible?


Solution

  • Use animation frames to run code before the next paint.

    window.requestAnimationFrame()

    $('.lorem').on('click', function(){
        // The browser will paint async not sync, so the div may still be visible
        // even after this line
        $(this).hide();
        // when the browser is ready to paint the div off screen the callback will fire
        window.requestAnimationFrame(() => { 
            if (prompt('DO SOMETHING') != null) {
                console.log('something');
            }
        });
    });
    

    note: You may have to do nested animation frames as browsers tend to implement request animation frame differently.

    requestAnimationFrame(() => requestAnimationFrame(() => {
        ...
    }));