Posts Tagged ‘Javascript’

Live Countdown Timer using Javascript

October 10th, 2009

Been done? Yes of course it has! However you don’t learn anything unless you get stuck in and have a go yourself and that is exactly what I did during an empty half hour period I had the other day (slow lecture). Whilst at university I am doing a lot of timed tasks (ten minutes etc.. as opposed to days) and the timers used are always a mobile phone timer or horrible Powerpoint countdown presentation. I wanted to write something which is simple to build on to create a JS version to ultimately integrate into online resources and lessons (Eg: this task will take you ten minutes. Click here to turn on the timer…).

The  code at the bottom of this post is the raw HTML file I wrote. I obviously made it into a WordPress plugin as well. see below example.

Example

Yes, it’s basic but it works well for demonstrative purposes.

Countdown from:

Usage

write sb_countdown in square brackets in a post or page and you will get the above example. If you want to edit the text or style it then just open the plugin file and right near the top is a few defines to get you going. I didn’t spend a lot of time on it so didn’t create an admin page. I may well do in the future though.

The Download

SB JS Countdown Timer (1.42 kB)

Raw HTML Version

<html>
 <head>
 <title>Countdown Timer</title>

 <style>
 body {
 font-family: tahoma;
 }

 #countdown_div {
 font-weight: bold;
 font-size: 56px;
 }

 #body_wrapper {
 padding: 10px;
 margin: 20px;
 }
 </style>

 <script>
 function do_countdown() {
 var start_num = document.getElementById("value").value;
 var unit_var = document.getElementById("countdown_unit").value;

 start_num = start_num * parseInt(unit_var);

 var countdown_output = document.getElementById('countdown_div');

 if (start_num > 0) {
 countdown_output.innerHTML = format_as_time(start_num);
 var t=setTimeout("update_clock(\"countdown_div\", "+start_num+")", 1000);
 }

 return false;
 }

 function update_clock(countdown_div, new_value) {
 var countdown_output = document.getElementById(countdown_div);
 var new_value = new_value - 1;

 if (new_value > 0) {
 new_formatted_value = format_as_time(new_value);
 countdown_output.innerHTML = new_formatted_value;

 var t=setTimeout("update_clock(\"countdown_div\", "+new_value+")", 1000);
 } else {
 countdown_output.innerHTML = "And... Stop!";
 }
 }

 function format_as_time(seconds) {
 var minutes = parseInt(seconds/60);
 var seconds = seconds - (minutes*60);

 if (minutes < 10) {
 minutes = "0"+minutes;
 }

 if (seconds < 10) {
 seconds = "0"+seconds;
 }

 var return_var = minutes+':'+seconds;

 return return_var;
 }
 </script>
 </head>

 <body>
 <div id="body_wrapper">
 <form id="countdown_form" onsubmit="return do_countdown();">
 Countdown from: <input style="width: 50px;" id="value" />
 <select id="countdown_unit">
 <option value="1">Seconds</option>
 <option value="60">Minutes</option>
 <option value="3600">Hours</option>
 </select>
 <input type="submit" value="Go" />
 </form>
 <div id="countdown_div">&nbsp;</div>
 </div>
 </body>

</html>

Simple AJAX

June 24th, 2008

I’ve been teaching myself AJAX over the last month or so. I’ve written a simple version of the ever popular Autocomplete field but for now I want to give a quick example of what AJAX is and how it can be used simply and implemented quickly.

What is AJAX?
The acronym if I remember correctly stands for Asynchronous Javascript And XML but i’m likely to be wrong :)

What you do need to know is that it uses Javascript to fire off custom requests wherever you want without having to reload the page. I have already mentionned the Autocomplete example above so I’ll use that as an example. At work we use something similar for a UK town search. A user starts to type in the name of a town and after a couple of keystrokes a list of suggestions appears.

Now for the technical bit…
In the above example, when the input field gets to a pre-determined number of characters the Javascript sends an asynchronous request to the server then does nothing. It does nothing because of course its asynchronous! The beauty of this is that the client machine doesn’t have to wait for a response so if a response comes then something will happen otherwise it fails seamlessly.

Putting this back into the example I gave, If the server returns something then the list of suggestions pops up or refreshes with the new data, otherwise it just wont do anything.

A callback function is declared and sent to the server as part of the request. If a number of conditions are met (ie: the server url is valid and it’s set up to receive such requests) then if the server echos anything it will be passed to the callback function. The callback then runs whatever code you have written and does what it wants with the returned result. This is better explained in some code so let’s see how it all works!

This script to use a remote server to echo a random number is the simplest thing i could think of:

<script>

function ajax_request() {
	var request = false;

	if (navigator.appName == "Microsoft Internet Explorer") {
		request = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		request = new XMLHttpRequest();
	}

	request.abort();
	request.open("GET", "ajax.php", true);
	request.onreadystatechange=function() {

		if(request.readyState == 4) {
			alert(request.responseText);
		}
	}
	request.send(null);
}
</script>

Ill take you through it section by section…

First we need to create an AJAX request object, this is done is every proper browser using

request = new XMLHttpRequest();

Of course Microsoft have to be different and don’t support this call (at the time of this post) so we have to put in the nasty if statement that calls this code

request = new ActiveXObject("Microsoft.XMLHTTP");

Next we actually have to set up the request, ie: tell it where to call and what callback function to run

request.open("GET", "ajax.php", true);
request.onreadystatechange=function() { }

In this example we are telling it to call ajax.php using GET (POST is also an option) and to alert the response as the callback (alert(request.responseText);).
Finally we need to fire off the request using

request.send(null);

There are a few bits i’ve missed out for the time being, namely

if(request.readyState == 4) {

}

This readyState option is checked in the callback and only does anything when it is  set to 4. This is the stage when a script actually does something. There are several other requests which i’m sure you can research but for the basic script, just leave the IF statement in. I also haven’t mentionned the XML side of things but we will leave that for another day.

The code that responds to all of this is a simple PHP script. It can simply echo out its data to be picked up by the callback as follows

<?php
echo rand(1,99);
?>

So that’s really it in terms of getting a basic example going but if you consider the possibilities of something rooted in something so simple then you will soon begin to see where you can easily place it into your script.

For example, the posting section in wordpress uses AJAX for an autosave feature in the post window. It probably has a bit of JS on a timer loop that takes the contents of the ‘Post’ box and sends it to a script which updates a DB table and then returns the flag to say whether it saved properly or not. See! easy and very functional!

Alternatively if you like the idea of AJAX but can’t be bothered to play with the proper stuff then there’s always JQuery and Scriptaculous