1

I have a button which is always present in the html, but by default is hidden with the css #comments_button{ display: none; }.

I want the button to appear if the notice has any comments. In _notice.html.erb:

<%= button_tag "Comments", id: "comments_button" do %>
  <span>Comments</span>
<% end %>

<% if notice.comments.any? %>
  *** get jQuery to do $("#comments_button").show(); ***
<% end %>

How do you call the jQuery from inside the ruby if/else loop?

Please note, the button should always be present in the html so I can't do this:

<% if notice.comments.any? %>
  <%= button_tag "Comments", id: "comments_button" do %>
    <span>Comments</span>
  <% end %>
<% end %>

2 Answers 2

1

you can insert script tag in erbs, e.g. following should work

<%= button_tag "Comments", id: "comments_button" do %>
  <span>Comments</span>
<% end %>

<% if notice.comments.any? %>
   <script>
      $("#comments_button").show();
   </script>
<% end %>
Sign up to request clarification or add additional context in comments.

Comments

1

Why use jQuery at all? A far better solutions is do this with just HTML and CSS.

/* application.css */
.hidden {
  display: none;
}

Lets create a helper method which adds the hidden class conditionally:

module CommentsHelper
  def comments_button(comments, opts = {}, &block)
    opts[:id] ||= 'comments_button'
    opts.merge!(class: 'hidden') unless comments.any?
    if block_given?
      button_tag(opts, block)
    else 
      button_tag(content_tag(:span, 'Comments'), opts)
    end
  end
end

<%= comments_button(notice.comments) %>

Note

You should remove this rule from your css:

#comments_button{ display: none; }

Comments

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.