How to change button text to short press using javascript only?

I am doing a shopping cart website and I want my Add to Cart button to say Added item by clicking on it, but only 2 seconds after that it changes back to Add to Cart . How do I achieve this?

+4
source share
5 answers

Try the following:

$('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);
    }
});
+3
source

In simple Javascript, you can use the variable to test the click of a button, and if not, set the button to the desired line and change it 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>
Run codeHide result
+3
  • " " "Item Added"
  • In the same case, the handler uses: setTimeout (makeTimeoutFunc (), 2000);
  • In makeTimeoutFunc (), change the button text to its original value.
0
source

After pressing the button, the button text will be changed and the button will also be disabled to prevent further actions, and then return 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>
Run codeHide result
0
source

Try the following:

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

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

Source: https://habr.com/ru/post/1655294/


All Articles