user14696
user14696

Reputation: 677

Jquery toggle not working / 2 classes (multiple class selector?)

My code is here: http://jsfiddle.net/GwUmb/4/

    $(document).ready(function(){
    $(".trigger,.trigger-2").click(function(){
        $(".panel,.panel-2").toggle("fast");
        $(this).toggleClass("active");
        return false;
    });
});

I've been struggling to load panel-2 from trigger-2...I notice that .trigger and .panel behave (somewhat) as expected (I notice some css-style weirdness).

If I remove the .panel-2 and the .trigger-2 the code behaves perfectly...but otherwise it doesn't.

I was trying to replicate what I read here: http://www.w3schools.com/jquery/sel_multiple_classes.asp .

Upvotes: 1

Views: 646

Answers (2)

lukeocom
lukeocom

Reputation: 3243

Another option for you is to use a single class name for your links/containers. I have cleaned up your code a little bit and provided a hover function to display your links. It should be a good starting point for you. A CSS approach using lists may be an even easier approach...

working example is here http://jsfiddle.net/GwUmb/11/

updated jQuery:

$(document).ready(function() {

                //global var to hold the current selected link
                var $link;

                $('.trigger').hover(function() {
                    $link = $(this);
                    //get position of clicked link
                    var linkPos = $link.position();
                    //position & display this links panel
                    $link.toggleClass("active");
                    $link.siblings('.panel').css({
                        'top' : linkPos.top
                    }).fadeIn(600);

                }, function() {//hide the panel on mouseout
                    $link.siblings('.panel').slideUp(600);
                    $link.removeClass('active');
                });

            });
            // end ready

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191779

The issue here is that no matter which trigger you click, both (or all) panels will be activated because you are selecting them both and calling .toggle on them. There are many ways to solve this such as storing the corresponding index of the panel on the trigger as data, or using the index. The latter may work well for you.

$(".trigger").click(function(e) {
    $(".panel").eq($(this).index(".trigger")).toggle("fast");
    $(this).toggleClass("active");
    e.preventDefault();
});

http://jsfiddle.net/GwUmb/6/

Upvotes: 2

Related Questions