0

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?

1

1 Answer 1

1

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'
Sign up to request clarification or add additional context in comments.

4 Comments

I really don't like turbolinks (for many reasons, which I won't discuss here), so I'm looking for a way to do page-specific loading.
If you're not using turbolinks, then you can just put a script tag in your view itself that does document.ready(function() {$('#mydiv').addClass('active');};
I'd like to avoid inline scripts in my view, as it will not be precompiled in the assets, and slows down page loading
If you put the script at the bottom and use document.ready(function() {...}); then it shouldn't really slow down the page load. It's a pretty minimal amount of code to worry about precompiling, but YMMV.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.