Skip to content Skip to sidebar Skip to footer

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 d

Solution 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) {
    returnfunction () {
        if (!clicked) {
            var last = this.innerHTML;
            this.innerHTML = 'Item added';
            clicked = true;
            setTimeout(function () {
                this.innerHTML = last;
                clicked = false;
            }.bind(this), 2000);
        }
    };
}(false), this);
<buttonid="button">Add to Cart</button>

Solution 2:

Try this:

$('button.add').click(function() {
    varself = $(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:

  1. In 'Add To Cart' event handler change the button text to 'Item Added'
  2. In the same event handler use: setTimeout(makeTimeoutFunc(), 2000);
  3. In makeTimeoutFunc() change the button text to original value.

Solution 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);

  });
})();
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script><buttonclass="btn-addcart">Add to cart</button>

Solution 5:

Try This:

<input type="button" id="btn"/>

$("#btn").click(function(){
$(this).val("Item Added");
setTimeout(function(){ $("#btn").val("Add to Cart"); }, 2000);         
});

Post a Comment for "How To Change The Button Text On Click For A Short Duration Only Using Javascript?"