Search code examples
ruby-on-railsajaxruby-on-rails-4colorboxturbolinks

Rails / Turbolinks - Colorbox Not Closing After Navigating to Different Pages


We're using the colorbox-rails gem to show a sign-up page to our users for our Rails 4 application. At the bottom of the popup, we have a link to that saysAlready a member? Login. The Login text redirects the user to our login page.

However, because Rails 4 is using turbolinks, the Login page's html is being loaded with AJAX in the background. This has the effect of loading the Login page behind the colorbox, while the colorbox still remains open.

Here is the html that triggers the colorbox:

<%= link_to 'Sign Up', '/blank/sign_in_helper', class: 'nav-link-box',
                                          :id => 'sign-up-link', :data => {
                                          :colorbox => true}
                                           %>

And the HTML of the colorbox (sign_in_helper):

<h2>Sign Up</h2>

<%= form_for(:user, url: registration_path(:user)) do |f| %>

  <div class="field">
    <%= f.label :name, 'Display Name' %><br />
    <%= f.text_field :name %>
  </div>

  <div class="field">
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true %>
  </div>

  <div class="field">
    <%= f.label :password %>
    <% if @minimum_password_length %>
    <em>(<%= @minimum_password_length %> characters minimum)</em>
    <% end %><br />
    <%= f.password_field :password, autocomplete: "off" %>
  </div>

  <div class="field">
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation, autocomplete: "off" %>
  </div>

  <div class="actions">
    <%= f.submit "Sign up" %>
  </div>

  <p>Already a member? <%= link_to 'Login.', new_user_session_path, class: 'lightbox-close' %> </p>
<% end %>

I've tried binding a colorbox close event to the link (coffeescript), but for some reason it only works the second time the link is clicked:

$('.lightbox-close').click ->
    $.colorbox.close()

Is there a way to do this while still using turbo-links? Or is the best way to disable turbo-links for that specific link?

Thanks!


Solution

  • If you want to disable turbolinks for a certain link add data-no-turbolinks attribute to it

    <%= link_to 'Login.', new_user_session_path, class: 'lightbox-close', data: {no_turbolinks: true} %>
    

    When using turbo links with javascript bindings it's better to execute the code that you used to on document.ready to page:load, for example (given that you're using jquery) in your application.js:

    var ready;
    ready = function(event) {
    
      //code when the page is loaded
    };
    
    $(document).on('ready page:load', ready);