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

20 Best New Websites, April 2024

Welcome to our sites of the month for April. With some websites, the details make all the difference, while in others,…

Exciting New Tools for Designers, April 2024

Welcome to our April tools collection. There are no practical jokes here, just practical gadgets, services, and apps to…

14 Top UX Tools for Designers in 2024

User Experience (UX) is one of the most important fields of design, so it should come as no surprise that there are a…

What Negative Effects Does a Bad Website Design Have On My Business?

Consumer expectations for a responsive, immersive, and visually appealing website experience have never been higher. In…

10+ Best Resources & Tools for Web Designers (2024 update)

Is searching for the best web design tools to suit your needs akin to having a recurring bad dream? Does each…

3 Essential Design Trends, April 2024

Ready to jump into some amazing new design ideas for Spring? Our roundup has everything from UX to color trends…

How to Plan Your First Successful Website

Planning a new website can be exciting and — if you’re anything like me — a little daunting. Whether you’re an…

15 Best New Fonts, March 2024

Welcome to March’s edition of our roundup of the best new fonts for designers. This month’s compilation includes…

LimeWire Developer APIs Herald a New Era of AI Integration

Generative AI is a fascinating technology. Far from the design killer some people feared, it is an empowering and…

20 Best New Websites, March 2024

Welcome to our pick of sites for March. This month’s collection tends towards the simple and clean, which goes to show…

Exciting New Tools for Designers, March 2024

The fast-paced world of design never stops turning, and staying ahead of the curve is essential for creatives. As…

Web Tech Trends to Watch in 2024 and Beyond

It hardly seems possible given the radical transformations we’ve seen over the last few decades, but the web design…