Search code examples
ruby-on-railscoffeescriptmaterialize

Rails Materializecss, coffeescript function is not defined


I have the following code in JavaScript which work

function displayButton() {
 var options = [
  {
   selector: '#news', 
   offset: 20, 
   callback: function(el) {
     $('#more-video-btn').hide();
     $('#more-news-btn').show();
   }
  },
  {
   selector: '#video', 
   offset: 20, 
   callback: function(el) {
     $('#more-news-btn').hide();
     $('#more-video-btn').show();
   }
  }
 ];

 Materialize.scrollFire(options);
}

and try to convert in to CoffeeScript

what I did is that

displayButton = () ->
  options = [
    selector: '#news'
    offset: 20
    callback: (el)->
      $('#more-video-btn').hide()
      $('#more-news-btn').show()
  ,
    selector: '#video'
    offset: 20
    callback: (el)->
      $('#more-news-btn').hide()
      $('#more-video-btn').show()
  ]

  Materialize.scrollFire(options)

When I call the displayButton from a view

<script type="text/javascript">
  $(window).scroll(function(e) {
    displayButton();
  });
</script>

I get 'displayButton is not defined'.

It is first time I try to write something in CoffeeScript and I have no idea why the displayButton is not defined.

Please help me


Solution

  • It all seems fine to me. The only thing I see that could be a problem is the scope. Maybe try window.displayButton = -> or @displayButton = ->. That way they should be available there.

    The next question I'd have is what gems you have installed (need coffee-rails) and where your coffee file is.