0

I'm working with timers when I click the button timer starts from 5 seconds and fadesout when it comes to 0. I tried but couldnt get , here is the fiddle I've tried: http://jsfiddle.net/GNrUM/937/

<div id="hideMsg" style="display:none;">
This Box will Close In <span>5</span> Seconds..</div>
<input id="take" type="button"  value="click me" >

jQuery code :

$("#take").live("click", function () {
    $('#hideMsg').show();
    var sec = $('#hideMsg span').text()
    var timer = setInterval(function () {
        $('#hideMsg span').text(--sec);
        if (sec == 0) {
            $('#hideMsg').fadeOut('fast');
            clearInterval(timer);
        }
    }, 1000);
});

It's working good for first click, when click 2 time count starts from 0,-1,-2,. It does not clear the intervals. any help?

2
  • try to re-initialize $('#hideMsg span') . like $('#hideMsg span').text('5'); jsfiddle.net/GNrUM/941 Commented Feb 6, 2014 at 7:43
  • keep going .. njoy :) Commented Feb 6, 2014 at 8:06

3 Answers 3

1

try to re-initialize $('#hideMsg span') . like $('#hideMsg span').text('5');

http://jsfiddle.net/GNrUM/941

Sign up to request clarification or add additional context in comments.

Comments

1

you have to reset the value once it fades out

 $('#hideMsg span').text(5);

JS Fiddle Demo demo

Comments

0

Try this:

 $("#take").live("click",function(){  
    $('#hideMsg').show();    
    var sec = $('#hideMsg span').text()
    var timer = setInterval(function() { 
       $('#hideMsg span').text(--sec);
       if (sec == 0) {
          $('#hideMsg').fadeOut('fast');
           $('#hideMsg span').text("5"); // reinitialize the span value
          clearInterval(timer);
       } 
    }, 1000);
    });

1 Comment

Better to do in callback method of fadeout. like $('#hideMsg').fadeOut('fast',function(){ $('#hideMsg span').text(5); });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.