This question already has an answer here:
I can't for the life of me figure this out or find a solution online. I am trying to figure out how to write a script in CoffeeScript from jQuery based JavaScript.
The script is this:
jQuery('.post-thumb a').hover( function() {
jQuery(this).find('.overlay').fadeIn(150);
}, function() {
jQuery(this).find('.overlay').fadeOut(150);
});
I initially tried rewriting that like this:
thumb_overlay =>
$('.post-thumb a').hover
=> $(this).find('.overlay').fadeIn(150)
,=> $(this).find('.overlay').fadeOut(150)
But that didn't work, so I thought I would post here. So how do I write that JavaScript in CoffeeScript?
I think you're almost there but you need some parentheses (to group things) and some backslashes to keep CoffeeScript from misinterpreting the newlines. Try this:
You could also mash it all into one line but you might regret it in a few months:
And BTW, go to the homepage and hit "Try CoffeeScript", that's an easy way to sort small bits of CoffeeScript out; start with the
->
version to cut down on the noise in the JavaScript and then switch to=>
when you get the right JavaScript.I'm not sure if you want to
=>
forms in this case, the->
form form:would give you the the JavaScript that you started with:
And if you don't like backslashes, you could do this:
Or if your functions are longer, you could give them names and skip a lot of the problem:
I tend to prefer this approach in both JavaScript and CoffeeScript, reads better to me.
For those searching for an answer in 2014 CoffeeScript,
compiles into