A Simple To-do List App Using HTML5 and local storage

HTML5 has brought great potential to the web applications of the future. But what about simple apps that don’t even need internet, such as your to-do list? Now that local storage is implemented by all major browsers, you can easily leverage this feature to build simple apps for personal use.

View demo | Share on twitter

This post will show you how to build a simple HTML5 and local storage powered to-do list. However, keep in mind that I’m only trying to show what can be accomplished with HTML5, so the code may not be perfect.

The localStorage API

The API that we’ll be using is simple. To set a value in local storage, we use localStorage.setItem() to save a task, and localStorage.removeItem() to delete one. The number of local storage items can be found by localStorage.length.

The HTML markup

This to-do app consists of just one text input field and an unordered list. The initial HTML markup required for the form and the task list looks like this:

<form id="tasks-list">
<input id=”task”>
</form>

<ul id=”tasks”></ul>

The JavaScript

This is the JavaScript I used to load the tasks from local storage initially.

$(document).ready(function() {

  // Initial loading of tasks

  var i = 0;

  for( i = 0; i < localStorage.length; i++)
    $("#tasks").append("<li id='task-"+ i +"'>" + localStorage.getItem('task-'+i) + " <a href='#'>Delete</a></li>");

  // Add a task
  $("#tasks-form").submit(function() {
    if (  $("#task").val() != "" ) {
      localStorage.setItem( "task-"+i, $("#task").val() );
      $("#tasks").append("<li id='task-"+i+"'>"+localStorage.getItem("task-"+i)+" <a href='#'>Delete</a></li>");
      $("#task").val("");
      i++;
    }
    return false;
  });

  // Remove a task

  $("#tasks li a").live("click", function() {
    localStorage.removeItem($(this).parent().attr("id"));
    $(this).parent().hide();
    for(i=0; i<localStorage.length; i++) {
      if( !localStorage.getItem("task-"+i)) {
        localStorage.setItem("task-"+i, localStorage.getItem('task-' + (i+1) ) );
        localStorage.removeItem('task-'+ (i+1) );
      }
    }
  });
});

[Note. The code here might differ slightly from the demo page. Take a look there to find the latest code.]

The first part of the above code loops through the tasks stored in local storage. The items are stored with the key, item-n, where n ranges from 1 to the size of the array.

The second part responds to form submission. When the user enters something into the text box and hits enter, the content gets appended as a list item to the <ul>.

On clicking the delete link, the item corresponding to that is removed, and then, looping over the list, the task keys are numbered again starting from task-1.

Improvements

The list needs to be editable, and you will probably want to reorder it as well. With this post I only wanted to show how easy it is to get started with creating such simple apps using HTML5 and JavaScript, It’s probably not really very well written JS code (I don’t know enough to know if it’s any good.).

To edit the tasks, we could probably use the contenteditable attribute. I will hopefully write another post very soon about how to make the list editable.

* * *

Thanks to my pal cooljaz124 for helping me out with this idea, and also for constantly pulling my attention towards cool things people have done with HTML5. He’s just started his own blog and done a couple of cool of cool CSS experiments there (see here and here).

Update. Koes Bong added a lot of features features to this app and his version is available here.

JavaScript: How to create a simple countdown timer

After yet another disappointing performance yesterday by the football (soccer, if you’re American) club I support, Liverpool, this was my tweet:

I’ve already started counting days until FIFA world cup. Football season seem practically over for Liverpool. :(

I actually did count the days, but being a web developer, I ended up writing javascript code to do the dirty work for me. ;-) I’ve never really done much with javascript date and time, so I’m not sure if there’s a better way to do this, but this works. Follow these steps to create a countdown timer for FIFA World Cup 2010. It’s easy to customize it for anything else.

First, we have to create a div with id as “worldcup_countdown_time” where you want to display the countdown timer. This div will be modified by our script to display the time remaining for the World Cup kick off.

<div id="worldcup_countdown_time"> </div>

Now let’s write the script that will calculate the number of days, hours, seconds and minutes left for kick off. We’ll write each of the steps first and then put it all in a function called updateWCTime().

First we have to calculate the time difference between the current time and the time of kickoff. Here, now is the current time, and kickoff is the kickoff time. We store the difference (which we get in milliseconds) in a variable called diff.

    now = new Date();
    kickoff = Date.parse("June 11, 2010 11:30:00");
    diff = kickoff - now;

We find the time left till kickoff in terms of days, minutes, hours and seconds as shown below. We use the Math.floor function to get the absolute values in the variables. It returns the highest integer that’s less then the floating point value.

    days  = Math.floor( diff / (1000*60*60*24) );
    hours = Math.floor( diff / (1000*60*60) );
    mins  = Math.floor( diff / (1000*60) );
    secs  = Math.floor( diff / 1000 );

