A taste of CoffeeScript (part 2)

Default avatar.
May 29, 2013
A taste of CoffeeScript (part 2).

thumbnailIn the first part of this article about CoffeeScript, you saw its basic capabilities; but let's be honest, most of the time we use the jQuery library to help us write our JavaScript and what I showed you in the first part was just vanilla JavaScript.

In this part we will join CoffeeScript, LocalStorage and jQuery to create a simple contact manager where we can save someone's number, name and also check if that person is a friend, and with the help of LocalStorage this contact manager will save your contacts when you refresh your page.

You can see the demo of what we will be creating in this demo I built.

The HTML

As you saw in the demo, our HTML will be the form and a simple empty <ul> that we will fill later with the names and numbers:

<form action="#" method="POST">
<label for="name">Name:</label>
<input type="text" name="name" id="name" required autofocus />
<label for="number">Number</label>
<input tpe="tel" name="number" id="number" required />
<label for="friend">Is he a friend?</label>
<input type="checkbox" name="friend" id="friend">
<input type="submit" id="submit" value="Add" />
</form>
<ul id="numbers"></ul>

Even though this form has a method and action we will later block the default action with JavaScript to stop it actually reloading the page and jumping when it is submitted. Instead we'll just fill the numbers unordered list with what is in the form's inputs.

The CoffeeScript

Now we will get into the best part of this article: talking about CoffeeScript and jQuery together, two tools that were made to make our JavaScript development simpler and more productive.

Let's think about what we want this app to do in bullet points before the coding:

  • Add the class checked if the checkbox is checked and remove it if not;
  • check for a click event on the submit button;
  • get the values of the number and name;
  • place these values on our page;
  • add all the names and numbers to LocalStorage;
  • delete everything we have typed into the form;
  • prevent the form submitting;
  • read and display any data held in LocalStorage.

Now we've got all of this straight we can start from the top. To add the checked class we need to check for a click and then toggle the class on every single class, we have already seen how to construct functions in CoffeeScript in part 1, so:

$('#friend').click -> $(this).toggleClass 'checked'

The next thing we need to is check for a click on the submit button and store some variables that we will be needing further down the road:

$('#submit').click ->
 ul = $('#numbers')
 number = $('#number').val()
 name = $('#name').val()

In this step we have defined our function and the variables we need later, the ul variable holds the unordered list that will contain all the names and numbers and the next two will store whatever we type on the inputs.

This is the part where we grab all the values we have and prepend a list item for each number we have. Remember we want to style things a little bit differently if the contact is a friend, so we will check the class of the checkbox and add different classes to our list items accordingly. For that we will use a simple if statement as described in part 1:

if $('#friend').hasClass 'checked'
$(ul).prepend '<li class="friend"><span>Name: ' + name + '<br/> Number: ' + number + '</span></li>'
else
$(ul).prepend '<li><span>Name: ' + name + ' <br/>Number: ' + number + '</span></li>'

The base of our app is ready but if you reload the page you will see that all the numbers are gone, so we need to add the contents of the numbers to LocalStorage and we will call it contacts:

localStorage.setItem 'contacts', $(ul).html()

What we are doing is naming what we want to save first, and then after the comma we declare the value to be saved. in this case we will save the contents of the unordered list.

With this line done, we have all the numbers and names in LocalStorage so let's add the final touches to the function by resetting the form and then returning false to ensure the page doesn't reload:

$("form")[0].reset()
return false 

The function is now complete and all we need to do now is check if we have something in LocalStorage with the name of contacts and if we do we just need to place that on the page:

if localStorage.getItem 'contacts'
 $('#numbers').html localStorage.getItem 'contacts'

All we are doing is checking and then placing the contents of that item on the page. With this last touch our little contact manager is done and the full CoffeeScript code used was:

$('#friend').click -> $(this).toggleClass 'checked'

