Search code examples
jqueryruby-on-railscoffeescriptwaitforimages

How would I write this in CoffeeScript?


I'm having trouble with CoffeeScript in my first Rails application. I'm using the waitForImages jQuery plugin, which is saved in a separate file called waitforimages.jquery.js. Rails automatically created home.js.coffee, in which I'd like to include the following jQuery snippet:

$('#fullbleed').waitForImages(function() {
    $(this).fadeIn(3000);
});

But how would I write this using CoffeeScript notation?

UPDATE

Things are working great now, so I thought I would post my final code. One of the issues was that I wasn't loading the waitForImages plugin before home.js.coffee.

CoffeeScript:

$(document).ready -> $('#fullbleed').waitForImages -> $(@).fadeIn 3000

HTML:

<!DOCTYPE html>
<html>
<head>
  <title>Title</title>
  <script src="/assets/jquery.js?body=1" type="text/javascript"></script>
  <script src="/assets/jquery_ujs.js?body=1" type="text/javascript"></script>
  <script src="/assets/jquery.waitforimages.js?body=1" type="text/javascript"></script>
  <script src="/assets/home.js?body=1" type="text/javascript"></script>
</head>
<body>
...
</body>
</html>

Solution

  • Use -> ... instead of function(){ ... }. Optionally, you can also swap this with @.

    $('#fullbleed').waitForImages ->
        $(@).fadeIn(3000)
    

    If you really like to save characters, then you can also omit the last two parentheses, and get:

    $('#fullbleed').waitForImages -> $(@).fadeIn 3000