views:

63

answers:

2

I'm building a custom pulldown menu in jQuery. Now I'd like to set the text of the A.select element to the text of the element that is clicked. But I can't get it to work.

This is the html:

<div class="pulldown">
    <a href="javascript:;" class="select">All cats/subs</a>
    <div class="options">
     <a href="javascript:;">Option one A</a>
     <a href="javascript:;">Option two A</a>
     <a href="javascript:;">Option three A</a>
        <a href="javascript:;">Option four A</a>
    </div>
</div>

This is the jQuery code:

$(document).ready(function() {
$('div.pulldown').toggle(function() {
    $(this).css('z-index','110');
    $('.options', this).css('z-index','100').show('fast');
    $('.options A', this).click(function(){
        var value = $(this).text();
        $(this).closest('DIV.pulldown A.select').text(value);
    });
}, function(){
    $(this).css('z-index','10');
    $('.options', this).css('z-index','0').hide('fast');
}); });

What am I missing here?

A: 

You should set a global variable for the entire div and use that as a reference

$(document).ready(function() {
    /*Grab the div into a variable*/
    var Pulldown = $('div.pulldown');

    /*Set up your event handlers*/
    $('.options a', Pulldown).click(function(){
        var value = $(this).text();
        $('.select',Pulldown).html(value);
    });

    /*Toggle the pulldown*/
    Pulldown.toggle(function() {
        Pulldown.css('z-index','110');
        $('.options', Pulldown).css('z-index','100').show('fast');
     }, function(){
         Pulldown.css('z-index','10');
         $('.options', Pulldown).css('z-index','0').hide('fast');
     });
});

Live Example here:

http://jsfiddle.net/RYcr3/2/

RobertPitt
But he definitely should **not** be re-establishing the "click" handler for the anchors in the "toggle" code.
Pointy
Updated, Good point.
RobertPitt
A: 

It will be easier to work with if you clean up your HTML a little bit:

<dl class="menu">
    <dt class="topItem">All cats/subs</dt>
    <dd class="subItem">Option one A</dd>
    <dd class="subItem">Option two A</dd>
    <dd class="subItem">Option three A</dd>
</dl>

Then your jQuery boils down to this:

$(function() {
    var $topItem = $('.topItem');
    var $subItems = $('.subItem');

    $topItem.bind('click', function() {
        $subItems.toggle();
    });

    $subItems.bind('click', function() {
        $topItem.text($(this).text());
        $subItems.toggle();
    });
});

A live demonstration can be found at http://jsfiddle.net/c8Qp8/.

Note, this example needs to be expanded to take care of multiple menus with multiple sub-items. Also, instead of setting your CSS properties with JavaScript you should set them with your stylesheet.

jsumners
Thanks @jsumners. Your code looks much cleaner. I'll give it a go!
Webbiker