0

Basically my question is an extension of Bootstrap Collapse - open the given id fragment and Rails 4: how to use $(document).ready() with turbo-links:

The difference is, that I need to open an accordion that is linked from within the same view.

I have a page with lots of information that is grouped using Bootstrap Accordions. The accordions look like the following:

# view_xyz.html.haml
.accordion#accId2
  .accordion-group

    .accordion-heading#Heading1
      %a.accordion-toggle{'data-toggle' => 'collapse', 'data-parent' => '#accId2', :href => '#Heading1_'}
        Heading 1
    .accordion-body.collapse#Heading1_
      .accordion-inner
        %p
          Content 1

    .accordion-heading#Heading2
      %a.accordion-toggle{'data-toggle' => 'collapse', 'data-parent' => '#accId2', :href => '#Heading2_'}
        Heading 2
    .accordion-body.collapse#Heading2_
      .accordion-inner
        %p
          Content 2

    ...

    .accordion-heading#HeadingN
      %a.accordion-toggle{'data-toggle' => 'collapse', 'data-parent' => '#accId2', :href => '#HeadingN_'}
        Heading N
    .accordion-body.collapse#HeadingN_
      .accordion-inner
        %p
          Content N
         = link_to('Heading 1', view_xyz_path(anchor: :Heading1))

Now, I want that the browser scrolls to accordion with #Heading1 and opens #Heading1_ when linking to it as shown in accordion #HeadingN.

Basically, I have accomplished that by using the following script as suggested in Bootstrap Collapse - open the given id fragment and Rails 4: how to use $(document).ready() with turbo-links accordingly.

# accordion.js.coffee
collapse = ->
  if (window.location.hash != null)
    $(window.location.hash + '_.collapse').collapse('show')

$(document).ready(collapse)
$(document).on('page:load', collapse)

While this works like a charm when referencing an accordion from every other view it does not work from within view_xyz because the 'page:onload' event does not get fired.

Is there any (elegant) way to make this work using turbolinks and jquery?

P.S.: I've also tried to hook into some other document events - especially 'page:click'. However the problem with 'page:click' is, that at click-time the anchor is not yet part of the referenced element so that the .collapse('show') has nothing to do as the window.location.hash is holding the "before-click" value.

Community
  • 1
  • 1
Ben
  • 301
  • 1
  • 10

1 Answers1

0

Although it is not the perfect solution, adding the hashchange event did the trick for me:

# accordion.js.coffee
collapse = ->

  if (window.location.hash != null)
    #alert('show "' + window.location.hash + '"')
    $(window.location.hash + '_.collapse').collapse('show')

$(document).on('ready page:load', collapse)
$(window).on('hashchange', collapse)
Mark Swardstrom
  • 17,217
  • 6
  • 62
  • 70
Ben
  • 301
  • 1
  • 10