Now these variables will give us the exact number of hours, minutes and seconds left, but that’s not exactly what we want. If the remaining time were a day and 7 hours, we would have the value 31 (24+7) in the minutes variable. But what we want is the value 1 in the day variable, and the value 7 in the hours. Let’s create another set of variables to do that.

    dd = days;
    hh = hours - days  * 24;
    mm = mins  - hours * 60;
    ss = secs  - mins  * 60;

Now that the time has been calculated, you have to update the div you created at the beginning.

    document.getElementById("worldcup_countdown_time")
        .innerHTML =
            dd + ' days ' +
            hh + ' hours ' +
            mm + ' minutes ' +
            ss + ' seconds';

Putting it all together

Now, to make the countdown timer work, let’s put it all together.

function updateWCTime() {
	now      = new Date();
	kickoff  = Date.parse("June 11, 2010 11:30:00");
	diff = kickoff - now;

	days  = Math.floor( diff / (1000*60*60*24) );
	hours = Math.floor( diff / (1000*60*60) );
	mins  = Math.floor( diff / (1000*60) );
	secs  = Math.floor( diff / 1000 );

	dd = days;
	hh = hours - days  * 24;
	mm = mins  - hours * 60;
	ss = secs  - mins  * 60;

        document.getElementById("worldcup_countdown_time")
            .innerHTML =
                dd + ' days ' +
                hh + ' hours ' +
                mm + ' minutes ' +
                ss + ' seconds';
}
setInterval('updateWCTime()', 1000 );

The last line in the above code creates a timer that calls the updateWCTime() every 1000ms to refresh the timer every second.

Put this script in a .js file and include it in your HTML page to turn the dv with id “worldcup_countdown_time” into a countdown timer that counts down to the world cup kickoff time. There you go, you have a working countdown timer ready now with something like the following diplayed in the div:

186 days 17 hours 12 minutes 14 seconds

To count down to some other event, you can easily change the value in the kickoff variable to the date that you want to use.

Update. I’ve put up the code on gihub where you can also download it as tar.gz.

How to create a simple datepicker using jQuery

jQuery allows you to easily create a datepicker and customize it according to your requirements. Here’s a quick look at how you can get started with using the jQuery datepicker.

The jQuery website has a nice application called Themeroller that lets you customize the interface for jQuery UI widgets. There are also plenty of themes available in the gallery that you can download and use directly. Copy the stylesheet, images, the jQuery file and the jQuery-UI files into the appropriate directories and link them in the header of your HTML file.

Now let’s create a simple form that contains the text field that you want to convert into a datepicker.

<form action="index" method="get">
  <input id="date-pick" name="date-pick" type="text" value="" />
  <input id="date-submit" name="date-submit" type="submit" value="Go!" />
</form>

To convert the input field with the id date-pick into a datepicker, write the following jQuery code in the head section of your HTML.

$(function(){
  $("#date-pick").datepicker();
});

That’s it! The input field that you created now works as a popup datepicker. A calendar showing the current month appears whenever you focus on the #date-pick field and the date you click on appears as text in the field.

There are tons of options to customize the datepicker, such as changing the date format sent to the server or using a different language for the calendar. You can explore these options in the jQuery UI documentation for the datepicker.

jQuery: Avoiding conflict with other libraries using jQuery.noconflict()

Recently, when using jQuery in my Ruby on Rails project, the jQuery calendar plugin I was using suddenly refused to work in one of the views. The plugin was working fine everywhere else, but it just wouldn’t work here.

The problem was that there was a conflict with a rails prototype helper (observe_field) that I was using in the view. Using jQuery along with other javascript frameworks such as prototype or mootools causes a namespace clash as they all use the $ alias.

jQuery provides a noconflict method to avoid this clash, which lets you rename the jQuery function ($) as something else.

In the code below, the noconflict method is called to replace the $ alias with the function name jQuery and release $ to other frameworks.

<script src="jquery.js">&lt/script>
<script>
  jQuery.noConflict();
  jQuery(document).ready(function(){
    // your code goes here.
  });
</script>

However, you can also use some other name instead of jquery by assigning jQuery.noconflict() to another variable. In the code below, I have use $jq as the new alias for the jQuery function. Now you must use this new alias where you would otherwise have used the $ shorthand.

<script src="jquery.js">&lt/script><script>
  var $jq = jQuery.noConflict();
  $jq(document).ready(function(){
    // your code goes here.
  });</script>

Using this form of the noconflict method allows you to avoid namespace conflicts while at the same time giving you the ability to use a short alias ($jq above) for jQuery.

If you want to globally disable the $ alias for jQuery, call the noconflict method from the last line of the jQuery file.

Make sure you call this function before using the conflicting library, otherwise it may still clash. However, you may include the other library without causing any conflict.