0

Right now I loop through my RoR objects and create a new jquery function for each separate object. I understand this is extremely inefficient and amateurish, and I would like to have just one jquery function that handles this operation.

<% @startups.each do |startup| %>
  <div class="panel-body showVideo<%=startup.id%>">
  ...
  </div>
  <div class="panel-body theVideo<%=startup.id%>">
  ...
  </div>
  <script type="text/javascript">
    $(function () {
      $('.theVideo<%=startup.id%>').hide();
      $('.showVideo<%=startup.id%>').on('click', function () {
        $('.theVideo<%=startup.id%>').show();
        $('.showVideo<%=startup.id%>').hide();
      });
    });
  </script>
<% end %>

Basically this code waits for a user to click the div, and hides that div while showing another div. The code currently works, but I don't want to create tons of functions when it could be one!

1 Answer 1

1

I think you just need to give the JS access to your IDs. You could do that by writing them into your HTML like this:

<script type="text/javascript">
  // Write the IDs into the script tag
  var ids = [ <% @startups.each do |startup| %>
    <%=startup.id%>,
  <% end %>];
  // Loop over the IDs
  for (var i=0; i<ids.length; i++) {
    var id = ids[i];
    // Do your stuff here
  }
</script>

Of course add some logic to make sure not to add a comma to the last one.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your help. I understand your concept, but I'm still not sure how to implement seeing as though I need to actually post the div's (One div that shows on page load, and one that shows when you click the first div)
What do you mean by "post the divs"?
Sorry for the confusion. What I mean is, I need to actually output the html. Do I do that in the javascript or outside of the JS script? Just not sure how to actually implement everything.
Well, you could certainly do it either way. If most of your app is in rails, I would just keep doing things that way and write out all the divs in rails.

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.