am-rails
am-rails

Reputation: 1473

How to Hide an Element using Jquery and Coffeescript in Rails?

I would like to hide an element in a page on my Rails site, but I'm not yet that familiar with Jquery or Coffeescript.

This code works in the console:

$('#TheButton').click(function(){$('#TheText').toggle()});

I then converted it to Coffescript:

$("#TheButton").click ->
  $("#TheText").toggle()

But it doesn't work on my Rails page. How do I fix it? Below is the generated javascript file:

(function() {
jQuery(function() { 
# stuff... 
  });

  $('form').on('click', '.add_fields', function(event) {
  # stuff... 
  });

  $("#TheButton").click(function() {
    return $("#TheText").toggle();
  });

}).call(this);

Upvotes: 0

Views: 2580

Answers (3)

Chris Aitchison
Chris Aitchison

Reputation: 4654

Add

$ ->

Before your code to ensure it runs after the DOM is loaded.

Upvotes: 0

Evan Hahn
Evan Hahn

Reputation: 12712

jQuery's selectors don't work until after the page is loaded. You'll need to make sure your code runs after the document is ready:

$(document).ready ->

  $("#TheButton").click ->
    $("#TheText").toggle()

  # other stuff you want to happen after document load

Upvotes: 0

Ven
Ven

Reputation: 19039

If your JS files are embedded at the top of your layout, every file you have must be wrapped in that jQuery call

Upvotes: 2

Related Questions