Modal with Countdown

Asked

Viewed 987 times

1

I created a modal with Bootstrap, and created in a separate file a Javascript chronometer. But I wanted that chronometer to run inside Modal. How do I proceed? Thanks in advance!

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> 

Code of the Countdown:

<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>
  • You can use the [setInterval()][1] function and change the text by selecting the id or class from where you want the time to appear. Other related questions: [1]: http://www.w3schools.com/jsref/met_win_setinterval.asp [2]: http://stackoverflow.com/questions/20618355/the-simplest-possible-javascript-countcount-timer [3]: http://pt.stackoverflowcom/questions/128608/como-make-timer-in-javascript

  • The user who asked this question does not enter since 2016... probably will not accept the answer...

1 answer

1

From what I understand, Oce wants to start a countdown as soon as the modal is open. You can do this using the callbacks shown.bs.modal and hidden.bs.modal of the modal of the bootstrap, firing the timer the moment it is displayed, and cleaning it when the modal and closed.

Demo: https://jsfiddle.net/f32toygj/

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');
            });
        });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.