Mockjax and jQuery UI Progressbars
Using a mock API to poll for progress updates.
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mockjax/1.5.2/jquery.mockjax.min.js"></script>
<div id="progressbar">
<div class="progress-label">Loading...</div>
</div>
CSS
body {
font-size: 0.8em;
}
.ui-progressbar {
position: relative;
}
.progress-label {
position: absolute;
left: 50%;
top: 4px;
font-weight: bold;
text-shadow: 1px 1px 0 #fff;
}
JavaScript
(function( $ ) {
// A mock progress API endpoint. Each call to "/api/progress"
// will increment the progress "server" variable. This value
// is returned in a JSON response.
var progress = 0;
$.mockjax({
url: "/api/progress",
responseTime: 50,
dataType: "json",
response: function( settings ) {
progress += 1;
this.responseText = { progress: progress };
}
});
})( jQuery );
$(function () {
// Create the progressbar widget.
$( "#progressbar" ).progressbar({
// This causes the animated background to appear till
// an integer value is set.
value: false,
// Updates the label as a percentage.
change: function( e, ui ) {
var $this = $( this );
$this.find( ".progress-label" )
.text( $this.progressbar( "value" ) + "%" );
},
// Updates the label using complete text.
complete: function () {
$( this ).find( ".progress-label" )
.text( "Complete!" );
}
});
// Poll our mock API for progress updates.
function poll() {
// Make the API call and store the deferred object.
var deferred = $.ajax({
url: "/api/progress",
dataType: "json",
});
// Process the mock API response.
deferred.done(function( data ) {
// Local variables
var value = data.progress,
$progressbar = $( "#progressbar" );
// Set the value to 100 if it's greater than 100. Update
// the progressbar value and continue to poll if we're
// not at 100 yet.
if ( value >= 100 ) {
value = 100;
$progressbar.progressbar( "value", value );
} else {
$progressbar.progressbar( "value", value );
...