user2557307
user2557307

Reputation: 53

Reset timer on click for show and hide - jquery

I have a jQuery task where on click of a button, I have to display a text message for 10 seconds which I've implemented.

Now the problem is while the text is still visible, if I click on the same button, it should reset the timer (the timer should be 0 and the text should show for 10 seconds again). Below is what I did. Can you tell me what I'm doing wrong?

$('#mybtn').live('click', function(e){
   /*mybtn is the button
    mytext is the text that should appear
   */
   e.preventDefault();
   var $mytext = $('#mytext');
   if( $mytext.length >0){ //text is existing or showing
       $mytext.stop();
       $mytext.show().delay(10000).hide(500);
   }
   else{
       $mytext.show().delay(10000).hide(500);
  }

});

Upvotes: 0

Views: 1977

Answers (2)

maverickosama92
maverickosama92

Reputation: 2725

try this:

var timer;
$('#mybtn').on('click', function(e){   
   var $mytext = $('#mytext');    
   $mytext.show(500);
   clearTimeout(timer);   
   timer = setTimeout(function(){
       $mytext.hide(500)
    },10000);        
});

working fiddle here: http://jsfiddle.net/jUkbh/

check also this fiddle: http://jsfiddle.net/jUkbh/2/

Upvotes: 2

Ganesh Jadhav
Ganesh Jadhav

Reputation: 2848

Instead of using delay(1000), you should use window.settimeout.

var time;
if( $mytext.length >0) {
    $mytext.stop();
    $mytext.show()
    cleartimeout(time);
    time=window.settimeout(
        function() {
            $mytext.hide(500);
        }, 1000);
}

Upvotes: 0

Related Questions