Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-3.1coffeescript

Hiding my rails div using JS


My products view:

<a href="#" id="show_metrics">Show Metrics</a>
  <div id="metrics" class="hidden">
<%="Number of Primary Products: #{Product.total_product_size(rating_set).count}"%><br/>
<%="Number of Recommendations: #{Product.total_recommendation_size(rating_set).count}"%><br/>
<%="Percentage of Bad Recommendations: #{bad}/#{total} = #{number_to_percentage(percentage_bad, :precision => 2)}"%>
</div>

products.js.coffee:

$ ->
  $("a#show_metrics").click (event) ->
    event.preventDefault()
    $("div#metrics").toggle()

The "Show Metrics" link shows on my view, however nothing happens when the link is clicked, however when I view my page source I see my metrics div as a hidden value. What do I need to change to show the metrics info when the "Show Metrics" link is clicked.

Generated HTML:

<div id="metrics" class="hidden">
Number of Primary Products: 5
<br>
Number of Recommendations: 105
<br>
Percentage of Bad Recommendations: 0/0 = NaN%
</div>

Generated JS:

(function() {
$(function() {
return $("a#show_metrics").click(function(event) {
event.preventDefault();
return $("div#metrics").show();
});
});
}).call(this); 

Solution

  • I think you can just do:

    $("div#metrics").removeClass("hidden")
    

    so add it to your code like this:

    $ ->
      $("a#show_metrics").click (event) ->
        event.preventDefault()
        $("div#metrics").removeClass("hidden")
    

    conversely, if you want to hide it you'll do:

    $("div#metrics").addClass("hidden")