'How to change the button text on click for a short duration only using javascript?
I'm making a shopping cart website and I want my Add to Cart button to say Item added upon clicking it, but only for like 2 seconds then it changes back to Add to Cart . How do I do achieve this?
Solution 1:[1]
In plain Javascript, you could use a variable for checking if the button is clicked and if not, set the button to the wanted string and change it back after two seconds.
document.getElementById('button').addEventListener('click', function (clicked) {
return function () {
if (!clicked) {
var last = this.innerHTML;
this.innerHTML = 'Item added';
clicked = true;
setTimeout(function () {
this.innerHTML = last;
clicked = false;
}.bind(this), 2000);
}
};
}(false), this);
<button id="button">Add to Cart</button>
Solution 2:[2]
Try this:
$('button.add').click(function() {
var self = $(this);
if (!self.data('add')) {
self.data('add', true);
self.text('Item added');
setTimeout(function() {
self.text('Add to Cart').data('add', false);
}, 2000);
}
});
Solution 3:[3]
- In 'Add To Cart' event handler change the button text to 'Item Added'
- In the same event handler use: setTimeout(makeTimeoutFunc(), 2000);
- In makeTimeoutFunc() change the button text to original value.
Solution 4:[4]
After click, button text will be changed and the button will also be disabled to prevent further actions, then reverted back after two seconds.
(function() {
$(".btn-addcart").on("click", function() {
var $this = $(this),
oldText = $this.text();
$this.text("Item added");
$this.attr("disabled", "disabled");
setTimeout(function() {
$this.text(oldText);
$this.removeAttr("disabled");
}, 2000);
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<button class="btn-addcart">Add to cart</button>
Solution 5:[5]
Try This:
<input type="button" id="btn"/>
$("#btn").click(function(){
$(this).val("Item Added");
setTimeout(function(){ $("#btn").val("Add to Cart"); }, 2000);
});
Solution 6:[6]
Here is a version with only javascript, without jquery.
<body>
<input id ="button" type="button" value="add to cart" onclick=" tick(button)">
</body>
<script type="text/javascript">
function tick(button){
document.getElementById("button").value = "Item added";
setTimeout(() => (document.getElementById("button").value = "add to cart"), 2000);
}
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | fiveelements |
| Solution 4 | Nhan |
| Solution 5 | Priyanka Bansal |
| Solution 6 | Alqua |
