I want to change label of a button for a moment and then bring it the original state.
All the commented lines are my attempts to make it work but I’m struggling.
Can somebody show me the correct approach?
codepen
$(".btn").click(function() {
//$(this).contents().remove();
$(this).html('loading...');
//$(this).html('<i class="fa fa-spinner fa-spin"></i> loading...'); //adding animation
//$(this).attr('disabled', true); //disabling
setTimeout(() => {
//how to reset default contents????????????????
//$(this).children().find('fa').remove();
//$(this).attr('disabled', false); //enabling
//$(this).html('<i class="fa fa-plus"></i> Add Book'); //defaulting
//$(this).children().show();
}, 500);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<button class="btn btn-success btn-lg"><i class="fa fa-plus"></i> Edit Book</button>
3
Answers
Answer is to store initial value in variable:
and then restoring it
All with 2 lines of code and I was going around like crazy. Entire code looks like this:
Using data-attributes
With one button, two texts:
Since you already use an arrow function, you can refer to
this
inside the callback oftimeout
, it will still mean the button which was clicked. Working example: