First steps to using jQuery with CoffeeScript

A colleague recently asked me how you typically write the jQuery DomReady and closure syntaxes with CoffeeScript. It’s actually quite simple but did require a bit of fiddling around to find the right recipe. So I thought I’d share this with you all just in case you’re wondering too!

DomReady:

# CoffeeScript
jQuery ($) ->
  # your code here!

// JavaScript
jQuery(function($) {
  // your code here!
});

DomReady v2:

# CoffeeScript
$(document).ready ->
  # your code here!

// JavaScript
$(document).ready(function() {
  // your code here!
});

Passing jQuery into a closure:

# CoffeeScript
(($) ->
  # your code here!
) jQuery

// JavaScript
(function($) {
  // your code here!
})(jQuery);

Bonus: Ternary statements

# CoffeeScript
a = if found then b else c

// JavaScript
a = found ? b : c;

Do you have a recipe for this too? What is it?

Comments are closed.