Search code examples
jqueryjquery-eventsjquery-ui-accordion

Add Current/Active State to Two Objects


I'm trying to change the active state of an accordion that has a second form of navigation in the sidebar to control it. I have the active states working for both the accordion and the sidebar buttons that control it but I want to have the active state for the accordion and the button that corresponds to it both to have the current state applied once one or the other is clicked... Here's the current js code for it:

jQuery(function($){
  var headerAnchors = $('.btn a').click(function(){
    headerAnchors.removeClass('current');
    $(this).addClass('current');
  });
});

jQuery(function($){
  var headerAnchors = $('.accordion h2 a').click(function(){
    headerAnchors.removeClass('current');
    $(this).addClass('current');
  });
});

and the corresponding html:

<div class="accordion">
    <section id="item1">
        <h2><a href="#item1">Item 1 Title</a></h2>
        <div>
            <p>Item 1 content</p>
        </div>
    </section>
    <section id="item2">
        <h2><a href="#accordion2">Item 2 Title</a></h2>
        <div>
            <p>Item 2 content</p>
        </div>
    </section>
</div>

<div id="sidebar-nav">
    <ul>
        <li class="btn"><a href="#item1"><img src="button1.jpg" /></a></li>
        <li class="btn"><a href="#item2"><img src="button2.jpg" /></a></li>
    </ul>
</div>

Here is one of the pages in question so that you can see better what I'm trying to accomplish: http://64.82.220.37/CreativeCompounds/exclusive-ingredients.php

You will notice that when an accordion item is clicked it turns blue and when a button in the sidebar is clicked the left end turns blue but I want the corresponding accordion and button to both turn blue.


Solution

  • Try this

    jQuery(function($){
      var headerAnchors = $('.btn a, .accordion h2 a').on('click', function() {
        $('.current').removeClass('current');
        var anchorID = $(this).attr('href');
        $('a[href="'+anchorID+'"]').addClass("current");
      });
    });