Search code examples
javascriptjquerywebbrowserconsole

want to use functions within ready jQuery method


I have a similar question before, my question was about how to access all the JavaScript functions in the web browser console even if they were within window.onload = function() {// code and functions} , but this time I want to do the same thing with jQuery:

$(document).ready(function() {
  // I want to access all the functions that are here in the web console
})

Solution

  • You can use the same syntax as in your previous question. Simply assign the function to the window.

    The following example illustrates what I mean. Note that you do not need the setTimeout(), this is just for this example here to auto-execute the your_function() when it is defined.

    $(document).ready(function() {
      window.your_function = function(){
        console.log("your function");
      };
      your_function();
    });
    
    // setTimeout() is needed because the $.ready() function was not executed when 
    // this code block is reached, the function(){your_function();} is needed because
    // the your_function() is not defined when the code is reached
    setTimeout(function(){
      your_function();
    }, 500);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    Note 2: I suggenst not to define global functions in the $(document).ready() if there is not a good reason for it. You can define the functions outside and then call them in the $(document).ready().