Rails PJAX and Twitter Bootstrap plugins don't play nicely

Hey so I am using Rails PJAX for my web app with twitter bootstrap JQuery Plugins. I can't seem to get both to work together. So, for example, I have pagination and some hover effects on some elements.

When I initially reload the page and hover over everything it works. When I click on the next page on the page, the dates are on the page, and then when I hover over it doesn't work. Logically I would think because the DOM has already been loaded once. What can I do?

Also note that using Rails Pjax in a Rails 3.2 app I didn't have to write JQuery in a Pjax app.

https://github.com/nz/pjax-rails http://twitter.github.com/bootstrap/javascript.html#popovers


I actually solved the problem with

$(document).on('ready ajaxComplete', function() { 



source to share

1 answer

Short version: Use the pjax: end event to apply bootstrap behavior to new elements.

When pjax loads new content, bootstrap handlers are not attached to all elements. With typical jQuery elements, you can use "live" to have jQuery detect new content and apply the correct handlers. Sorry if this first part is what you already know.

For example, if this is in your jQuery ready function:

$('a').click(function() { alert('here') }


If you are dynamically loading content that contains another anchor element, the click handler will not be attached to it.

But if you do this:

$('a').live('click', function() { alert('here') }


when new content is loaded, jQuery will add a click handler because it is linked with live.

Let's go back to bootstrapping. As far as I understand, there is no equivalent "live" method for something like popover. You cannot change this:




$('a').live('popover')  # WON'T WORK


So, if the anchor is loaded via pjax (or ajax or something dynamic), any new bindings are not anchored as popovers.

How would this have to do with binding the pjax: end event so that you can do something after the pjax content has been inserted. In the popover example:

  .on('pjax:end', function() { $('a').popover() })


Whenever the pjax content is loaded, it runs this function and applies the popover functionality to any anchor elements, including newly inserted ones. You can also isolate it with a selector with just a container with new content so you don't reapply functionality to things that haven't changed.



All Articles