0

i'm using this code for loading of buttons

<script>
        $('#load1').click(function() {
            $('#load1').html('<span class="spinner-border spinner-border-sm mr-2" role="status" aria-hidden="true"></span>Loading...').attr('disabled', true);
        });
</script>

how to setTimeout in this code

Nima
  • 91
  • 1
  • 12

1 Answers1

2

You can use setTimeout function to hide the loading and spinner after x seconds of each button being clicked.

In order to return the button to its original state. We need to save the HTML of that clicked button on variable and then apply back that HTML back to relevant clicked button.

Also use a class selector instead of id for button click to that you can reuse the same function multiple loading message and spinner of different having the same class.

Use prop to set the disabled property attr is not ideal in this case and is not rec-emended to be used

Live Working Example:

$('.load1').click(function() {
  var _this = $(this) //click button
  var existingHTML = _this.html() //store exiting button HTML
  //Add loading message and spinner
  $(_this).html('<span class="spinner-border spinner-border-sm mr-2" role="status" aria-hidden="true"></span>Loading...').prop('disabled', true)

  setTimeout(function() {
    $(_this).html(existingHTML).prop('disabled', false) //show original HTML and enable
  }, 3000) //3 seconds
});
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<button class="btn btn-success load1">
  Click Success
</button>
<br>
<br>
<button class="btn btn-danger load1">
  Click Danger
</button>
Always Helping
  • 14,316
  • 4
  • 13
  • 29