Reputation: 51
I've been reading things online for awhile and have not figured out the correct way to use the setTimeout function.. any reason why?
$('.drop-down').click(function() {
$(this).hide();
});
$('.nav-main li ul').hide().removeClass('.drop-down');
setTimeout(function() {
$('.nav-main li').hover(
function openDrop() {
$('ul', this).stop().slideDown(1000);
},
function closeDrop() {
$('ul', this).stop().slideUp(1000);
}
);}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="nav-main" role="navigation">
<ul>
<li class="nav-top"><a href="#welcome">Welcome</a></li>
<li class="nav-top"><a href="#about">About</a>
<ul class="drop-down">
<li><a href="#about">Services</a></li>
<li><a href="#client">Clients</a></li>
<li><a href="#press">Press</a></li>
<li><a href="#leadership">Leadership</a></li>
<li><a href="#twitter">Twitter</a></li>
</ul>
</li>
<li class="nav-top"><a href="#contact">Contact</a> </li>
</ul>
</nav>
Upvotes: 2
Views: 122
Reputation: 1013
You can use JQuery's delay() method in this case, no need for setTimeout
$('ul', this).stop().delay(1000).slideDown(1000);
See updated fiddle: https://jsfiddle.net/8xtxxk35/3/
Upvotes: 8
Reputation: 3011
As @Tim said, you don't need to use setTimeout in this instance.
But just to answer why it wasn't working...
If you were to use it (and you really don't need to in this case), the reason it's not working is because of the location of your setTimeout:
setTimeout(function() {
$('.nav-main li').hover(
function openDrop() {
$('ul', this).stop().slideDown(1000);
},
function closeDrop() {
$('ul', this).stop().slideUp(1000);
}
);
}, 1000);
Here, you're not actually doing anything except for delaying the hover
handler from being added to the page.
You need to wrap the code you actually want to run with setTimeout:
$('.nav-main li').hover(
function openDrop() {
setTimeout(function() {
$('ul', this).stop().slideDown(1000);
}, 1000);
},
function closeDrop() {
setTimeout(function() {
$('ul', this).stop().slideUp(1000);
}, 1000);
}
);
note there are 2 setTimeouts now, one for each function.
Upvotes: 3