tags:

views:

127

answers:

1

Hi i have a simple accordion set up with jQuery with the HTML structure of:

<div  class="accordion_headings">Title 1</div>
<div class="accordion_child">Accordion Content 1</div>

<div  class="accordion_headings">Title 2</div>
<div class="accordion_child">Accordion Content 2</div>

and this script

$('div.accordion_headings').click(function() {
 $('div.accordion_child').slideUp('normal'); 
 $(this).next().slideDown('normal');
});

$("div.accordion_child").hide();

Now I also want another div on the page to be swapped out when clicking on any of those accordion links so I added more classes to the links

<div  class="accordion_headings link1">Title 1</div>
<div class="accordion_child">Accordion Content 1</div>

<div  class="accordion_headings link2">Title 2</div>
<div class="accordion_child">Accordion Content 2</div>

and added the div content that I wanted to swap out

<div id="content_1" class="swap">Content 1</div>
<div id="content_2" class="swap">Content 1</div>

This is the script I came up with (after sniffing around Stack Oveflow)

$(document).ready(function () {

    var clickHandler = function (link) {
         $('.swap').hide();
         $('#content_' + link.data.id).show();
         $('.selected').removeClass('selected');
         $(this).attr('class','selected');
   }

   $('.link1').bind('click', {id:'1'} ,clickHandler);
   $('.link2').bind('click', {id:'2'} ,clickHandler);

});

Almost works.. however on clicking on the accordion it now removes the accordion_headings class and destroys my styling... the weird thing is the accordion still works ? Can someone please help me clean this up. Also how would I animate or use fade? Would I replace the hide and show with fadeIn fadeOut? Thanks.

+1  A: 

Instead of:

$(this).attr('class','selected');

use

$(this).addClass("selected");

I would also recommend you don't use naked class selectors (eg ".link1") as they're typically much slower than selectors with a tag attached. Here's a suggested change:

$(document).ready(function() {
  var clickHandler = function(evt) {
    $('div.swap').hide();
    $('#content_' + link.data.id).show();
    $('div.selected').removeClass('selected');
    $(this).addClass("selected");
  }
  $('div.link1').bind('click', {id:'1'}, clickHandler);
  $('div.link2').bind('click', {id:'2'}, clickHandler);
});
cletus
Great! Thank you cletus!
zac