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?
Create an HTML document that includes the jQuery library. Inside a script element in your HTML document, write jQuery's ready() function, which will wait until the selected object (the HTML document in this case) is ready before executing the code passed into it.
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.
Combining Ben and fotanus' answers I created the following pattern:
$(document).ready(function () { AjaxInit() }); $(document).ajaxComplete(function () { AjaxInit() }); function AjaxInit() { alert("test"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With