Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery show timeout countdown output

So I have this code to hide certain div's, and I want to add to the html code the seconds that the div is closing in, ex: 5,4,3,2,1, (closed);

Here is the code:

<script type="text/javascript">
    jQuery(document).ready(function () {
        var isVisible;
        var cvr = $("#cover");
        var dlg = $("#dialog");
        isVisibleCvr = cvr.is(":visible");
        isVisibleDlg = dlg.is(":visible");
        if(isVisibleCvr && isVisibleDlg == true){
            setTimeout(function() {
                cvr.hide();
                dlg.hide();
            }, 5000);
        }
    });
</script>

Any sugestions?

like image 355
Nikato Avatar asked Jun 16 '26 19:06

Nikato


2 Answers

A solution :

 jQuery(document).ready(function () {
    var cvr = $("#cover");
    var dlg = $("#dialog");
    var t = 5;
    isVisibleCvr = cvr.is(":visible");
    isVisibleDlg = dlg.is(":visible");
    if(isVisibleCvr && isVisibleDlg == true){
        (function countDown(){
            if (t--) {
               $('#t').text(t + ' s');
               setTimeout(countDown, 1000);
            } else {
               $('#t').text('gone!');
               cvr.add(dlg).hide();
            }
        })();
    }
});

I think the code is self explaining. If not, ask for clarification.

Demonstration

like image 160
Denys Séguret Avatar answered Jun 19 '26 08:06

Denys Séguret


You can use the setInterval function, use the following script: (demo)

<script type="text/javascript">
 jQuery(document).ready(function () {

  var counter = 5;
  var interval = setInterval(function() {
      counter--;
      jQuery("#number").html(counter);
      if (counter == 0) {
        //Do something
        jQuery("#number").html("Countdown ended!");
        // Stop the counter
        clearInterval(interval);
      }
  }, 1000);

 });
 </script>

and the following div:

<div id="number">5</div>

Check out the live demo on jsFiddle: http://jsfiddle.net/RtFKr/

like image 21
BrownEyes Avatar answered Jun 19 '26 08:06

BrownEyes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!