4

I have a rails app which displays steps and substeps in rows. I'm looking to create an action where clicking on a step row will change it's class from 'step_container' to 'step_container active', and then show the corresponding substep rows for that step. I have had a difficult time figuring out how to use AJAX (or understanding if that is the best tool) to accomplish this.

<% @steps.each do |step| %>
      <div class="step_container"> <!-- add 'active' if clicked-->
        <div class="medium-8 columns"><!-- add 'active_container' if clicked-->
          <div class="medium-5 columns step_info">
            <div class="step_number">
              <span><%= step.order %></span>
            </div>
            <div class="custom_step">
              <span class="step_title"><%= step.title %> (custom step)</span>
              <span class="step_desc"><%= step.description %></span>
            </div>
          </div>
        </div>

        <!-- Only show this div if top div is clicked -->
        <div class="medium-4 columns sub_steps_container">
          <% @substeps.where(step_id: step.id).each do |substep| %>
                  <div class="sub_steps">
                    <div class="step_number">
                      <span><%= substep.order %></span>
                    </div>
                    <div class="">
                      <span class="step_title"><%= substep.action %></span>
                      <span class="step_desc"><%= substep.description %></span>
                    </div>
                  </div>
          <% end %>
        </div>
      </div>
  <% end %>

Thanks in advance for assistance. This has taken me most of the day with limited results.

Ron M
  • 773
  • 2
  • 10
  • 22

2 Answers2

5

There is no need for AJAX here, just little bit of javascript and css.

JavaScript:

$('.step_container').click(function() {
  $(this).addClass('active');
}

CSS (sass):

.step_container {
  .sub_steps_container {
    display: none;
  }

  &.active {
    .sub_steps_container {
      display: block;
    }
  }
}
BroiSatse
  • 44,031
  • 8
  • 61
  • 86
  • Thank you for the solution! Worked wonderfully and is very simple. – Ron M Dec 15 '15 at 02:25
  • Also wanted to note that I needed to wrap my call in $(document).ready(function() { ... }); to get around the turbolinks issues (http://stackoverflow.com/questions/18770517/rails-4-how-to-use-document-ready-with-turbo-links) – Ron M Dec 15 '15 at 02:40
2

If I understand you correctly, you won't actually need Ajax for this. This could be pretty simple:

Hide the sub_step_container div initially via css.

.sub_steps_container {
  display: none;
}

Add this to your HTML code (or better yet, don't use script tags and use in separate JS file).

<script>
  $('.step_container').on('click', function(){
    $(this).addClass('active');
    $('.sub_steps_container').show()
  });
</script>
Ryan Rebo
  • 1,278
  • 2
  • 13
  • 27