Dave Tsay
Dave Tsay

Reputation: 409

Jquery not working in Coffeescript function Rails

I'm new to coffee script, so forgive me if this is a simple problem.

I'm trying to make a simple class change when a specific view is loaded in Rails. Specifically I want to run:

$(#mydiv).addClass('active')

In my coffee script, I have the following:

class MyApp.Sessions extends MyApp.Base
  constructor:() ->
    super  # call Base class for core functionality
    this   # and be sure to return this

  index:() -> 
    $ -> 
        $('#mydiv').addClass('active')

but the resulting javascript ends up placing my Jquery command outside of the function:

Sessions.prototype.index = function() {
  return $(function() {});
};

$('#mydiv').addClass('active');

Any ideas?

Upvotes: 0

Views: 534

Answers (1)

Brian Glick
Brian Glick

Reputation: 2201

This seems really complicated. If you only want to set a class when a page is loaded, then the answer depends on if you're using Turbolinks from Rails 4.

With turbolinks, you could just hook into the page:load event like

document.on 'page:load', () ->
  $('#mydiv').addClass 'active'

Upvotes: 1

Related Questions