Search code examples
jqueryonclickdocument-ready

Run jQuery document ready function a second time onclick?


I am sorry, I know this might be a very basic question. I have a document ready jQuery function, that has various different functions inside itself. This function is triggered on every pageload.

Is there somehow a possibility, to run this function onclick again, without realoading the page? Is it possible to name the function, and then trigger it again onclick?

e.g.:

$(document).ready(function() {
// doing a lot of stuff on DOM ready
});

$( "button" ).click(function() {
// do all the stuff again onclick without reloading the page
});

Thank you very much in advance!


Solution

  • I think you need to put the common functionality into a function and call it on load and on click like below:

    $(document).ready(function() {
        // doing a lot of stuff on DOM ready
        DoSomething();  // Called on the Document Ready.
    
    
       $( "button" ).click(function() {
         // do all the stuff again onclick without reloading the page
    
          DoSomething();  // Called on the button click.
       });
    
    
    });
    
    function DoSomething() {
       // doing a lot of stuff
    }
    

    Hope that helps.