Daniel Anderson Daniel Anderson - 3 months ago 12
CSS Question

Transition for a button using .delay() with jQuery and Bootstrap

I am testing something very simple. I created a basic login form using Bootstrap, as follows:

<div class="form-inline form-group-sm">
<div class="input-group">
<label for="email" class="sr-only">Email Address :</label>
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input type="email" required id="email" placeholder="Email Address" class="form-control">
</div>
<div class="input-group">
<label for="password" class="sr-only">Password :</label>
<input type="password" required id="password" placeholder="Password" class="form-control">
</div>
<button id="signIn" class="btn-sm btn-primary" autocomplete="off" data-loading-text="Wait...">Login</button>
</div>


My goal is to use a transition to change the button's text when the user clicks the 'Login' button to show that it is processing, and once the processing is complete, change it back. For testing only, I added the following jQuery code:

<script type="text/javascript">
$(document).ready(function () {
$('#signIn').on('click', function () {
var $btn = $(this);
$btn.button('loading');
$btn.delay(1500);
$btn.button('reset');
})
});
</script>


These two lines seem to be the problem:

$btn.delay(1500);
$btn.button('reset');


If I take them out then the transition to change the button's text works, which is fine, although I still want to change it back to its original text after a delay. But adding those two lines in to reset the button breaks it. I could use some help understanding why, because I get no messages in the debugger console. It fails silently.

Any help would be appreciated. Thanks!

Answer

You should use setTimeout instead, as .delay() is limited to jQuery effects.

The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.


$(document).ready(function () {
    $('#signIn').on('click', function () {
        var $btn = $(this);
        $btn.button('loading');
        setTimeout(function(){
            $btn.button('reset');
        }, 1500);
    })
});

This is just an example of where you could use .delay() to accomplish similar effect

$('#signIn').on('click', function () {
  $(this).button('loading')
         .fadeTo("fast", 0.5)
         // can use .delay() here, in between two jQuery animation effects:
         .delay(1500)
         .fadeTo("fast", 1, function(){
             $(this).button('reset');
         });
});

JSFiddle

Comments