Perry Horwich Perry Horwich - 3 months ago 8
Javascript Question

Rails 4 Bootstrap3 Dropdown works, then doesn't work

I put this dropdown on Page A:

<span class="dropdown">
<button id="dLabel" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown trigger
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dLabel">
<li>This
<li>That
</ul>
</span>


... and it works just fine.

When I browse to page B and then browse back to page A, the dropdown is seen on the page, but clicking on the dropdown no longer expands the dropdown window. It's as if some aspect of javascript no longer works.

The console in developer tools shows no error and the rails server log shows no error.

If I then stay on Page A and reload the page, the dropdown works. The issue is consistently reproducible.

I am not even sure where to start looking to fix this sort of problem. If a simple fix is not immediately apparent, how about an approach to narrowing the problem down? Many thanks.

My application.js file contains this:

//= require jquery
//= require jquery-ui/sortable
//= require jquery_ujs
//= require jquery.turbolinks
//= require turbolinks
//= require bootstrap-sprockets
//= require cocoon
//= require steps.js.coffee
//= require protocols.js.coffee
//= require retina-1.1.0.js
//= require ie10-viewport-bug-workaround.js


UPDATE:

The answer from luissimo fixes the above problem. Clicking on the dropdown now always works. However, this has uncovered a new issue. The dropdwon window displays properly. When I browse to Page B and then back to page A, the dropdown is offset as seen here:

enter image description here

enter image description here

Is there a more fundamental root cause to this trouble?

UPDATE:

changing:

<span class="dropdown">


to:

<span class="btn dropdown">


... fixed the offset problem.

Answer

It's because Turbolinks causes a page:change event to occur each time a link is clicked and because of that it reevaluates the Javascript every time. Thats why it works at first but when you change pages it might disfunction. This is the easiest work around for it.

 <script>
   $('#dLabel').dropdown()
 </script>

You can also add data-turbolinks-eval=false to the application.js <script> tag to interrupt the reevaluation after clicking on links.

Comments