Shawn Mclean
Shawn Mclean

Reputation: 57469

Jquery linking button to specific content

I have a concept similar to that of an accordian. I have a button, when clicked, it slides down a div with a specific ID. I have around 3 of these on the page. How do I write one function which automatically chooses the correct div to slide down?

I've seen plugins use rel attribute to achieve this. In actual Jquery code, how would I accomplish this?

Eg code:

<a rel="#c1">slide 1</a>
<a rel="#c2">slide 2</a>
<div id="c1"></div>
<div id="c2"></div>

Upvotes: 2

Views: 103

Answers (3)

Chris
Chris

Reputation: 4471

You could do something like

$("a").click(function() {
    var divSelector = $(this).attr("rel");
    $(divSelector).slideDown();
});

If you want to get a bit more fancy, you could group your items together (or give them a class) and do something like the following so that the other containers slide up.

<div id="sliders">
    <a rel="#c1">slide 1</a>
    <a rel="#c2">slide 2</a>
</div>
<div id="slidees">
    <div id="c1"></div>
    <div id="c2"></div>
</div>

$("#sliders a").click(function() {
    var divSelector = $(this).attr("rel");
    $("#slidees div").not(divSelector).slideUp();
    $(divSelector).slideDown();
});

Upvotes: 4

Soufiane Hassou
Soufiane Hassou

Reputation: 17750

$('a').click(function() {
  var target = $(this).attr('rel');
  $(target).toggle();
});

Upvotes: 0

kobe
kobe

Reputation: 15835

Shawn

Use class for divs, so that you can do something like this

$('.other').click(function() {

});

the above code will be applied to all the elements with same class name.

Upvotes: 0

Related Questions