Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute document.ready after ajax post

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?

like image 475
Jason Yost Avatar asked Apr 10 '11 07:04

Jason Yost


People also ask

How do I run Ajax in document ready?

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.


2 Answers

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.

like image 197
Ben Avatar answered Sep 17 '22 09:09

Ben


Combining Ben and fotanus' answers I created the following pattern:

$(document).ready(function () {      AjaxInit()  });    $(document).ajaxComplete(function () {      AjaxInit()  });    function AjaxInit() {      alert("test");  }
like image 39
Ken Mc Avatar answered Sep 19 '22 09:09

Ken Mc