Reputation: 109
I have a problem. I have this menu which dropdowns on click and I want it to go back after 5 seconds if nothing happened. I got this far. But there is this glitch that when I have clicked it to go back, it comes out after 5 sec without asking. Is it possible for it to check if it's still visible then go back, if not, keep calm and carry on?
Here is the code:
$(document).ready(function () {
$('#aktivs-share').click(function() {
$('#share').slideToggle('slow', function() { });
setTimeout(function() {
$('#share').slideToggle('slow', function() { });
}, 5000);
});
$('#aktivs').click(function() {
$('#valodas').slideToggle('slow', function() { });
setTimeout(function() {
$('#valodas').slideToggle('slow', function() { });
}, 5000);
});
});
Upvotes: 1
Views: 178
Reputation: 4314
You need to keep track of the state the menu is in, and then use clearTimeout() to clear the timeout if the state of the menu is closed.
(code is untested, but hopefully you get the idea)
var shareOpen = false; var shareTimeoutHandle = undefined; $('#aktivs-share').click(function() { $('#share').slideToggle('slow', function() { }); // check the current state, if open already, close and reset if (shareOpen) clearTimeout(shareTimeoutHandle); else { shareTimeoutHandle = setTimeout(function() { $('#share').slideToggle('slow', function() { }); }, 5000); } // set the new state to be the opposite shareOpen = !shareOpen; });
Upvotes: 1
Reputation: 1074238
Remember the return value of setTimeout
, it's a handle you can use to cancel it via clearTimeout
.
In your case, since you want to do it with more than one thing, probably best to store the timer handle actually on the element, via data
.
You might consider writing yourself a plug-in method to do this, to avoid duplicating the logic. slideToggleAutoClose
or something. :-)
Upvotes: 0