JavaScript Working Text

Letting the user now that something in the background is working is an essential part of website usability. If nothing at all happens then the user will more than likely either try again or go elsewhere. A good way of doing this is to have a little bit of text that says "Working" and animate dots behind it. Here is a function that will do this.

var strDots = '';
var dotLength = 10;
var timeout = 500;
function dots()
  { 
  strDots += '.';
  if ( strDots.length == dotLength ) {
    strDots = '.';
  }
  document.getElementById('working').innerHTML = "<b>Working"+strDots+"</b>";
  dotTimer = setTimeout('dots()', timeout);
}

You then need to add the following bit of HTML to your page to start the dots off. The first one will print off:

Working

Followed by:

Working.

And so on. To get the code working on your page create a HTML element with an ID of working and include the following below that element.

<p id="working"></p>
<script type="text/javascript" language="javascript">dots();</script>

To stop this you need to then call a second function.

function stopDots()
  { 
  // stop the dots
  if ( typeof(dotTimer) != 'undefined' ) {
    clearTimeout(dotTimer);
  }
  document.getElementById('working').innerHTML = "<b>Done!</b>";
}

When you call this function the "Working" will be replaced by the text "Done!". If you are loading content in AJAX you can start the animation when the AJAX starts and then stop it when you get the data back from the server.

Another way of using this script is if you are flushing content to the browser with PHP you can start off the page by printing off the working function and then end the page with the stopDots() function. The browser will run the JavaScript as it comes through so you can create a nice little working notice on your pages that take a long time to load. This is a weird way of using JavaScript, but it does work on slow loading pages.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
1 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.