Click the button to see items in your cart being added!

I am looking to customize a button element to function as an 'add to bag' button with multiple text states triggered by user clicks. Initially, the button will display "Add to Bag," then change to a spinner image upon click. After a 1-second animation in this state, the text should switch to "Added to Bag!" before returning to the original "Add to Bag" state.

For reference, you can see a similar functionality in action on this page:

Below is a snippet of code that accomplishes most of these text changes, except for the spinner state:

// Cart button text change
(function() {
  $(".btn-cart").on("click", function() {
    var $this = $(this),
      oldText = $this.text();

    $this.text("Added to Bag!");
    $this.attr("disabled", "disabled");

    setTimeout(function() {
      $this.text(oldText);
      $this.removeAttr("disabled");
    }, 1600);
  });
})();

Answer №1

Check out this example below

$( document ).ready(function() {
// Changing Cart button text
  $(".btn-cart").on("click", function() {
    var $this = $(this),
      oldText = $this.text(); 
 $this.html("<img width='50' height='50' src='http://www.bebestore.com.br/images/shared/lazyloader.gif'/>"); 
    setTimeout(function() {
      $this.text("Added to Bag!");
    }, 3000);
    setTimeout(function() {
      $("img").hide();
      $this.show();    
      $this.text(oldText);
    }, 5000);
  });
});
button,div{text-transform:uppercase;background: #828282;
    border: #828282 1px solid;
    color: #fff;    transition: opacity 0.2s;    border-radius: 0;
    cursor: pointer;
    font-family: "Calibre SemiBold", arial, sans-serif;
    font-size: 12px;
    height: 45px;
    letter-spacing: 1.5px;
    line-height: 45px;
    overflow: hidden;
    padding: 0;
    text-align: center;
    text-decoration: none;
    text-transform: uppercase;
    width: 170px;
    -webkit-appearance: none;}
