Skip to content Skip to sidebar Skip to footer

.slideToggle() On One DIV Instead Of All Others With Same Class

I'm trying to create a menu with DIVs for Appetizers, Soups, etc. I use paragraph tabs as my toggler. All of my togglers have identical classes of 'toggle'. All of the DIV areas ha

Solution 1:

You can target an item relative to the one that was clicked on like this:

$(document).ready(function(){
    $('.toggle').click(function(){
        $(this).prev('.selection').slideToggle("slow");
    });
});

This will get the clicked on .toggle item and get the previous .selection item and slideToggle just that one.

You can see it work here: http://jsfiddle.net/jfriend00/2zJ8z/

I would suggest improving it so you can click on the .selection item to make it go away as this makes toggling to explore with the mouse a little easier:

$(document).ready(function(){
    $('.toggle').click(function(){
        $(this).prev('.selection').slideToggle("slow");
    });

    $('.selection').click(function(){
        $(this).slideToggle("slow");
    });
});​

You can see this minor enhancement here: http://jsfiddle.net/jfriend00/JrhNz/

If you want any other open ones to close when you open a new one, you could use this:

$(document).ready(function(){
    $('.toggle').click(function(){
        var prev = $(this).prev('.selection');
        $(this).siblings('.selection').not(prev).slideUp("slow");
        prev.slideToggle("slow");
    });

    $('.selection').click(function(){
        $(this).siblings('.selection').slideUp("slow");
        $(this).slideToggle("slow");
    });
});​

Demo of this option here: http://jsfiddle.net/jfriend00/JrhNz/6/


Solution 2:

I think you're looking for .prev():

$('.toggle').click(function(){
    $(this).prev('.selection').slideToggle("slow");
});

Post a Comment for ".slideToggle() On One DIV Instead Of All Others With Same Class"