Skip to content

Instantly share code, notes, and snippets.

@dmonopoly
Created December 23, 2011 04:35
Show Gist options
  • Save dmonopoly/1513155 to your computer and use it in GitHub Desktop.
Save dmonopoly/1513155 to your computer and use it in GitHub Desktop.
How do you convert this animate method of jQuery to CoffeeScript?
$('#book').animate({
opacity: 0.25,
left: '+=50',
height: 'toggle'
}, 5000, function() {
// Animation complete.
});
@TrevorBurnham
Copy link

Here's how I'd do it:

$('#book').animate {
    opacity: 0.25
    left: '+=50'
    height: 'toggle'
  }, 5000, ->
    # Animation complete.

@dmonopoly
Copy link
Author

What about this?

$("#clickable a").click(function(e) {
   e.stopPropagation();
})

@showell
Copy link

showell commented Dec 29, 2011

Check out js2coffee (http://js2coffee.org/). It translates the above as follows:

$("#clickable a").click (e) ->
  e.stopPropagation()

I think this is the most idiomatic translation, and I'm 99.9% sure it's correct (but untested, of course).

For more complicated cases, js2coffee occasionally stumbles on edge cases, but it's a good tool to remove some of the drudgery. I often use js2coffee for an initial translation, then I manually fix some style things.

@dmonopoly
Copy link
Author

Thanks! I'll be sure to use that link and your advice in the future.

@suhaotian
Copy link

$('#book').animate
opacity: 0.25
left: '+=50'
height: 'toggle'
5000, ->
# Animation complete. ;)

@SteveBenner
Copy link

SteveBenner commented Jun 13, 2019

I am a big fan of the clean style demonstrated by CSS Tricks. Currently my preference is to code more horizontally, so for instance I would write a 3-part .animate() chain with callbacks like this:

$('#hero-section').animate height: '0px', paddingBottom: '0px', ->
  $('#featured-content').animate opacity: '0', ->
    $('.main-content-wrapper').animate paddingTop: '25vh'

Note: It should not be overlooked that jQuery is awesome and allows one to leave out the duration parameter, which is normally the 2nd argument to .animate(), as demonstrated in other examples online. The default behavior is to accept a callback function as the final parameter, so you don't actually have to include duration if you don't want to.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment