Reputation: 1465
Working on a small piece of code for a custom shopping cart. I want to change a button to show a success message for 2 seconds, then revert the button back to the original HTML.
HTML...
<button id="42" class="btn btn-primary btn-block" type="button" onclick="added_to_order('42')">1st Semester<span class="glyphicon glyphicon-chevron-right float-right"></span></button>
Javascript...
function added_to_order(id){
var old_html = $('#' + id + '').html();
$('#' + id + '').html('<span class="glyphicon glyphicon-ok-sign"></span> Added to your order!');
$('#' + id + '').removeClass('btn-primary').addClass('btn-success').delay(2000).html(old_html);
}
Everything is fine, except I'm not getting the delay of 2 seconds before the button is updated with the old HTML.
Any ideas?
Upvotes: 0
Views: 26
Reputation: 22237
I don't think that any old function qualifies to be a valid member of the jQuery effects queue. I've wrapped your code in some queue function calls. Take a look at the other examples on that page for more ideas.
function added_to_order(el){
var old_html = $(el).html();
$(el).html('<span class="glyphicon glyphicon-ok-sign"></span> Added to your order!');
$(el)
.queue(function () {
$(el).removeClass('btn-primary').addClass('btn-success').dequeue();
})
.delay(2000)
.queue(function () {
$(el).html(old_html).dequeue();
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-primary btn-block" type="button" onclick="added_to_order(this)">1st Semester<span class="glyphicon glyphicon-chevron-right float-right"></span></button>
Upvotes: 1
Reputation: 896
It's best to use the setTimeout
function in this case.
function added_to_order(id){
var old_html = $('#' + id + '').html();
$('#' + id + '').html('<span class="glyphicon glyphicon-ok-sign"></span> Added to your order!');
$('#' + id + '').removeClass('btn-primary').addClass('btn-success');
setTimeout(function() {
$('#' + id + '').html(old_html);
}, 2000);
}
Upvotes: 1