nickmjones
nickmjones

Reputation: 482

Another jQuery noob question about functions

I want to "functionalize" more of my jQuery code, instead of writing little standalone snippets. Here's an example. Let's say I have some li's that I'd like to use as triggers, like so:

<li class="alpha-init" id="a-init">A</li>
<li class="alpha-init" id="b-init">B</li>
<li class="alpha-init" id="c-init">C</li>

And some stuff I'd like to hide and show in correspondence to clicks on those triggers, like so:

<ul id="a-sub" class="alpha-popdown">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>

<ul id="b-sub" class="alpha-popdown">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>


<ul id="c-sub" class="alpha-popdown">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>

If I wanted to write a little snippet for each case, I could do:

$('li.alpha-init #a-init').click(function(){
    $('ul#a-sub').slideToggle(200);
}

But that means writing as many snippets as there are sets of links and submenus. How can I write this into a function? I'm not looking to "eat for a day", so as much explanation as you feel up to writing would be much appreciated. Thanks very much!

Upvotes: 0

Views: 236

Answers (4)

nickmjones
nickmjones

Reputation: 482

I used a combination of Artem Barger and John Sheehan's code. Thanks everyone for your help; now I get to sleep!

Upvotes: 0

Gabriel Hurley
Gabriel Hurley

Reputation: 40052

First off, id's should be unique on your page. You only need to use the selector $('#a-init') to access it.

I would write that like so (for each item):

html:

<li class="alpha-init" id="a-init">
<div>A</div>
<ul id="a-sub" class="alpha-popdown">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>
</li>

And then write the jquery as:

$('li.alpha-init').click(function(){
    $(this).children('ul.alpha-popdown').slideToggle(200);
}

The basic idea would be to use the $(this) method to access the item that was clicked and select your menu element relative to the parent element.

Upvotes: 0

Jason Berry
Jason Berry

Reputation: 2469

Have you considered using jQuery UI Tabs for this? It sounds nearly exactly like what you want. You can just style the tabs differently than the default!

Upvotes: 1

Artem Barger
Artem Barger

Reputation: 41222

$('li.alpha-init').click(function(){
    $('ul#'+this.id.substr(1) + "-sub").slideToggle(200);
}

Upvotes: 3

Related Questions