Search code examples
javascriptwindowloadinganimated

How do I check if a window is still loading and also finished loading?


I am creating a functionality where a user presses a button (Print Timetable) and then a popup window appears with a page showing their timetable and then the printing options automatically appear. However, when the popup is still loading the timetable I want to display an animated GIF. The timetable in the popup isn't fetched with AJAX so I can't use ajax start and stop so how would I do this then?

<input type="button" value="Print Timetable" class="printButton" onclick="window.open(url, ' _parent','height=550, width=800');"/>

This is what is happening so far in the timetable popup:

<div id="animated-logo" class="animated-logo">
    <a href="/" title="Print your timetable">Test</a>
</div>

<script  type="text/javascript">
        $('.animated-logo').addClass('logo');
        $('.animated-logo').removeClass('animated-logo');
    if (window.print){ self.print();}

</script>

Obviously, that animated gif isn't going to work but it's a start.

Any help would be great. Thanks!


Solution

  • Have a look at jQuery's load() over here.

    HTML

     <div id="" class="itm-animated-logo">
            <a href="/" title="Print your timetable">Test</a>
            <div id="time-table">...</div>
        </div>
    

    jQuery

    $("#time-table").load(function() {
      $(this).parent().removeClass("itm-animated-logo");
    }
    

    CSS

    .itm-animated-logo {background-image: loading.gif;}
    

    So when the pop-up is loaded (with class itm-animated-logo), its background will be the loading.gif file. As soon as your time table is loaded (#time-table) the class of the pop-up will be removed and the background, subsequently, as well.

    The downside of this may be that parts of the time table will get loaded (so the time table gets loaded in chunks) in which case they will be 'on top of' the background-image. To fix this you can make an extra div. Maybe this solution is even better:

    HTML

     <div id="" class="itm-animated-logo">
            <div id="loading"><img src="loading.gif" alt="Loading your time table" height="32" width="32" /></div>
            <a href="/" title="Print your timetable">Test</a>
            <div id="time-table">...</div>
        </div>
    

    jQuery

    $("#time-table").load(function() {
      $(this).parent().children("#loading").fadeOut("slow");
    }
    

    CSS

    #loading {
       display: block;
       width: 32px;
       height: 32px;
       margin: 50px auto;
       padding: 0;
    }