Search code examples
javascriptjqueryjquery-uijquery-eventsjquery-click-event

How to show opaque background on jQuery click event


In order to show an opaque background or animated gif while executing some method after an button click fails to show this. It only runs after all the code has been executed.

Can I do this in jQuery, i.e. on a click event render html changes before and after main code.

The long running method is adding 100-500 divs to the page that takes about 10 seconds to finish.

$('#button).click(function() {   
    $('#curtain').css('visibility', 'visible');
    longRunningMethod();    
    $('#curtain').css('visibility', 'hidden');  
 });    

The problem is that the #curtain div never shows, as the complete javascript has to be executed before rendering all the changes.

Style:


#curtain {
    position: fixed;
    _position: absolute;
    z-index: 99;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    _height: expression(document.body.offsetHeight + "px");
    background-color: #CCCCCC;
    filter:alpha(opacity=50);
    -moz-opacity:0.5;
    -khtml-opacity: 0.5;
    opacity: 0.5;
    visibility: hidden;
}


Solution

  • This is kind of a hack, but if you use setTimeout it might work.

    $('#button').click(function() {   
        $('#curtain').css('visibility', 'visible');
        setTimeout(doBigJob, 100);
     });
    
    function doBigJob()
    {
        longRunningMethod();    
        $('#curtain').css('visibility', 'hidden');
    }