andy nightingale
andy nightingale

Reputation: 21

Simpler way of coding this

On this page: of my website

I have this jQuery, but it seems a bit long winded.

<script type="text/javascript">
$(document).ready(function(){
$("p").hide();
$("#lastfmrecords").hide();
$("h2.btn1 a").click(function(){
$("ol.btn1>*").toggle(400);
});
$("h2.btn2 a").click(function(){
$("ol.btn2>*").toggle(400);
});
$("h2.btn3 a").click(function(){
$("ol.btn3>*").toggle(400);
});
$("h2.btn4 a").click(function(){
$("ol.btn4>*").toggle(400);
});
$("h2.btn5 a").click(function(){
$("ol.btn5>*").toggle(400);
});
  $("h2.btn6 a").click(function(){
$("ol.btn6>*").toggle(400);
});
  $("h2.btn7 a").click(function(){
$("ol.btn7>*").toggle(400);
});
});
</script>

<h2 class="btn5"><a href="#">FAVOURITE Books</a></h2>
    <ol class="btn5">
      <p>Freakonomics, Bad Science, A Brief History of Nearly Everything, 100 years of Solitude, On Chesil Beach</p>
    </ol>

Then I have 7 ordered lists with those names, no. 5 above (btn1 - btn7) which toggle when I click on the H2 title that corresponds. All works fine, but is there a way of compacting the jQuery?

Upvotes: 0

Views: 50

Answers (2)

Andreas Wong
Andreas Wong

Reputation: 60516

For one, you can wrap the h2's under a div and have your <a> rel to the class of the ol you wanna toggle

<div class="wrapper">
   <h2><a rel="btn1"> </a><ol class="btn1">...</ol>
   ...
   <h2><a rel="btn7"> </a><ol class="btn7">...</ol>
</div>

then do it as below, note that you also might want to prevent the browser to scroll to the top by passing in event object as the function argument and call .preventDefault()

$('.wrapper h2 a').click(function(e) { 
   e.preventDefault(); 
   $('ol.' + $(this).attr('rel') + ' p').toggle(400); 
});

EDIT: If you'd prefer to keep your layout as is, you can also do something like:

$('h2[class^=btn] > a').click(function(e) {
   e.preventDefault();
   $('ol.' + $(this).parent().attr('class') + ' > p').toggle(400);
});

Upvotes: 0

Aistina
Aistina

Reputation: 12683

A for loop seems like an obvious solution.

$(document).ready(function() {
  $('ol').hide();
  for (var i = 1; i <= 7; ++i) {
    $('h2.btn' + i + ' a').click(function() {
      $('ol.btn' + i + ' > *').toggle(400);
    });
  }
});

Upvotes: 1

Related Questions