$('#submit').click ->
ul = $('#numbers')
number = $('#number').val()
name = $('#name').val()
if $('#friend').hasClass 'checked'
$(ul).prepend '<li class="friend"><span>Name: ' + name + '<br/> Number: ' + number + '</span></li>'
else
$(ul).prepend '<li><span>Name: ' + name + ' <br/>Number: ' + number + '</span></li>'
localStorage.setItem 'contacts', $(ul).html()
$("form")[0].reset();
return false

if localStorage.getItem 'contacts'
$('#numbers').html localStorage.getItem 'contacts'

And if we run this code through the compiler we end up with the following JavaScript:

$('#friend').click(function() {
return $(this).toggleClass('checked');
});

$('#submit').click(function() {
var name, number, ul;
ul = $('#numbers');
number = $('#number').val();
name = $('#name').val();
if ($('#friend').hasClass('checked')) {
$(ul).prepend('<li class="friend"><span>Name: ' + name + '<br/> Number: ' + number + '</span></li>');
} else {
$(ul).prepend('<li><span>Name: ' + name + ' <br/>Number: ' + number + '</span></li>');
}
localStorage.setItem('contacts', $(ul).html());
$("form")[0].reset();
return false;
});

if (localStorage.getItem('contacts')) {
$('#numbers').html(localStorage.getItem('contacts'));
}

Compare both we can see that the CoffeeScript has 587 words and 14 lines while the Javascript one has 662 words and 21 lines, and if we compare legibility we can see that the CoffeeScript is substantially more legible than the JavaScript equivalent. If in this type of simple application CoffeeScript can save you 7 lines of code imagine how much it would save in full blown application!

Conclusion

I hope this article has given you a better idea of CoffeeScript and how it can improve your day-to-day JavaScript coding. The code written in this article isn't meant to be cleanest or easiest JavaScript, rather it was intended to illustrate using CoffeeScript. I hope now that you can see how powerful it is with jQuery and you consider using this great little language in your daily coding because it will most definitely save you hours of typing.

Do you use CoffeeScript? How useful do you find it day-to-day? Let us know in the comments.

Featured image/thumbnail, coffee image via Shutterstock.

Sara Vieira

Sara Vieira is a freelance Web Designer and Developer with a passion for HTML5/CSS3 and jQuery. You can follow her on twitter or check out her website.

Read Next

3 Essential Design Trends, November 2024

Touchable texture, distinct grids, and two-column designs are some of the most trending website design elements of…

20 Best New Websites, October 2024

Something we’re seeing more and more of is the ‘customizable’ site. Most often, this means a button to swap between…

Exciting New Tools for Designers, October 2024

We’ve got goodies for designers, developers, SEO-ers, content managers, and those of you who wear multiple hats. And,…

15 Best New Fonts, September 2024

Welcome to our roundup of the best new fonts we’ve found on the web in the previous four weeks. In this month’s edition…

3 Essential Design Trends, October 2024

This article is brought to you by Constantino, a renowned company offering premium and affordable website design You…

A Beginner’s Guide to Using BlueSky for Business Success

In today’s fast-paced digital world, businesses are always on the lookout for new ways to connect with their audience.…

The Importance of Title Tags: Tips and Tricks to Optimize for SEO

When it comes to on-page SEO, there’s one element that plays a pivotal role in both search engine rankings and user…

20 Best New Websites, September 2024

We have a mixed bag for you with both minimalist and maximalist designs, and single pagers alongside much bigger, but…

Exciting New Tools for Designers, September 2024

This time around we are aiming to simplify life, with some light and fast analytics, an all-in-one productivity…

3 Essential Design Trends, September 2024

September's web design trends have a fun, fall feeling ... and we love it. See what's trending in website design this…

Crafting Personalized Experiences with AI

Picture this: You open Netflix, and it’s like the platform just knows what you’re in the mood for. Or maybe you’re…

15 Best New Fonts, August 2024

Welcome to August’s roundup of the best fonts we’ve found over the last few weeks. 2024’s trend for flowing curves and…