web design cyprus

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

View Compiled

DOM Ready

$ ->
  console.log("DOM is ready")

View Compiled

Call Method with No Params

$(".submit").click ->
  console.log("submitted!")

View Compiled

Call Method with One Param

$(".button").on "click", ->
  console.log("button clicked!")

View Compiled

Call Method With Multiple Params

$(document).on "click", ".button2", ->
  console.log("delegated button click!")

View Compiled

Params in the Anonymous Function

$(".button").on "click", (event) ->
  console.log("button clicked!")
  event.preventDefault()

View Compiled

Returning False

$(".button").on "click", ->
  false

View Compiled

A Simple Plugin

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

View Compiled

Using Plugin

$("a").makeColor
   color: "green"

View Compiled

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}"

View Compiled

Animation

Two ways.

div.animate {width: 200}, 2000

div.animate
  width: 200
  height: 200
  2000

View Compiled

Animation with Callback

div.animate
  color: red
  2000
  ->
    doSomething()

View Compiled

Chaining

Not too much different.

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

View Compiled

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)

View Compiled

Fat Arrow to Retain `this`

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

$(".button").click ->
  setTimeout ( =>
    $(@).slideUp()
  ), 500