Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 601
Harri Caceres Avatar asked Sep 21 '16 07:09

Harri Caceres


People also ask

How do I change the text on a button click?

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' .

How do I change the class on a click button?

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.

Can I click a button using JavaScript?

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.


2 Answers

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>
like image 56
Nina Scholz Avatar answered Oct 17 '22 11:10

Nina Scholz


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);
    }
});
like image 33
jcubic Avatar answered Oct 17 '22 12:10

jcubic