Execute document.ready after ajax post

Jason Yost picture Jason Yost · Apr 10, 2011 · Viewed 52.8k times · Source

I have a custom.js file in which I have several elements that have click and other methods bound to them. The entire file is encapsulated in document.ready() and everything works. However when I do an AJAX post obviously document.ready() is never fired again for the current page. Is there anyway I can get document.ready() to fire again or do I need to have everything in named functions call them form my create.js.erb?

Answer

Ben picture Ben · Apr 10, 2011

You could always just put everything in one function (named loadfunction or something) and call that function when the document loads, and again when the ajax is loaded. Though it is a hacked together solution, it should work well enough.

So then take everything between $(document).onready(function () { and its end bracket } And put it in function OnloadFunction () { ending with }. Then put $document.onready(OnloadFunction);

Example: You have

$(document).ready(function () {alert("test");});

It would turn into:

function OnloadFunction ()
{
    alert("test");
}
$(document).ready(OnloadFunction);

Then you can call OnloadFunction whenever you want to.