Reputation: 28853
I have created a jquery dropdown menu with the following HTML:
<dl class="dropdown">
<dt><a id="linkglobal1"><span class="icon lock">Action</span></a></dt>
<dd>
<ul id="ulglobal1">
<li><a href="#"><span>Everyone</span></a></li>
<li><a href="#"><span>Friends</span></a></li>
<li><a href="#"><span>Only Me</span></a></li>
<li><a href="#"><span>Customize</span></a></li>
</ul>
</dd>
</dl>
and then the JS:
$(document).ready(function()
{
$('dl.dropdown dt a').click(function()
{
$("dl.dropdown dt a").removeClass("selected");
var toggleId = "#" + this.id.replace(/^link/,"ul");
$('dl.dropdown dd ul').not(toggleId).hide();
$(toggleId).toggle();
if($(toggleId).css("display") == "none")
{
$(this).removeClass("selected");
}
else
{
$(this).addClass("selected");
}
});
$("dl.dropdown dd ul li a").click(function()
{
$("dl.dropdown dd ul").hide();
$("dl.dropdown dt a").removeClass("selected");
});
$(document).bind('click', function(e)
{
var $clicked = $(e.target);
if (! $clicked.parents().hasClass("dropdown"))
{
$("dl.dropdown dd ul").hide();
$("dl.dropdown dt a").removeClass("selected");
}
});
});
The problem I am having is that it relies on using ID's on both the <dt>
link and the <ul>
. How can I modify my jQuery so that it no longer relies on them?
Thanks
EDIT: I've answered this myself. See below.
Upvotes: 1
Views: 831
Reputation: 28853
Did it with this:
$(document).ready(function()
{
$('dl.dropdown dt a').click(function()
{
$("dl.dropdown dt a").removeClass("selected");
var toggleMenu = $(this).parent().parent().find('dd ul');
$(toggleMenu).toggle();
$('dl.dropdown dd ul').not(toggleMenu).hide();
if(toggleMenu.css("display") == "none")
{
$(this).removeClass("selected");
}
else
{
$(this).addClass("selected");
}
});
$("dl.dropdown dd ul li a").click(function()
{
$("dl.dropdown dd ul").hide();
$("dl.dropdown dt a").removeClass("selected");
});
$(document).bind('click', function(e)
{
var $clicked = $(e.target);
if (! $clicked.parents().hasClass("dropdown"))
{
$("dl.dropdown dd ul").hide();
$("dl.dropdown dt a").removeClass("selected");
}
});
});
Upvotes: 1
Reputation: 51
You can use jbar jQuery plugin jbar is a jQuery plugin that transforms an unordered list into a toolbar with dropdown menus. Please follow the following link:- jbar@GitHub
Upvotes: 0
Reputation: 22770
give those items classes. the classes don't need to exist.
<ul id="ulglobal1" class="dropdown">
<li><a href="#"><span>Everyone</span></a></li>
<li><a href="#"><span>Friends</span></a></li>
<li><a href="#"><span>Only Me</span></a></li>
<li><a href="#"><span>Customize</span></a></li>
</ul>
then your jquery selector uses
$(".dropdown")....
Upvotes: 0