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);
});
});
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; });