Keefer Keefer - 27 days ago 10
Javascript Question

Refactoring jQuery to Affect N Number of anchor and div pairs

I've got an unknown number pairs of links and divs that I hide and show based on clicks. I know there's got to be a better way to do this — refactoring my code to take the numeral part and looping through them from 01 to N.

While the example below has 4 pairs of anchor tags, and divs, the number could be anywhere from 1 to 100 (or more)

HTML markup:

<a class="bioImg bioImg01"></a>
<a class="bioImg bioImg02"></a>
<a class="bioImg bioImg03"></a>

<div class="bioContainer bioContainer01">
</div>

<div class="bioContainer bioContainer02">
</div>

<div class="bioContainer bioContainer03">
</div>

<a class="bioImg bioImg04"></a>

<div class="bioContainer bioContainer04"></div>


JavaScript (jQuery):
This is the part that I know is inefficient — just don't have the experience and vocabulary to do it properly

// Click events for Bio page
if ($('.bioImg').length > 0) {
$('.bioImg').click(function() {
$('.bioImg').removeClass('active');
$(this).addClass('active');
});
}

if ($('.bioContainer').length > 0) {
$('.bioImg01').click(function() {
$('.bioContainer').hide();
$('.bioContainer01').fadeToggle();
});
}

if ($('.bioContainer').length > 0) {
$('.bioImg02').click(function() {
$('.bioContainer').hide();
$('.bioContainer02').fadeToggle();
});
}

if ($('.bioContainer').length > 0) {
$('.bioImg03').click(function() {
$('.bioContainer').hide();
$('.bioContainer03').fadeToggle();
});
}

if ($('.bioContainer').length > 0) {
$('.bioImg04').click(function() {
$('.bioContainer').hide();
$('.bioContainer04').fadeToggle();
});
}

Answer

You can use indexing to match these groups together. Unless you have special css it is rare to need unique class names for each one in a group of same type elements

var $bioImg = $('.bioImg').click(function() {
  // get index of current bioImg within collection 
  var index = $bioImg.index(this);
  $bioImg.removeClass('active');
  $(this).addClass('active');
  // hide all containers and fade in matching indexed one
  $('.bioContainer').hide().eq(index).fadeIn();
});
Comments