Grow your CSS skills. Land your dream job.

jQuery with CoffeeScript

Published by Chris Coyier

I don't always write CoffeeScript, but when I do, I'm probably using jQuery too; I always forget the syntax for stuff. So I'm going to write it all down here so I can reference it until I memorize it.

Note that the compiled example doesn't include the automatic closure around everything you get in CoffeeScript.

Safe jQuery Closure

So you can use the $ safely (common in WordPress):

(($) ->
  
) jQuery
(function($) {

})(jQuery);

DOM Ready

$ ->
  console.log("DOM is ready")
$(function() {
  return console.log("DOM is ready");
});

Call Method with No Params

$(".submit").click ->
  console.log("submitted!")
$(".submit").click(function() {
  return console.log("submitted!");
});

Call Method with One Param

$(".button").on "click", ->
  console.log("button clicked!")
$(".button").on("click", function() {
  return console.log("button clicked!");
});

Call Method With Multiple Params

$(document).on "click", ".button2", ->
  console.log("delegated button click!")
$(document).on("click", ".button2", function() {
   return console.log("delegated button click!");
});

Params in the Anonymous Function

$(".button").on "click", (event) ->
  console.log("button clicked!")
  event.preventDefault()
$(".button").on("click", function(event) {
  console.log("button clicked!");
  return event.preventDefault();
});

Returning False

$(".button").on "click", ->
  false
$(".button").on("click", function() {
  return false;
});

A Simple Plugin

$.fn.extend
  makeColor: (options) ->
    settings = 
      option1: "red"
    
    settings = $.extend settings, options
    
    return @each () ->
      $(this).css
        color: settings.color
$.fn.extend({
  makeColor: function(options) {
    var settings;
    settings = {
      option1: "red"
    };
    settings = $.extend(settings, options);
    return this.each(function() {
      return $(this).css({
        color: settings.color
      });
    });
  }
});

Using Plugin

$("a").makeColor
   color: "green"
$("a").makeColor({
  color: "green"
});

Ajax

Note the string interpolation in there too, that's nice.

$.ajax
   url: "some.html"
   dataType: "html"
   error: (jqXHR, textStatus, errorThrown) ->
     $('body').append "AJAX Error: #{textStatus}"
   success: (data, textStatus, jqXHR) ->
     $('body').append "Successful AJAX call: #{data}"
$.ajax({
  url: "some.html",
  dataType: "html",
  error: function(jqXHR, textStatus, errorThrown) {
    return $('body').append("AJAX Error: " + textStatus);
  },
  success: function(data, textStatus, jqXHR) {
    return $('body').append("Successful AJAX call: " + data);
  }
});

Animation

Two ways.

div.animate {width: 200}, 2000

div.animate
  width: 200
  height: 200
  2000
div.animate({
  width: 200
}, 2000);

div.animate({
  width: 200,
  height: 200
}, 2000);

Animation with Callback

div.animate
  color: red
  2000
  ->
    doSomething()
div.animate({
  color: red
}, 2000, function() {
  return doSomething();
});

Chaining

Not too much different.

$("input")
  .val("")
  .css
    'z-index': 5
  .removeClass "fart"
$("input").val("").css({
  'z-index': 5
}).removeClass("fart");

Promises

The last line gets returned here when it doesn't really need to but whatever.

$.when(
  $.get("/feature/", (html) ->
    globalStore.html = html;
  ),
  $.get("/style.css", (css) ->
    globalStore.css = css;
  )
).then -> 
  $("<style />").html(globalStore.css).appendTo("head")
  $("body").append(globalStore.html)
$.when($.get("/feature/", function(html) {
  return globalStore.html = html;
}), $.get("/style.css", function(css) {
  return globalStore.css = css;
})).then(function() {
  $("<style />").html(globalStore.css).appendTo("head");
  return $("body").append(globalStore.html);
});

Fat Arrow to Retain `this`

Otherwise inside the setTimeout you wouldn't have a reference to the button.

$(".button").click ->
  setTimeout ( =>
    $(@).slideUp()
  ), 500
$(".button").click(function() {
  return setTimeout(((function(_this) {
    return function() {
      return $(_this).slideUp();
    };
  })(this)), 500);
});

Here's the lot of them in a Pen if you wanna tinker.

