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?
To change the text of a button on click:Add a click event listener to the button. Use the textContent property to change the button's text. For example, btn. textContent = 'Button clicked' .
getElementById('myElement'). className = "myclass"; Example 1: In this code change the class of the button from “default” to “changedClass” using the onclick event which in turn changes the background color of the button from RED to GREEN.
In the Javascript code, we create a variable that gets the element on the page that has an id of selfclick (which is the button we made). We then perform the click function on this button using the Javascript click() function. And this is how we can click a button with Javascript code.
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>
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);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With