user2279302
user2279302

Reputation:

Tabbed content won't work with multiple divs

I'm new to Javascript and am working on the following:

$('.tabs-holder li').click(function () {
    var tabID = $(this).attr('data-tab-id');
    $(this).closest('.tabbed-content').find('.tabs-holder li').removeClass('active');
    $(this).addClass('active');
    $(this).closest('.tabbed-content').find('.content-holder').children('.tab-content').removeClass('active').siblings('.tab-content[data-tab-id=' + tabID + ']').addClass('active');
});

I'm trying to get it to work on all divs with a data-tab-id of the same value, but it's only acting on the one div.

JSFiddle here http://jsfiddle.net/dynaf9pc/8/

Upvotes: 1

Views: 142

Answers (2)

jmore009
jmore009

Reputation: 12923

That content container you're trying to target is a sibling of .tabbed-content so you need to back out to the parent .tabbed-content and then navigate to its sibling like so:

   $(this).closest(".tabbed-content")
          .siblings(".content-holder")
          .find('.tab-content[data-tab-id=' + tabID + ']')
          .addClass('active')
          .siblings()
          .removeClass('active');

Also I refactored some of your JS that was redundant and made it shorter by chaining your selectors:

FIDDLE

Upvotes: 1

HelpNeeder
HelpNeeder

Reputation: 6480

You are not iterating through the elements. If you add each(), it will go through multiple div's that it will find.

$('.tabs-holder li').click(function () {
    var tabID = $(this).attr('data-tab-id');
    $(this).closest('.tabbed-content').find('.tabs-holder li').removeClass('active');
    $(this).addClass('active');
    $(this).closest('.tabbed-content')
        .find('.content-holder')
        .children('.tab-content')
        .removeClass('active')
        .siblings('.tab-content[data-tab-id=' + tabID + ']')
        .each(function() {
            $(this).addClass('active');
        })
});

Upvotes: 0

Related Questions