/*div {
    border: 7px solid #f3f3f3; 
    border-top: 7px solid #3498db; 
    border-radius: 50%;
    width: 20px;
    height: 20px;
    
}*/
span {
    background: url(https://www.storefirst.com/static/common/images/loading-spinner.svg);
    height: 30px;
    display: inline-block;
    width: 30px;
}
@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn-cart">Add to bag</button>

Answer №2

To smoothly achieve this effect, consider providing the original text in markup and then adjusting it before and after a timeout period.

<button class="btn-cart">Add to bag</button>

$(".btn-cart").on("click", function(){
    var $this = $(this);
    $this.text("Adding to bag");

    setTimeout(function(){
        $this.setText("Added to bag!");   
    }, 1000);
});

Edit based on feedback

I prefer it to show a spinner rather than simply stating "adding to bag"

You can easily accomplish this by making slight changes to your markup

<button class="btn-cart">
    <span class="btn-cart--text">Add to cart</span>
    <span class="btn-cart--loading" style="display: none">
        <img src="spinner.gif" />
    </span>
</button>

$(".btn-cart").on("click", function(){
    var $this = $(this);
    $text = $(".btn-cart--text", $this);
    $loading = $(".btn-cart--loading", $this);

    // Hide text and display loading spinner
    $text.css("display", "none");
    $loading.css("display", "block");        

    setTimeout(function(){
        // Change text, display text again, hide spinner
        $text.setText("Added to bag!");   
        $text.css("display", "block");
        $loading.css("display", "none");
    }, 1000);
});

Answer №3

In order to fulfill your requirements, you can implement a button update function triggered by a click event. This function will modify the text on the button and add a loading spinner image. Subsequently, a series of timers can be used to sequentially change the text. Here is an example:

$('.btn-cart').click(function() {
  var $btn = $(this).prop('disabled', true).addClass('adding').html('<img src="https://i.imgur.com/01yMDgZ.gif" />Adding to bag...');

  setTimeout(function() {
    $btn.text('Added to bag!').toggleClass('adding added');
    setTimeout(function() {
      $btn.text('Add to bag').removeClass('added').prop('disabled', false);
    }, 1000)
  }, 1000);
})
.btn-cart {
  background-color: #C00;
  border: 0;
  border-radius: 10px;
  color: #FFF;
  padding: 10px;
  font-size: 1em;
  cursor: pointer;
  outline: 0;
}

.btn-cart.adding {
  padding-left: 35px;
  background-color: #CCC;
}
.btn-cart.added {
  background-color: #CCC;
}

.btn-cart img {
  height: 25px;
  position: absolute;
  top: 15px;
  left: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn-cart">Add to bag</button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Enhance your website with the powerful combination of SweetAlert

I'm having trouble getting my ajax delete function to work with SweetAlert. I can't seem to find the error in my code. Can someone help me figure out how to fix it? function deletei(){ swal({ title: 'Are you sure?', ...

Alignment issue detected with the text for radio buttons

Attempting to include radio buttons on my survey form has resulted in the button and text being misaligned. Here is a screenshot showcasing how it currently looks: view image here I have experimented with using display: inline; but unfortunately, no chang ...

Sub-menus at multiple levels are failing to automatically close child elements when clicked

Currently, I am tackling the challenge of creating a multi-level sub-menu that is triggered by clicks instead of hover actions. However, I'm facing an issue with closing child sub-menus when opening another one. It's crucial for all second-level ...

Tips for optimizing the positioning of HTML elements in a flexible and responsive manner

For the past two days, I have been struggling to responsively position some HTML elements. The effect I am aiming for is similar to what can be seen on this site before the stacking occurs in the Field Service Management and Intelligent Route Planning & Fl ...

Refresh your jQuery function without the need to reload the entire page

Is there a way to update a function's parameters without reloading the entire page? For instance, if I modify the 'style' dropdown value as shown in the URL image, can it be passed to the accordion function so that the accordion's color ...

Is there a workaround for jQuery serializing hidden form elements that are set to display:none?

I am facing the following issue: I have a form that needs to be serialized, however, I am using JavaScript to alter the appearance of the select fields. This means that the actual select fields are hidden using display:none property. The problem arises as ...

Enhance your dynamic content with jQuery/AJAX through customized CSS styling

Below is the jquery (3.1.1)/ajax request that I am using: $.ajax({ type: "POST", url: "pref.php", dataType: "text", data: { groupe_id: groupe_id, action: "getProducts" }, cache: false, error: function(html){ ...

Aligning two columns accurately

Utilizing Jquery, I have implemented the .offset() method to precisely position two columns that span 100% of the page height, serving as drop shadows for the content margins. The CSS styling applied to these columns is: div#lshade, div#rshade { widt ...

In the Firebug console, Ajax posts are highlighted in a vibrant red color

Upon executing the code provided, the Firebug was enabled. While submitting the form, in the console, the message "post to login_submit.php" appeared in red. However, there was no response received as well. <!DOCTYPE html> <html> ...

Footnote fiascos

I am currently in the process of creating a footer for my webpage and have implemented the following CSS styling: #footer { height: 100px; background-color: #F3F3F3; position: absolute; bottom: 0; } Although the footer is displaying at th ...

Greetings! I am interested in injecting HTML elements into a DOM using PHP and the jQuery Ajax method

After trying the following code snippet: $.ajax({ url: 'cod.php', type: 'POST', dataType: 'html', success: function(res){ $("#tests").html(res); } I implemented a foreach loop in my PHP s ...

How to Make Your Site/Content Fade In with jQuery Upon Loading?

Is there a way to add a fade-in effect to a website once it has finished loading, in order to avoid any sudden changes and ensure that the content appears smoothly? It might be simpler if the fading effect is applied only to certain sections, such as head ...

Exploring multidimensional JSON arrays with the jQuery each() method

What am I missing here? The first iteration works fine, but it breaks in the second one.. var testJSON = {"cluster":[{"node":[{"name":"one", "number":'100', "error":"none"},{"name":"two", "number":'200', "error":"none"},{"name":"three ...

Creating a custom PHP header file that dynamically includes .js and .css files based on the page

Is there a more efficient way to dynamically include .css and .js files in the head tags of my header.php, based on the current open .php file? This would help reduce loading time by only including necessary files for each specific page. I've been co ...

IE6/7 dilemma with CSS floating

Encountering a strange CSS float issue in IE6 and IE7. The HTML code looks like this: <fieldset style="float:left"> <legend>Summary</legend> <div class="display-label">Recruitment type</div> <div class="displa ...

It appears that the pixel sizes are different than what was originally designed

In my project, I have a header panel where the burger button is designed with a width of 32px and height of 24px. .header { display: flex; font-weight: bold; font-size: 50px; height: 100px; border: 1px solid black; position: relativ ...

Having issues with the functionality of Bootstrap 4 sticky-top feature

How can I make the sidebar stick to the top across different screen sizes? It works fine for smaller screens up until the 'sm' breakpoint, but beyond that, it doesn't stick. I've tried adjusting the order of class names, but it didn&apo ...

What is the best way to cycle through a JSON array of objects using JavaScript and jQuery?

Currently, my focus is on understanding JavaScript and JSON objects along with arrays. One of the tasks assigned to me involves iterating through the following array: {"6784": {"OD": [ { "od_id":"587641", ...

Tips for applying personalized CSS to the ngbDatepicker component in Angular 4

Here is the HTML code I am working with: <div> <div style="color:white">Date Range:</div> <div class="input-daterange input-group"> <input class="form-control" value="2017-01-01" name="dp1" ...

Populate form fields with dynamic data using jQuery and Ajax JSON response

I'm currently working on parsing returned data from JSON into form fields using an autocomplete form. I've successfully implemented the autocomplete feature. jQuery(document).ready(function() { var autocompleteArray = new Array(); jQuery("#bus ...