Hey so I am using Rails PJAX for my web application with twitter bootstrap Jquery Plugins. I can’t seem to get both of them working together. So for an example, I have pagination and have some hover effects on some elements.
When I initially reload the page and hover over everything it works. When I click on the next on the pagination, the page up dates and then when I hover, it does not work. Logically I would think because the DOM was already loaded once. What can I do?
Also note that using Rails Pjax on a Rails 3.2 Application, I haven’t had to write any Jquery in the application for Pjax.
https://github.com/nz/pjax-rails
http://twitter.github.com/bootstrap/javascript.html#popovers
Solved:
I actually solved the issue by
$(document).on('ready ajaxComplete', function() {
$('a').popover()
});
Short version: use the pjax:end event to apply bootstrap behavior to new elements.
When pjax loads the new content, the bootstrap handlers haven’t been bound to all of the 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 stuff you already know.
For example if this is in your jQuery ready function:
If you dynamically load content containing another anchor element, the click handler won’t be bound to it.
But if you do this:
when the new content is loaded, jQuery will add the click handler because it’s bound using live.
Back to bootstrap. For something like a popover, there is no equivalent ‘live’ method as far as I can tell. You can’t change this:
to this:
So if the anchor is loaded via pjax (or ajax or anything dynamic), any new anchors aren’t bound as popovers.
The way around that is it to bind a pjax:end event so you can do stuff after the pjax content is inserted. In the popover example:
Whenever pjax content is loaded it will run that function and apply the popover functionality to any anchor elements, including newly inserted ones. You could further isolate it via a selector to just the container with the new content so you don’t reapply functionality to things that haven’t changed.