Modal Countdown

1

I created a modal with Bootstrap, and created in a separate file a timer in Javascript. But I wanted this timer to roll inside the Modal. How do I proceed? Thank you!

Modal code:

<div class="bs-example">
    
    <div id="QuestaoModal" class="modal fade">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    
                </div>
                <div class="modal-body" width="200px">
                  
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">OK</button>
                </div>
            </div>
        </div>
    </div>
</div> 

Countdown Code:

<html>

    <head>
        <script type="text/javascript">
            var segundo = new Number();
            var segundo = 180;

            function start() {
                if ((segundo - 1) >= 0) {
                    tempo.innerText = count;
                    count = count - 1;
                    setTimeout('start();', 1000);
                }
            }

        </script>
    </head>

    <body onload="start();">
        div id ="tempo"></div>
    </body>

</html>
    
asked by anonymous 27.11.2016 / 16:00

1 answer

1

From what I understand, you want to start a count so the modal is open. You can do this by using the shown.bs.modal and hidden.bs.modal callbacks of the bootstrap modal, firing the timer the moment it is displayed, and clearing it when the modal is closed.

Demo : link

function timer(elToUpdate) {

    var maxTime = 60;

    elToUpdate.text(maxTime);

    var interval = setInterval(function () {

        if (maxTime > 0) {
            maxTime--;
            elToUpdate.text(maxTime);
        }
        else {
            clearInterval(interval);
        }

    }, 1000);

    return interval;
}

         $("#QuestaoModal").on('shown.bs.modal', function () {

            var t = timer($('#modal-time'));

            $(this).on('hidden.bs.modal', function () {
                clearInterval(t);
                $('#modal-time').text("");
                $(this).off('hidden.bs.modal');
            });
        });
    
28.11.2016 / 06:09