markopfc
markopfc

Reputation: 15

How can I toggle height of <a> where it would work like an accordion?

I am having trouble setting this up for multiple divs. I have it here http://jsfiddle.net/DpffX/ set up for only one. I would like to have the height of link increase onclick and a hidden div slideDown. When clicking the second link, the first div would slide up then link height back to original height, and second link go through the same opening sequence, so everything works like an accordion. *link tag has a bg image which is a line so it would look like a line is being drawn to the hidden div. Thank you. Updated fiddle jsfiddle.net/J2ySt/2

HTML

<div class="slider2">
    <h2>title</h2>
    <a href="#" class="line">link1 |</a>
    <a href="#" class="line">link2 |</a>
    <a href="#" class="line">link3 |</a>
    <a href="#" class="line">link4 |</a>
</div><!-- end .slider2 -->
<div id="link1" style="height:100px; background:#000; color:#fff; margin-left:20px; display:none;">content1</div>
<div id="link2" style="height:100px; background:#000; color:#fff; margin-left:20px; display:none;">content2</div>
<div id="link3" style="height:100px; background:#000; color:#fff; margin-left:20px; display:none;">content3</div>
<div id="link4" style="height:100px; background:#000; color:#fff; margin-left:20px; display:none;">content4</div>

jQuery

$(document).ready(function(){
    $(".line").toggle(function(){
        $(this).animate({height:108},500);
        $("#link1").delay(500).slideDown();
        },function(){
            $(this).delay(500).animate({height:20},500);
            $("#link1").slideUp();
    }); 
});

Upvotes: 0

Views: 100

Answers (2)

ayyp
ayyp

Reputation: 6598

Re-factored the code a little to

$(document).ready(function(){
    $(".line").click(function() {
        $(".line").animate({height:20},500);
        $("[id^=link]").slideUp();
        $(this).animate({height:108},500);
        $($(this).attr("href")).delay(500).slideDown();
        return false;
    });
});

In the HTML you just need to be sure to change the <a href> to resemble this: <a href="#link1">, with the href being the ID of the associated div preceded by a #. Code seen here: http://jsfiddle.net/Skooljester/DpffX/5/

Upvotes: 0

Ram
Ram

Reputation: 144689

you can use data-* attribute:

<a href="#" data-link="1" class="line">link1 |</a>
<a href="#" data-link="2" class="line">link2 |</a>
<a href="#" data-link="3" class="line">link3 |</a>
<a href="#" data-link="4" class="line">link4 |</a>

$(document).ready(function(){
    $(".line").toggle(function(){
           var w = $(this).data('link');
           $(this).animate({height:108},500);
           $("#link"+w).delay(500).slideDown();
        },function(){
           var w = $(this).data('link');
           $(this).delay(500).animate({height:20},500);
           $("#link"+w).slideUp();
    });
});

DEMO

Upvotes: 1

Related Questions