Reputation: 5089
I have an alert message bar that slides down when the user clicks a specific link. The alert bar slides back up after a specified period. If the user clicks this link multiple times, I would like to reset the timer, slide the alert bar back up and then slide it down again (reseting the timer).
$(document).ready(function(){
$('#main_container').live('click', function(){
$('.answer_yes').click (function(){
if ($('#topbar_alert').is(':visible')){
clearTimeout(slideUpTimer)
}
$('#topbar_alert').slideDown(300);
$('#topbar_alert_container').empty();
$('#topbar_alert_container').append('Alert Created!');
var slideUpTimer = setTimeout(function() {
$('#topbar_alert').slideUp(300);
},8000);
});
});
});
So everything works except the clearTimeout portion. If you click the link, the alert bar slides down and then slides back up after the setTimeout finishes. But if you click the link multiple times, it doesn't reset the alert bar.
Upvotes: 1
Views: 904
Reputation: 1731
You should declare slideUpTimer
outside your function. Make it global.
Upvotes: 0
Reputation: 10721
when you use var slideUpTimer
inside the function, it only exists for that one execution, it does not persist.
To use slideUpTimer
as you want to, you'll need to put it in the global scope.
var slideUpTimer;
$(document).ready....
then assign it with
slideUpTimer = setTimeout()...
notice the lack of var
when assigning.
Upvotes: 3
Reputation: 10305
you should define the var slideUpTimer
outside the current scope
var slideUpTimer;
$('#main_container').live('click', function(){
$('.answer_yes').click (function(){
if ($('#topbar_alert').is(':visible')){
clearTimeout(slideUpTimer)
}
$('#topbar_alert').slideDown(300);
$('#topbar_alert_container').empty();
$('#topbar_alert_container').append('Alert Created!');
slideUpTimer = setTimeout(function() {
$('#topbar_alert').slideUp(300);
},8000);
});
});
Upvotes: 3