views:

50

answers:

3

I'm new to jquery and i'm trying to make a dropdown menu list like on www.teefury.com (mens and woman sizes). I came pretty close but when i click 1 of the buttons all of them open (or on my second try only the first one). Thus my questions:

  • Does anyone know a tutorial i can use for this?
  • What's the best way to try and create one on my own? (i have the html & css ready)
  • How do i make it so only 1 of the dropdowns will open on click and not all of them or only the first one?

This is what i have so far: http://users.telenet.be/ezarto/dropdown/

PS: this is also my first stackoverflow, please inform me of anything i did wrong :)

PSS: only 1 hyperlink allowed, sorry but you'll have to copy/paste the teefury one

A: 

demo

http://jsfiddle.net/QznH7/

css

.invisible
{
    display:none;
}​

html

<dl>
        <dt><a class='showMenu' href="javascript:"><span>1</span></a></dt>
        <dd>
            <ul class="invisible">
                <li><a href="#">a</a></li>
                <li><a href="#">b</a></li>
            </ul>
        </dd>
</dl>

<dl>
        <dt><a class='showMenu' href="javascript:"><span>2</span></a></dt>
        <dd>
            <ul class="invisible">
                <li><a href="#">a</a></li>
                <li><a href="#">b</a></li>
            </ul>
        </dd>
    </dl>

javascript

jQuery(function(){
    jQuery('.showMenu').bind('click',function(e){
        jQuery(e.target).parents('dl:first').find('ul').toggleClass('invisible')
    });   
});

Praveen Prasad
Very useful answer, gave me a little more insight. I picked the above answer though because it was easier to implement. Thanks a bunch!
Boktor
A: 

Your dropdown menus got the same class dl class="dropdown">

So when you do that for example :

$(".dropdown dt a").click(function() {
  $(".dropdown dd ul").toggle();
});

It does it on both of them!

You may want to recognize which one you click on. For example, you can give you dropdowns an id

<dl id="dropdown1">

and change your jQuery in consequence.

Chouchenos
Yeah i knew that was a problem but didn't really know a way to work around it. Thanks for your answer!
Boktor
A: 

Use this and tranverse the DOM to hit the appropriate list that you are trying to show. I refactored your JavaScript to do so.

$(function() {

 $(".dropdown dt a").click(function() {
   $(this).closest('dt').siblings('dd').find('ul').toggle();
 });

 $(".dropdown dd ul li a").click(function() {
   var text = $(this).text();

   $(this).closest('dd').siblings('dt').find('span').text(text);

   $(this).closest('ul').hide();
 });

});​
John Strickler
Works like a charm, thanks so much!
Boktor
I also added this $(document).bind('click', function(e) { var $clicked = $(e.target); if (! $clicked.parents().hasClass("dropdown")) $(".dropdown dd ul").hide(); });to make the menu close on a click anywhere on the screen
Boktor