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

how to do task only for one time inside button click function in jQuery

here is my code. when I click on go button it shows text started and animations starts. after finishing the animation it shows the text finished. I want that during animation if I click on the go button for many times, it should print finished only for once at the end of animation. but this shows me finished text as many times as button is clicked. how can I do this that even I click for many times after animation the finished text should be printed only for once.

Note: I have not to disable the button during the animation

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>promise demo</title>
  <style>
  div {
    height: 50px;
    width: 50px;
    float: left;
    margin-right: 10px;
    display: none;
    background-color: #090;
  }
  </style>
  <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
 
<button>Go</button>
<p>Ready...</p>
<div></div>
<div></div>
<div></div>
<div></div>
 
<script>
$( "button" ).on( "click", function() {
  $( "p" ).append( "Started..." );
 
  $( "div" ).each(function( i ) {
    $( this ).fadeIn().fadeOut( 1000 * ( i + 1 ) );
  });
 
  $( "div" ).promise().done(function() {
    $( "p" ).append( " Finished! " );
  });
});
</script>
 
</body>
</html>

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

>Solution :

Add the totalClick, increase the totalClick for each click, then check if there’s no more totalClick left, display ‘finished!’

let totalClick = 0;

$('button').on('click', function () {
  $('p').append('Started...');

  totalClick++;

  $('div').each(function (i) {
    $(this)
      .fadeIn()
      .fadeOut(1000 * (i + 1));
  });

  $('div')
    .promise()
    .done(function () {
      totalClick--;
      if (!totalClick) {
        $('p').append(' Finished! ');
      }
    });
});
div {
  height: 50px;
  width: 50px;
  float: left;
  margin-right: 10px;
  display: none;
  background-color: #090;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Go</button>
<p>Ready...</p>
<div></div>
<div></div>
<div></div>
<div></div>
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