Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

calling another function after finishing button click function in jQuery

I want to call a function named func2 after the button click function finished its operations using jQuery. I’m using this method but doesn’t work. it calls the button click function on load time.

$("#btn-click").click(function(){
  //do something
});

function func2() {
  //do something
}

    $.when( $("#btn-click").click() ).done(function() {
       func2();
    });

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is one way to do it:
You define an action for the button click. In my example I created a promise with a setTimeout() call. This could be an Ajax call or anything else (not necessarily returning a promise). As soon as the action is done or the promise fulfilled, func2 will step into action.

$("#btn-click").click(func1);

function func1(){
  console.log("func1 started...");
  $.when(new Promise(res=>
setTimeout(res,1000)))
   .then(()=>{
     console.log("func1 done.");
     func2()});
} 

function func2() {
  console.log("func2");
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<button id="btn-click">click</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading