Question

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;
}

Was it helpful?

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');
}

OTHER TIPS

You should never have long running methods in the UI thread of a webpage. It will make the page appear to lock up and is very annoying for the user.

Instead you should use asynchronous callback. The long running method I assume does some AJAX calls. In which case it should accept a function as an argument (like the jquery "click", "ajax", etc.). Then pass that function to the ajax method as the completion or success callback.

Then you can do:

$('#button).click(function() {   
    $('#curtain').css('visibility', 'visible');
    longRunningMethod(function() {$('#curtain').css('visibility', 'hidden');});
 });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top