How can I create bootstrap auto hide modal with time indicator?

Viewed 57

I have a modal caller link and a modal as below :

<!-- modal caller -->
<a href="#" data-toggle="modal" data-target="#modal">CALL MODAL</a>
<!-- modal -->
<div id="modal" class="modal auto-hide-modal" data-time="3000" data-backdrop="static" data-keyboard="false" tabindex="-1">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">MY TITLE</h5>
            </div>
            <div class="modal-body">MY TEXT</div>
            <div class="modal-footer">
                <div class="progress" style="height: .25rem;">
                    <div id="time_indicator" class="progress-bar" role="progressbar"></div>
                </div>
            </div>
        </div>
    </div>
</div>

And I have these scripts :

$(document).on('shown.bs.modal', '.auto-hide-modal', function () {
    var time = $(this).data('time');
    $(this).delay(time).fadeOut(300, function () {
        $(this).modal('hide');
    });
});

So far, so good. I want progress bar (time_indicator) shows remaining time for the modal to close.

1 Answers

You have to use jQuery animate functoin and set the speed of animation to time. and then reset the width back to 0; so the next time you open the modal the animation performs again.

CSS:

#time_indicator {
  width: 0;
}

JavaScript:

$(document).on('shown.bs.modal', '.auto-hide-modal', function () {
    var time = $(this).data('time');
    $("#time_indicator").animate({width: "100%"}, time);
    $(this).delay(time).fadeOut(300, function () {
        $(this).modal('hide');
        $("#time_indicator").css("width", 0);
    });
});
Related