Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling jQuery document.ready functions by hand

If I make an AJAX request and want to call all functions that were set up by $(document).ready(). How can I do it? Thank you

like image 992
idm Avatar asked Feb 23 '26 15:02

idm


2 Answers

$(document).ready();

If that doesn't work, try this:

function startup() {

    // All your functions in here.

}

$(document).ready(startup);

And after your AJAX request is finished:

startup();
like image 187
Jeffrey Avatar answered Feb 26 '26 03:02

Jeffrey


The easiest way is to use a shared function:

$(document).ready(function() {
    setup();
});

$.post('/', {}, function() {
    setup();
}, 'json');

But if you're using it to re-assign listeners, you would probably be able to get away with assigning them before they're created, like this:

$(document).ready(function() {
    $(document).delegate('.my-button', 'click', function() { });
});

Using this code, all .my-button clicks will be handled by your custom function, regardless of whether the button existed in your DOM upon DOMReady.

Note that:

  • $(document).ready(function() { ... }); can be minimized to $(function() { ... });
  • If you're using jQuery 1.7+, prefer .on over .delegate: $(document).on('click', .my-button', function() { });
  • Prefer narrower context over broader, i.e. $('#close-parent').delegate over $(document).delegate
like image 28
David Hedlund Avatar answered Feb 26 '26 03:02

David Hedlund



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!