Multiple dropdown menus, one JQuery script
I have been playing with the jDiv dropdown menu developed by Skyrocket Labs and improved by Peter Hinton. It works well for multiple menus on开发者_JAVA百科 the same page, as long as you replicate the code with different identifiers (#nav1 triggers #hidden-menu1, #nav2 triggers #hidden-nav2, etc).
var hide1 = false;
$("#nav1").hover(function(){
if (hide1) clearTimeout(hide1);
$("#hidden-nav1").show();
}, function() {
hide1 = setTimeout(function() {$("#hidden-nav1").hide();});
});
$("#hidden-nav1").hover(function(){
if (hide1) clearTimeout(hide1);
}, function() {
hide1 = setTimeout(function() {$("#hidden-nav1").hide();});
$("#hidden-nav1").stop().show();
});
I am trying to sort out how to rewrite the code so that it can, "discover" the numerical value of the navX linked hovered and trigger the appropriate hidden-navX divs.
Here is a working
JSFiddle DEMO
I removed ALL ID's just to show how easy and striped can be the code and functional too, just using classes.
You can undo your ID's if you need to use them, but leave all unchanged.
If you need explanation about the code I can comment each line.
Here is the new/changed Jquery:
$(document).ready(function() {
var countNavs = 0; $('#navlist li').attr('class', function() {countNavs++;return 'connected' + countNavs;});
var countDrops = 0; $('.dropdown').attr('class', function() {countDrops++;return 'dropdown connected' + countDrops;});
var hide1 = false;
$("#navlist li").hover(function(){
var equal = $(this).attr('class');
$('.active').removeClass();
if (hide1) clearTimeout(hide1);
$('.dropdown').hide();
$('.'+equal).not('li').show();
$(this).children('a').toggleClass('active');
}, function() {
hide1 = setTimeout(function() {$('.'+equal).not('li').hide();});
});
$('.dropdown').hover(function(){
if (hide1) clearTimeout(hide1);
}, function() {
hide1 = setTimeout(function() {$('.dropdown').hide();});
$('.active').removeClass();
$('.dropdown').stop().show();
});
});
With COMMENTS
To help you understand in few words: We add automatically a SAME custom class to each 'li' and his corespondent 'dropdown' called: '.connectedN',
where 'N' is an incremented number.
Than we just say: if the hovered 'li' is class 'connected3' that means we just hovered the 3th 'li' , and we'll go to open the '.dropdown' that have the SAME class.
Try
function doNav(id) {
var hide = false;
$(id).hover(function() {
if (hide) clearTimeout(hide);
$("#hidden" + id).show();
}, function() {
hide = setTimeout(function() {
$("#hidden" + id).hide();
});
});
$("#hidden" + id).hover(function() {
if (hide) clearTimeout(hide);
}, function() {
hide = setTimeout(function() {
$("#hidden" + id).hide();
});
$("#hidden" + id).stop().show();
});
}
for (var i = 1; i < 4; i++) {
doNav("nav" + i);
}
精彩评论