简体   繁体   中英

jquery only works when I refresh the page for toggle for rails app

The toggle action of showing part of a div on my Rails app only works if I refresh the page. If I click on a link to the page, all of the toggles are already open and don't react to clicking. Any help would be greatly appreciated! Also, if anyone has tips on how to test this with Capybara, that would be great.

This in my app/assets/javascripts

$(document).ready(function(){
  $(".donation-time").hide()
  $(".donation-candidate").on("click", function(event){
    $(this).siblings().first().toggle();
    $("span", this).toggleClass("glyphicon-chevron-right glyphicon-chevron-down");
  })
})

This is my partial for the view being used, and it's the part that's completely open and visible instead of just the .donation-candidate being visible after clicking to the page.

<div class="donation-candidate">
  <h3><span class="glyphicon glyphicon-chevron-right"></span> <%= candidate_issue.name %></h3>
  <div style="margin-left: 32px;"><h4><%= candidate_issue.stance %></h4></div>
</div>


<div class="donation-time">
  <div style="margin-left: 32px;">
    <%= form_for Donation.new, url: donations_path do |f| %>
      <%= f.label :amount %>
      <%= f.hidden_field :candidate_issue_id, value: candidate_issue.id %>
      <%= f.number_field :amount, in: 1.0..2700.0, step: 1.0 %>
      <%= f.hidden_field :issue_id, value: candidate_issue.issue_id %>
      <%= f.submit "Donate" %>
    <% end %>
  </div>
</div>

First time using jquery or javascript, so not really sure where to look. If you have tips on how to test with capybara, that would be great. I included js: true in the scenario and included selenium as a gem, but I'm not sure what to do for clicking open the div, since it's not a button or link apparently. Thanks!

Are you using turbolinks? $(Document).ready() requires a workaround with turbolinks, as covered in this post use document ready with turbopinks

Sounds like you probably have turbolinks in your app https://github.com/rails/turbolinks . Turbolinks speeds up page loading by requesting the next page via Ajax and then replacing the body of the page. This means scripts don't have to be reparsed, etc. it also means that .ready functions aren't executed again. You can change your $(document).ready to be

$(document).on('page:change', function(){
  ...
})

If your function is idempotent, otherwise you might want page:load (read the turbolinks docs for details on when each type of event fires), Or you can install jquery-turbolinks or you can disable turbolinks.

For testing you can click on the element with

find(:css, '.donation-candidate').click

The :css may not be needed if you have :css as the default in Capybara

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM