Search code examples
javascriptjquerydom-manipulation

How do I bind each child of one element to the child of another element?


There is a bootstrap carousel that is changing automatically:

<div id="carousel">
  <div class="active"> </div>
  <div class="">       </div>
  <div class="">       </div>
  <div class="">       </div>
</div>

Only one div is set to active at a time, and it cycles through like that.
How can I bind all of carousel's children to another element so that it can set it's specific child to be active as well.

For example:

<div id="copy-cat">
  <li class=""> </li>
  <li class=""> </li>
  <li class=""> </li>
  <li class=""> </li>
</div>

<div id="carousel">
  <div class="active"> </div>
  <div class="">       </div>
  <div class="">       </div>
  <div class="">       </div>
</div>

How can I bind copy-cat to have the same child active as carousel? Keep in mind, I don't want to copy all of the class attributes- just detect that one is active, and set that same numbered child to active also.


Solution

  • I'd use Bootstrap's slid event callback:

    http://jsfiddle.net/isherwood/6xF7k/

    $('#carousel').on('slid.bs.carousel', function () {
        // get the index of the currently active panel
        var myIndex = $(this).find('div.active').index();
    
        // set the element with that index active, deactivating the others
        $('#copy-cat').find('li').removeClass('active').eq(myIndex)
            .addClass('active');
    })
    

    Notice that I changed #copy-cat to ul to make it valid HTML.

    http://getbootstrap.com/javascript/#carousel-usage