In the initial segment on CoffeeScript, you uncovered its fundamental features. Clearly, though, in contemporary web development we frequently depend on jQuery as a crutch to streamline our JavaScript tasks, and the material you learned previously was strictly basic JavaScript.
This segment will showcase an integration of CoffeeScript, LocalStorage, and jQuery to construct an elementary contact manager. This tool allows for the storage of contact information such as phone numbers and names and labels contacts as friends. Leveraging LocalStorage, this application will remember your contacts even after you’ve refreshed your browser page.
Experience the functionality of the tool through this interactive example I’ve crafted.
HTML Structure
Examining the demonstration, you’ll notice that our HTML consists simply of a form and an initially empty <ul>, which we will populate with contact details subsequently:
<form action="#" method="POST">
<label for="name">Name:</label>
<input type="text" name="name" id="name" required autofocus />
<label for="number">Number</label>
<input type="tel" name="number" id="number" required />
<label for="friend">Friend status:</label>
<input type="checkbox" name="friend" id="friend">
<input type="submit" id="submit" value="Add" />
</form>
<ul id="contacts"></ul>
Although our form is configured with a method and action, we will later intercept the form submission using JavaScript, to prevent the default behavior of reloading the page.
Delving Into CoffeeScript
Now, let’s dive into the best part: CoffeeScript’s synergy with jQuery. These tools aim to optimize our JavaScript development process.
Prior to coding, here’s a rundown of our application’s objectives:
- Toggle the class checked based on the checkbox state;
- Detect a click event on the submit button;
- Retrieve values from input fields;
- Display these values on the webpage;
- Store contact data in LocalStorage;
- Clear form inputs;
- Prevent the form from submitting;
- Load and show any stored data from LocalStorage.
With a clear plan, we start by toggling the checked class via a click event:
$('#friend').click -> $(this).toggleClass 'checked'
Next up is capturing clicks on the ‘Add’ button to establish key variables for later use:
$('#submit').click -> ul = $('#contacts') number = $('#number').val() name = $('#name').val()
At this juncture, we’ve outlined our function and the variables that will serve us going forward. The ul variable represents the list that will display our contacts, while the other two variables capture data from input fields.
Now we append a new list item for each contact. We’ll vary the style for friends using a basic if statement:
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 contact manager’s foundation is set, but your data would vanish upon reload. So, we’ll store our contacts in LocalStorage:
localStorage.setItem 'contacts', $(ul).html()
This line ensures all data is preserved in LocalStorage. We’ll complete our function by resetting the form entries and preventing the form submission:
$("form")[0].reset() return false
The last step is to examine if LocalStorage contains any saved ‘contacts’ data and display it accordingly:
if localStorage.getItem 'contacts' $('#contacts').html localStorage.getItem 'contacts'
With that, the simple yet effective contact manager project reaches completion. The comprehensive CoffeeScript code looks like this:
$('#friend').click -> $(this).toggleClass 'checked'
$('#submit').click ->
ul = $('#contacts')
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'
$('#contacts').html localStorage.getItem 'contacts'
The converted JavaScript reads:
$('#friend').click(function() {
return $(this).toggleClass('checked');
});
$('#submit').click(function() {
var name, number, ul;
ul = $('#contacts');
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')) {
$('#contacts').html(localStorage.getItem('contacts'));
}
Reviewing both scripts highlights the succinctness and readability of CoffeeScript over its JavaScript counterpart. Imagine the efficiencies to be gained in a larger application when even this simple one benefits from brevity and clarity.
Final Thoughts
I trust this exploration has provided you a glimpse into the practicality of CoffeeScript in daily web development tasks. The sample code isn’t the epitome of JavaScript elegance, but serves as an example of CoffeeScript practice. Its potency with jQuery is evident, and incorporating this compact language into your workflow may very well save you considerable time.
Is CoffeeScript part of your development toolkit? Share your experiences and its daily application benefits in the comments below.
Featured image/thumbnail, coffee image via Shutterstock.