Search code examples
jqueryruby-on-railstwitter-bootstrapturbolinks

Rails: Bootstrap Collapse doesn't work after refresh


I have a simple Bootstrap collapse (as seen working in this fiddle):

<h3>
    <a data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
        OUR NAME</a>
</h3>
<div class="collapse" id="collapseExample">
    <p>
        Stuff about our name.
    <p>
</div>
<h3>
    <a data-toggle="collapse" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
        THE BOTTOM LINE BASICS</a>
</h3>
<div class="collapse" id="collapseTwo">
    <p>
    More words!
    </p>
</div>

I am trying to put it in an "About Us" page. It works fine in JSFiddle, but in my Rails app, I see this behavior:

Load a different page (not About Us), then navigate to the "About Us" page: collapse works fine.

Refresh the "About Us" page: collapse doesn't work.

I figure this has something to do with Turbolinks, but nothing I'm trying is working.


Solution

  • It ended up being interference on the click event caused by this "smooth scrolling" script.

    I fixed it by matching against "collapse":

       $('a[href*=#]:not([href*=#collapse])').click(function() {
          if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
            if (target.length) {
              $('html,body').animate({
                scrollTop: target.offset().top
              }, 1000);
              return false;
            }
          }
        });