Comments

  1. I’m curious to hear what your thoughts are on Coffee script compared to writing JS. I listened to your talk at Front End Design Conference about SASS and it’s necessary abstraction. Do you feel the same with Coffee Script?

    • I’m curious about this too. I don’t see a huge benefit to using CoffeeScript over JS, compared to the hurdles to jump over (setup compiler, learning new syntax)

    • I agree as well…

      Looking at the code differences between Coffee script and jQuery I only see a savings of a few characters…but I also find the Coffee script much harder to read…

      The brackets in native JS and jQuery help (me at least) understand the code and break the code up into understandable chunks…

      I too do not see the benefit in filling your brain with yet another syntax and adding another set of complexity to your work flow only to save a few keystrokes…

      Just my oppinion…

    • I wasn’t convinced at first, but having used Coffeescript for a few years now, I choose it over Javascript whenever I have the chance. Here are a few reasons:

      I write code faster, and have more time to ensure it is of good quality
      Some complain it makes people sloppy Javascript coders. I don’t think any language can prevent that. Quality code is a discipline, and you can do it with Coffeescript as well as with Javascript. I still spend a lot of time in Javascript, and usually check the generated output.
      I now find the lack of curly braces a benefit. The indentation is easier to see, and I find the syntax more readable than javascript in many situations.
      The only annoyance I have is when I switch languages; I sometimes code one in the other. But I do that with other languages anyway.
      The setup is really not hard. And if you are preprocessing Sass, it is a very small step to add Coffeescript. Nearly nothing if you use Grunt or Gulp or Codekit.

      I’m sure more could be said, but these are a few ideas. Certainly life will go on if you don’t try Coffeescript. I think it is worth a good try. You never know, you may like it a lot.

    • I like to use it in combination with SASS because of their similarity in appearance and indenting syntax.

    • Do you feel the same with Coffee Script?

      I don’t feel like CoffeeScript is as useful to JavaScript as Sass is to CSS. With Sass, that is the primary abstraction. Sass gives you those basic tools of abstraction that are (usually) needed. Those primary abstractions already exist in JavaScript (variables, functions, etc).

      I don’t have very strong feelings about CoffeeScript overall. If you like it and are productive in it, awesome. I would never try and take that away from someone. I dabble in it because I think it’s interesting and fun. I do think its way better for JSON config, e.g. Gruntfile.coffee

    • Алексей Андреевич Соснин

      $(“input”)
      .val “”
      .css ‘z-index’: 5
      .removeClass “fart”

  2. JCD

    Your examples with no, one and many parameters actually have one more parameter than claimed: the -> is an anyonymous function passed as a parameter in those examples.

    For Coffeescript, I guess preference in other languages might matter. If you are used to for instance PHP or Java, the plain Javascript syntax will probably feel more natural. But if you use Python or Ruby a lot, Coffeescript might go down easier.

  3. Ryan

    For some reason I’ve never been able to get into CoffeeScript. I know the syntax is supposed to be concise, but it just looks so weird and is hard to read. I know you get used to anything given time and experience with it, but the fact that you’re making a blog post to help you remember the syntax is a little disconcerting.

    If you’re going to use a JS preprocessor, TypeScript has got my vote!

  4. T.J. Crowder

    You have an OBOE in your post (an Off By One Error). Your “Call Method with No Params” has one argument, “Call Method with One Param” has two, and so on…

  5. Just another way to shoot yourself in the foot :-)

    Why don’t you just memorize, learn and use plain JavaScript, as this is the underlying platform anyways ?

  6. A great example… of how CoffeeScript solves a problem which doesn’t exist!

    I’ve played with CoffeeScript. It seemed neat at first. However, I would never use it on any project where any other developer might ever have to touch it.

    Brackets are good! If your indentation ever gets screwed up for whatever reason, then CoffeeScript doesn’t seem fun anymore…

    • Lucas

      Another reason to write a nice, consistent and well indented code. If CoffeeScript can’t compile it, it means your code is not properly written…

  7. I think JCD nailed it above in that Coffeescript syntax might be more appealing if you’re a Ruby developer. PHP devs will probably like the brackets of plain js/jquery. Same with tools like HAML I think. Still not sure why Jade seems so prevalent for Node/Express apps though.

  8. Great article Chris very informative! I personally use js2coffee to convert my codes.

  9. But still why do we use cofee script ?

  10. Jake
    Permalink to comment#

    I found the confusing part of using js, jquery, and coffee is all the variations of implementing them, and slightly different syntax. Compound this with framework-specific adjustments, (e.g. turbolinks in Rails), it’s pretty hard to have them sink in when you’re learning all of them.

This comment thread is closed. If you have important information to share, you can always contact me.

*May or may not contain any actual "CSS" or "Tricks".