Skip to content Skip to sidebar Skip to footer

Hide/show Different Links

I have a script that works on one link on jsfiddle. I have two links. Link one is 'Link one' the other one is 'Link two' you can see the code on jsfiddle = http://jsfiddle.net/lam

Solution 1:

Get the index from the clicked anchor, in this case that would have to be the wrapping li, and then use that index to select the right one in the collection of .test elements. No need to recreate the slideUp/Down already built into jQuery.

$(function() {
    var elems = $('.test').hide();

    $('a').click(function(e) {
        e.preventDefault();
        var selEl = elems.eq($(this).closest('li').index());
        selEl.slideToggle(600);
        elems.not(selEl).slideUp(600);
    });
});​

FIDDLE

Solution 2:

Although I like @adeneo's answer, I prefer this method using selectors rather than elements :

$(".test").hide();
$('.list a').each(function(i) {
    $(this).on("click", function() {
        $(".test").slideUp(0).eq(i).slideDown(400, function() {
            $(".close a").on("click", function() {
                $(".test").slideUp();
            }); // on click close
        }); // after slideDown (shown div)
    }); // on click link
}); // each 

The only condition is that there should be the same number of links (list items) as the number of div to be shown and in the same order.

See JSFIDDLE

Solution 3:

Give class to the anchor tag,

<ahref="#"class="link1">Link 01</a><ahref="#"class="link2">Link 02</a>

give the appropriate class as id to the div tag as

<div id="link1" class="test">
...
...
</div>

<div id="link2" class="test">
...
...
</div>

Do the below change in your javascript function

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

         $('div.test').hide();
        var showDivClass = $(this).attr("class");
        $("#" + showDivClass).show().animate({
                height: height
            }, {
                duration: 500
            });
        $('div.test').not("#" + showDivClass).hide().animate({
                height: 0
            }, {
                duration: 500
            });

    });

Update and test.

Solution 4:

Please provide the id to anchor tag which will be same as the class you need to show/hide. and replace the $div with the id tag

Post a Comment for "Hide/show Different Links"