Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change div class on click in Rails app

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.

like image 948
Ron M Avatar asked Sep 11 '25 16:09

Ron M


2 Answers

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;
    }
  }
}
like image 52
BroiSatse Avatar answered Sep 13 '25 04:09

BroiSatse


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>
like image 29
Ryan Rebo Avatar answered Sep 13 '25 06:09

Ryan Rebo