JavaScript Working Text

18th January 2008

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.

  1. var strDots = '';
  2. var dotLength = 10;
  3. var timeout = 500;
  4. function dots()
  5. {
  6. strDots += '.';
  7. if ( strDots.length == dotLength ) {
  8. strDots = '.';
  9. }
  10. document.getElementById('working').innerHTML = "Working"+strDots+"";
  11. dotTimer = setTimeout('dots()', timeout);
  12. }

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.

  1. <p id="working"></p>
  2. <script type="text/javascript" language="javascript">
  3. <!--//--><![CDATA[// ><!--
  4. dots();
  5. //--><!]]>
  6. </script>

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

  1. function stopDots()
  2. {
  3. // stop the dots
  4. if ( typeof(dotTimer) != 'undefined' ) {
  5. clearTimeout(dotTimer);
  6. }
  7. document.getElementById('working').innerHTML = "Done!";
  8. }

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.