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

15 Best New Fonts, July 2024

Welcome to our monthly roundup of the best fonts we’ve found online in the last four weeks. This month, there are fewer…

20 Best New Websites, July 2024

Welcome to July’s round up of websites to inspire you. This month’s collection ranges from the most stripped-back…

Top 7 WordPress Plugins for 2024: Enhance Your Site's Performance

WordPress is a hands-down favorite of website designers and developers. Renowned for its flexibility and ease of use,…

Exciting New Tools for Designers, July 2024

Welcome to this July’s collection of tools, gathered from around the web over the past month. We hope you’ll find…

3 Essential Design Trends, July 2024

Add some summer sizzle to your design projects with trendy website elements. Learn what's trending and how to use these…

15 Best New Fonts, June 2024

Welcome to our roundup of the best new fonts we’ve found online in the last month. This month, there are notably fewer…

20 Best New Websites, June 2024

Arranging content in an easily accessible way is the backbone of any user-friendly website. A good website will present…

Exciting New Tools for Designers, June 2024

In this month’s roundup of the best tools for web designers and developers, we’ll explore a range of new and noteworthy…

3 Essential Design Trends, June 2024

Summer is off to a fun start with some highly dramatic website design trends showing up in projects. Let's dive in!

15 Best New Fonts, May 2024

In this month’s edition, there are lots of historically-inspired typefaces, more of the growing trend for French…

How to Reduce The Carbon Footprint of Your Website

On average, a web page produces 4.61 grams of CO2 for every page view; for whole sites, that amounts to hundreds of KG…

20 Best New Websites, May 2024

Welcome to May’s compilation of the best sites on the web. This month we’re focused on color for younger humans,…