Question

Im very new to the Jquery language and need to get something done for a site. I want to be able to click on any of the DIVs to hide or unhide. At the moment only the first DIV does that. My code only works when I change the div id="boxes" to class="boxes" but I can only use the former. Can you help me to fix this please?

Jquery

$(document).ready(function () {
      $(".hidearea").toggle();
      $(".moreinfo").text('More Info');
      $("#boxes").click(function () {

          var index = $(this).index(),

              newTargets = $('.hidearea').eq(index);
              ancTargets = $('.moreinfo').eq(index);
          $(ancTargets).text($(ancTargets).text() == 'More Info' ? 'Less Info' : 'More Info');
          newTargets.slideToggle(300)
          return false;
      })
  });

HTML

<div id="boxwrap">

  <div id="boxes" style="width:400px; min-height:200px; border:thin solid black;"> Visible area    
    <a class="moreinfo" href=""></a>    
    <div class="hidearea" style="width:200px; height:200px; border:thin solid red;">Hidden area     
    </div>  
  </div>

  <div id="boxes" style="width:400px; min-height:200px; border:thin solid black;"> Visible area    
    <a class="moreinfo" href=""></a>    
    <div class="hidearea" style="width:200px; height:200px; border:thin solid red;">Hidden area     
    </div>  
  </div>

  <div id="boxes" style="width:400px; min-height:200px; border:thin solid black;"> Visible area    
    <a class="moreinfo" href=""></a>    
    <div class="hidearea" style="width:200px; height:200px; border:thin solid red;">Hidden area     
    </div>  
  </div>

</div>
Was it helpful?

Solution

As you probably know, an ID must be unique per element and can only be used at most once within a document. You're violating those rules by having the same ID on multiple elements (in the same document).

That being said, if you aren't able to change the ID's to classes, you can use an attribute selector:

$(document).ready(function () {
  $(".hidearea").toggle();
  $(".moreinfo").text('More Info');
  $("[id='boxes']").click(function (e) {
      e.preventDefault();
      var index = $(this).index(),
          newTargets = $('.hidearea').eq(index),
          ancTargets = $('.moreinfo').eq(index);
      $(ancTargets).text($(ancTargets).text() == 'More Info' ? 'Less Info' : 'More Info');
      newTargets.slideToggle(300)
      return false;
  })
});

jsfiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top