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?
CoffeeScript tends to run as fast, or faster than hand-written JavaScript.
CoffeeScript is a lightweight language that compiles into JavaScript. It provides simple and easy to learn syntax avoiding the complex syntax of JavaScript.
The syntax of function in CoffeeScript is simpler as compared to JavaScript. In CoffeeScript, we define only function expressions. The function keyword is eliminated in CoffeeScript. To define a function here, we have to use a thin arrow (->).
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:
thumb_overlay => $('.post-thumb a').hover \ (=> $(this).find('.overlay').fadeIn(150)), \ (=> $(this).find('.overlay').fadeOut(150))
You could also mash it all into one line but you might regret it in a few months:
thumb_overlay => $('.post-thumb a').hover (=> $(this).find('.overlay').fadeIn(150)), (=> $(this).find('.overlay').fadeOut(150))
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:
$('.post-thumb a').hover \ (-> $(this).find('.overlay').fadeIn(150)), \ (-> $(this).find('.overlay').fadeOut(150))
would give you the the JavaScript that you started with:
$('.post-thumb a').hover((function() { return $(this).find('.overlay').fadeIn(150); }), (function() { return $(this).find('.overlay').fadeOut(150); }));
And if you don't like backslashes, you could do this:
$('.post-thumb a').hover( -> $(this).find('.overlay').fadeIn(150) -> $(this).find('.overlay').fadeOut(150) )
Or if your functions are longer, you could give them names and skip a lot of the problem:
fadeIn = -> $(this).find('.overlay').fadeIn(150) fadeOut = -> $(this).find('.overlay').fadeOut(150) $('.post-thumb a').hover(fadeIn, fadeOut)
I tend to prefer this approach in both JavaScript and CoffeeScript, reads better to me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With