Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Bootstrap and dropdown not working

In my application.html.erb, I have the following:

<head>
  <title><%= title %></title>
  <%= stylesheet_link_tag "application", media: 'all' %>
  <%= javascript_include_tag "application" %>
  <%= javascript_include_tag "https://js.stripe.com/v1/", "application" %>
  <%= csrf_meta_tags %>
  <%= tag :meta, :name => "stripe-key", :content => STRIPE_PUBLIC_KEY %>
  <%= javascript_include_tag "http://twitter.github.com/bootstrap/assets/js/bootstrap-dropdown.js", "application" %>
  <%= render 'layouts/shim' %>
</head>

In my gemfile, I have the following:

gem 'twitter-bootstrap-rails'
gem 'bootstrap-datepicker-rails'

In my views\layouts_header.html.erb, I have:

  <li class="dropdown" id="admin_menu">
    <a class="dropdown-toggle" data-toggle="dropdown" data-target="#admin_menu">
      <%= ADMIN_TITLE %>
      <b class="caret"></b>
    </a>
    <ul class="dropdown-menu">
      <% Admin_menu.each do |menu_text, menu_action| %>
          <li><a href="<%= menu_action %>"><%= menu_text %></a></li>
      <% end %>
    </ul>
  </li>

Admin_menu is defined elsewhere as: Admin_menu = Hash.new Admin_menu["Papers"] = "/papers" Admin_menu["Tracks"] = "/tracks" Admin_menu["Attendance"] = "/attendance"

When I click on the caret, nothing happens. I checked the HTML code, and the dropdown menu selections are there.

Any ideas?

like image 231
EastsideDev Avatar asked Aug 08 '12 14:08

EastsideDev


1 Answers

You need to change these lines:

<%= javascript_include_tag "application" %>
<%= javascript_include_tag "https://js.stripe.com/v1/", "application" %>
<%= javascript_include_tag "http://twitter.github.com/bootstrap/assets/js/bootstrap-dropdown.js", "application" %>

to this:

<%= javascript_include_tag "https://js.stripe.com/v1/" %>
<%= javascript_include_tag "application" %>

Your current code includes application.js many times, which is a problem for Bootstrap's dropdown code. I'll bet if you look in your application.js file, you'll see this near the top:

//= require bootstrap

That would mean you're loading bootstrap once every time you include application.js, then again from github.

If you read Bootstrap's Dropdown JS code, you'll see it adds a click listener to toggle the dropdown menu. If you run this code twice, you're adding two click listeners. So on every click, those two listeners open the menu and suddenly close it again.

I had a problem similar to yours, where I didn't notice that my javascript_include_tag for Stripe was also re-including application. I guess we probably copy/pasted from the same place!

like image 186
Paul A Jungwirth Avatar answered Sep 21 '22 04:09

Paul A Jungwirth