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

Apple Opts for AR over VR at WWDC

An Apple VR headset has been one of the most widely-rumored devices of the last few years, and it was finally settled a…

Exciting New Tools for Designers, June 2023

We’re halfway through 2023 already, and the number of incredible apps, tools, and resources for designers is mounting.

3 Essential Design Trends, June 2023

This month we are focusing on three trends within a bigger website design trend – different navigation menu styles and …

15 Best New Fonts, May 2023

The choices you make when selecting a typeface have more impact on your design than almost any other decision, so it’s …

10+ Best Tools & Resources for Web Designers and Agencies (2023 updated)

Having the ability to envision a tastefully designed website (i.e., the role creativity plays) is important. But being …

20 Best New Websites, May 2023

This month, there are tons of great new agency websites to get excited about. 3D animated prisms are a popular theme, a…

How to Find the Right White Label Website Builder for Your Agency

Web design agencies face a lot of obstacles in closing the deal with new clients. One of the most common ones is the ar…

Exciting New Tools For Designers, May 2023

There are hundreds of new tools for designers and developers released each month. We sift through them all to bring you…

3 Essential Design Trends, May 2023

All three of the website design trends here mimic something bigger going on in the tech space, from a desire to have mo…

10 Best AI Tools for Web Designers (2023)

It’s time to stop worrying if AI is going to take your job and instead start using AI to expand the services you can of…

10 Best Marketing Agency Websites (Examples, Inspo, and Templates!)

Marketers are skilled in developing strategies, producing visual assets, writing text with high impact, and optimizing …

15 Best New Fonts, April 2023

Fonts are a designer’s best friend. They add personality to our designs and enable fine typography to elevate the quali…